Easy-Es Documentation

repository·main·Indexed 23 days ago

https://github.com/dromara/easy-es

An enhanced toolkit for the Elasticsearch RestHighLevelClient that simplifies development by providing a Lambda-style API and MySQL-like syntax for complex queries. It features automated index management, smart field type inference, and a DSL for configuring index settings, mappings, and parent-child join fields via the Index interface. Easy-Es significantly reduces boilerplate code compared to the standard RestHighLevelClient.

Tokens
2.6K
Snippets
4
Records
10
Agent score
79%

What's inside Easy-Es

  1. Overview of Easy-Es

    main

    Easy-Es is an open-source framework designed to simplify Elasticsearch operations. It provides an automated, intelligent index management system that handles the entire lifecycle of an index (creation, updates, and data migration) without downtime or manual intervention.

    Key features include:

    • Automated Index Management: Developers don't need to manually manage index lifecycle steps.
    • Smart Field Type Inference: Automatically determines if a query needs a .keyword suffix based on context.
    • MySQL-like Syntax: Allows developers to use familiar MySQL-style logic to interact with Elasticsearch.
    • Lambda-style Programming: Supports elegant, type-safe chainable programming via Lambda expressions.
    • Reduced Boilerplate: Significantly reduces the amount of code required compared to using the native RestHighLevelClient (typically by 3-8x).
  2. Install Easy-Es via Maven or Gradle

    main

    To use Easy-Es in your project, add the easy-es-boot-starter dependency to your build configuration. This starter is designed for seamless integration, particularly with Spring Boot environments.

    <dependency>
        <groupId>org.dromara.easy-es</groupId>
        <artifactId>easy-es-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>
    compile group: 'org.dromara.easy-es', name: 'easy-es-boot-starter', version: 'Latest Version'
  3. Configure Easy-Es Mappers

    main

    To enable Easy-Es functionality for a specific entity, create a mapper interface that extends BaseMapper<T>. This allows you to use the enhanced query capabilities provided by the toolkit.

    public interface DocumentMapper extends BaseMapper<User> {
    }
  4. Compare Easy-Es query syntax with RestHighLevelClient

    main

    Easy-Es provides a high-level abstraction that drastically reduces code complexity. While a standard RestHighLevelClient query requires manual construction of SearchRequest, BoolQueryBuilder, and manual JSON parsing of hits, Easy-Es allows you to perform the same operation in a single line using a Lambda-style wrapper.

    // Using Easy-Es: Only 1 line of code
    List<Document> documents = documentMapper.selectList(EsWrappers.lambdaQuery(Document.class).eq(Document::getTitle, "传统功夫").eq(Document::getCreator, "码保国"));
    // Traditional way (RestHighLevelClient): Requires ~19 lines of code
    String indexName = "document";
    SearchRequest searchRequest = new SearchRequest(indexName);
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    TermQueryBuilder titleTerm = QueryBuilders.termQuery("title", "传统功夫");
    TermsQueryBuilder creatorTerm = QueryBuilders.termsQuery("creator", "码保国");
    boolQueryBuilder.must(titleTerm);
    boolQueryBuilder.must(creatorTerm);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(boolQueryBuilder);
    searchRequest.source(searchSourceBuilder);
    try {
         SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
         List<Document> documents = Optional.ofNullable(searchResponse)
                .map(SearchResponse::getHits)
                .map(SearchHits::getHits)
                .map(hit->Document document = JSON.parseObject(hit.getSourceAsString(),Document.class))
                .collect(Collectors.toList());
    } catch (IOException e) {
         e.printStackTrace();
    }
  5. Perform queries using LambdaEsQueryWrapper

    main

    Easy-Es allows you to write Elasticsearch queries using a MySQL-like syntax via a Lambda-style API. This significantly reduces the boilerplate code required compared to the standard RestHighLevelClient.

    LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
    wrapper.eq(Document::getTitle,"Hello World")
           .eq(Document::getCreator,"Guy");
    List<Document> documentList = documentMapper.selectList(wrapper);
  6. Compare Easy-Es syntax with MySQL and Elasticsearch DSL

    main

    Easy-Es maps common MySQL operators to Elasticsearch DSL. Use the following mapping as a reference for constructing queries:

    MySQLEasy-EsEs-DSL / Java API
    andandmust
    ororshould
    =eqterm
    !=neboolQueryBuilder.mustNot(queryBuilder)
    >gtQueryBuilders.rangeQuery('field').gt()
    >=ge.rangeQuery('field').gte()
    <lt.rangeQuery('field').lt()
    <=le.rangeQuery('field').lte()
    like '%field%'likeQueryBuilders.wildcardQuery(field, *value*)
    not like '%field%'notLikemust not wildcardQuery(field, *value*)
    like '%field'likeLeftQueryBuilders.wildcardQuery(field, value*)
    like 'field%'likeRightQueryBuilders.wildcardQuery(field, *value)
    betweenbetweenQueryBuilders.rangeQuery('field').from(xx).to(xx)
    notBetweennotBetweenmust not rangeQuery('field').from(xx).to(xx)
    is nullisNullmust not existsQuery(field)
    is notNullisNotNullexistsQuery(field)
    inintermsQuery("field", xx)
    not innotInmust not termsQuery("field", xx)
    group bygroupByAggregationBuilders.terms()
    order byorderByfieldSortBuilder.order(ASC/DESC)
    minminAggregationBuilders.min
    maxmaxAggregationBuilders.max
    avgavgAggregationBuilders.avg
    sumsumAggregationBuilders.sum
    order by xxx ascorderByAscfieldSortBuilder.order(SortOrder.ASC)
    order by xxx descorderByDescfieldSortBuilder.order(SortOrder.DESC)
    -matchmatchQuery
    -matchPhraseQueryBuilders.matchPhraseQuery
    -matchPrefixQueryBuilders.matchPrefixQuery
    -queryStringQueryQueryBuilders.queryStringQuery
    select *matchAllQueryQueryBuilders.matchAllQuery()
    -highLightHighlightBuilder.Field
  7. Configure parent-child join fields

    main

    To implement parent-child relationships in Elasticsearch, use the join method on the Index interface. This configures a field of type join.

    • join(String column, String parentName, String childName): Specifies the field name, the name of the parent type, and the name of the child type.
    • join(R column, String parentName, String childName): Uses an entity property reference for the column name.
  8. Configure index settings and mappings with the Index interface

    main

    The Index<Children, R> interface provides a DSL for configuring Elasticsearch index creation, including index names, settings, mappings, aliases, and join types (parent-child relationships). It supports both using entity property references (type R) and raw string column names (type String).

    Key Capabilities:

    • Index Name: Set one or more index names using indexName(String... indexNames).
    • Settings: Configure shards, replicas, and maxResultWindow via settings(Integer shards, Integer replicas, Integer maxResultWindow), or provide a custom IndexSettings.Builder.
    • Mappings: Define field types, analyzers, date formats, field data (for aggregations), and boost values using various overloaded mapping(...) methods.
    • Aliases: Create an alias for the index using createAlias(String aliasName).
    • Join Fields: Define parent-child relationships using join(String column, String parentName, String childName).
  9. Configure index settings and shards/replicas

    main

    Use the Index interface to define the physical configuration of an index.

    • indexName(String... indexNames): Sets the target index name(s).
    • settings(Integer shards, Integer replicas, Integer maxResultWindow): Sets the number of primary shards, replica shards, and the maximum result window.
    • settings(IndexSettings.Builder settings): Allows passing a custom Elasticsearch IndexSettings.Builder for advanced configurations.
  10. Configure field mappings in the Index DSL

    main

    The mapping method is highly overloaded to allow granular control over field properties. You can use either a property reference (of type R) or a String representing the column name.

    Common parameters include:

    • fieldType: The Elasticsearch field type (using org.dromara.easyes.annotation.rely.FieldType).
    • analyzer / searchAnalyzer: Custom analyzers for indexing and searching.
    • dateFormat: The date format string.
    • fieldData: Boolean to enable fielddata (useful for text aggregations).
    • boost: A double value to adjust the field's importance in scoring.

    Common Mapping Signatures:

    • mapping(R column, FieldType fieldType)
    • mapping(String column, FieldType fieldType, Boolean fieldData)
    • mapping(String column, FieldType fieldType, String analyzer, String searchAnalyzer)
    • mapping(String column, FieldType fieldType, String analyzer, String searchAnalyzer, String dateFormat, Boolean fieldData, Double boost)