### Query Document from Easy-Es Index (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/04414d This example demonstrates how to query specific data from an Elasticsearch index based on conditions. The syntax is similar to MyBatis-Plus, supporting both chained and non-chained query styles for flexibility. ```Java @Test public void testSelect() { // 测试查询 写法和MP一样 可以用链式,也可以非链式 根据使用习惯灵活选择即可 String title = "老汉"; Document document = EsWrappers.lambdaChainQuery(documentMapper) .eq(Document::getTitle, title) .one(); System.out.println(document); Assert.assertEquals(title,document.getTitle()); } ``` -------------------------------- ### Easy-Es Boot Starter Dependency Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d This snippet provides the necessary dependency configurations for integrating Easy-Es Boot Starter into your project, supporting both Maven and Gradle build systems. It includes a placeholder for the latest version and notes on managing potential dependency conflicts. ```Maven org.dromara.easy-es easy-es-boot-starter ${Latest Version} ``` ```Gradle compile group: 'org.dromara.easy-es', name: 'easy-es-boot-starter', version: 'Latest Version' ``` -------------------------------- ### Test Update Operation with Easy-Es (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d Shows two scenarios for updating data in Easy-Es, analogous to a MySQL UPDATE operation. The first case demonstrates updating a document by its known ID. The second case illustrates updating documents based on a specified condition using `LambdaEsUpdateWrapper`. ```Java @Test public void testUpdate() { // 测试更新 更新有两种情况 分别演示如下: // case1: 已知id, 根据id更新 (为了演示方便,此id是从上一步查询中复制过来的,实际业务可以自行查询) String id = "krkvN30BUP1SGucenZQ9"; String title1 = "隔壁老王"; Document document1 = new Document(); document1.setId(id); document1.setTitle(title1); documentMapper.updateById(document1); // case2: id未知, 根据条件更新 LambdaEsUpdateWrapper wrapper = new LambdaEsUpdateWrapper<>(); wrapper.eq(Document::getTitle,title1); Document document2 = new Document(); document2.setTitle("隔壁老李"); document2.setContent("推*技术过软"); documentMapper.update(document2,wrapper); // 关于case2 还有另一种省略实体的简单写法,这里不演示,后面章节有介绍,语法与MP一致 } ``` -------------------------------- ### Test Insert Operation with Easy-Es (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d Demonstrates how to insert a new document into Easy-Es, equivalent to a MySQL INSERT operation. It creates a Document object, sets its title and content, and then uses `documentMapper.insert()` to save it, returning the count of successful insertions. ```Java @Test public void testInsert() { // 测试插入数据 Document document = new Document(); document.setTitle("老汉"); document.setContent("推*技术过硬"); int successCount = documentMapper.insert(document); System.out.println(successCount); } ``` -------------------------------- ### Easy-Es Configuration in Spring Boot application.yml Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d This YAML snippet provides the essential configuration for Easy-Es in a Spring Boot `application.yml` file. It includes settings for compatibility mode, framework enablement, Elasticsearch connection address, username, and password. ```YAML easy-es: compatible: true # 兼容模式开关,默认为false,若您的es客户端版本小于8.x,务必设置为true才可正常使用,8.x及以上则可忽略此项配置 enable: true #默认为true,若为false则认为不启用本框架 address : 127.0.0.1:9200 # es的连接地址,必须含端口 若为集群,则可以用逗号隔开 例如:127.0.0.1:9200,127.0.0.2:9200 username: elastic #若无 则可省略此行配置 password: WG7WVmuNMtM4GwNYkyWH #若无 则可省略此行配置 ``` -------------------------------- ### Test Delete Operation with Easy-Es (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d Explains how to delete data from Easy-Es based on conditions, similar to a MySQL DELETE operation. This example specifically demonstrates deleting documents by a specified title using `LambdaEsQueryWrapper` to define the deletion criteria. ```Java @Test public void testDelete() { // 测试删除数据 删除有两种情况:根据id删或根据条件删 // 鉴于根据id删过于简单,这里仅演示根据条件删,以老李的名义删,让老李心理平衡些 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); String title = "隔壁老李"; wrapper.eq(Document::getTitle,title); int successCount = documentMapper.delete(wrapper); System.out.println(successCount); } ``` -------------------------------- ### Test Select Operation with Easy-Es (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d Illustrates how to query data from Easy-Es based on conditions, similar to a MySQL SELECT operation. It uses a lambda chain query with `EsWrappers.lambdaChainQuery()` to find a single document by its title and asserts the retrieved document's title. ```Java @Test public void testSelect() { // 测试查询 写法和MP一样 可以用链式,也可以非链式 根据使用习惯灵活选择即可 String title = "老汉"; Document document = EsWrappers.lambdaChainQuery(documentMapper) .eq(Document::getTitle, title) .one(); System.out.println(document); Assert.assertEquals(title,document.getTitle()); } ``` -------------------------------- ### Spring Boot Application Class with EsMapperScan Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d This Java code snippet shows a typical Spring Boot application entry point. It includes the `@EsMapperScan` annotation to specify the package where Easy-Es mappers are located, enabling the framework to scan and register them. ```Java @SpringBootApplication @EsMapperScan("com.xpc.easyes.sample.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### from Method Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/1cebb8 Specifies the starting offset for results, similar to the `m` in MySQL's `LIMIT m,n`. For example, `from(10)` starts querying from the 10th data entry. ```APIDOC from(Integer from) ``` -------------------------------- ### Document Mapper Interface for Easy-Es Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d This Java interface defines the mapper for the `Document` entity. It extends `BaseEsMapper`, providing standard CRUD operations for Elasticsearch documents through Easy-Es. ```Java public interface DocumentMapper extends BaseEsMapper { } ``` -------------------------------- ### Easy-ES searchAfter Pagination Example and Best Practices Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/0cf11e This example demonstrates the `searchAfterPage` method, a highly recommended approach for efficient pagination, especially with large datasets. It mandates specifying a unique sort rule (e.g., `id` or `uuid`) to ensure correct pagination and prevent errors. The `SAPageInfo` object facilitates retrieving subsequent pages by providing the `nextSearchAfter` cursor. ```Java @Test public void testSearchAfter() { LambdaEsQueryWrapper lambdaEsQueryWrapper = EsWrappers.lambdaQuery(Document.class); lambdaEsQueryWrapper.size(10); // 必须指定一种排序规则,且排序字段值必须唯一 此处我选择用id进行排序 实际可根据业务场景自由指定,不推荐用创建时间,因为可能会相同 lambdaEsQueryWrapper.orderByDesc(Document::getId); SAPageInfo saPageInfo = documentMapper.searchAfterPage(lambdaEsQueryWrapper, null, 10); // 第一页 System.out.println(saPageInfo); Assertions.assertEquals(10, saPageInfo.getList().size()); // 获取下一页 List nextSearchAfter = saPageInfo.getNextSearchAfter(); SAPageInfo next = documentMapper.searchAfterPage(lambdaEsQueryWrapper, nextSearchAfter, 10); Assertions.assertEquals(10, next.getList().size()); } ``` -------------------------------- ### Easy-ES Spring Annotation Configuration Example Source: https://www.easy-es.cn/pages/7ead0d/pages/a12489 This Java configuration class demonstrates how to set up Easy-ES in a Spring application using annotations. It defines EasyEsProperties for basic connection settings (e.g., Elasticsearch address) and EasyEsDynamicProperties for advanced multi-datasource configurations, allowing different mappers to connect to different Elasticsearch instances via @EsDS. ```Java import org.dromara.easyes.common.property.EasyEsDynamicProperties; import org.dromara.easyes.common.property.EasyEsProperties; import org.dromara.easyes.spring.annotation.EsMapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * spring不用xml配置的平替 * @author MoJie * @since 2.1.0 */ @Configuration @EsMapperScan("org.dromara.easyes.test.mapper") public class EasyEsSpringConfig { @Bean public EasyEsProperties easyEsProperties() { EasyEsProperties easyEsProperties = new EasyEsProperties(); // 以下是easy-es的配置项 easyEsProperties.setAddress("127.0.0.1:9200"); return easyEsProperties; } @Bean public EasyEsDynamicProperties easyEsDynamicProperties() { EasyEsDynamicProperties easyEsDynamicProperties = new EasyEsDynamicProperties(); // 多数据源配置 Map datasource = new HashMap<>(); // 这里你可以配置多个数据源,在mapper中可通过@EsDS("key")注解来指定数据源 easyEsDynamicProperties.setDatasource(datasource); return easyEsDynamicProperties; } } ``` -------------------------------- ### Java Example: Manual queryStringQuery Construction Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/1cebb8 Demonstrates how to manually construct a complex `queryString` using `StringBuilder` for the `queryStringQuery` API. This example combines multiple conditions (equality, text match, wildcard) with AND/OR logic, illustrating a flexible approach for dynamic query generation based on user input. ```Java @Test public void testQueryString() { LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); StringBuilder sb = new StringBuilder(); sb.append("(") .append("(") .append("creator.keyword") .append(":") .append("老王") .append(")") .append("AND") .append("(") .append("creator") .append(":") .append("隔壁") .append(")") .append(")") .append("OR") .append("(") .append("creator.keyword") .append(":") .append("*大猪蹄子*") .append(")"); // sb最终拼接为:((creator.keyword:老王)AND(creator:隔壁))OR(creator.keyword:*大猪蹄子*) ,可以说和MySQL语法非常相似了 wrapper.queryStringQuery(sb.toString()); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Java Easy-ES Pipeline Aggregation Example Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/b508b3 Demonstrates how to perform pipeline aggregations in Easy-ES, where subsequent aggregations operate on the results of previous ones. This example groups by creator and then finds the maximum star count within each group. ```Java @Test public void testAgg() { // 根据创建者聚合,聚合完在该桶中再次根据点赞数聚合 // 注意:指定的多个聚合参数为管道聚合,就是第一个聚合参数聚合之后的结果,再根据第二个参数聚合,对应Pipeline聚合 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.eq(Document::getTitle, "老汉") .groupBy(Document::getCreator) .max(Document::getStarNum); SearchResponse response = documentMapper.search(wrapper); System.out.println(response); } ``` -------------------------------- ### Easy-ES Configuration Strategy Details Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/9a3e4c Detailed explanations of the supported types and strategies for `id-type`, `field-strategy`, and `refresh-policy` within Easy-ES configuration. This section clarifies their behaviors, recommendations, and how they interact with global and annotation-based settings. ```APIDOC id-type: - auto: Automatically generated by ES. This is the default and recommended configuration. - uuid: System-generated UUID, then inserted into ES. (Not recommended) - customize: User-defined. In this mode, users can store any data type as the ES data ID, e.g., using MySQL auto-increment IDs as ES IDs. This mode can be enabled, or specified via the @TableId(type) annotation. field-strategy: - not_null: Non-null check. Fields are updated only if their value is not null. - not_empty: Non-empty check. Fields are updated only if their value is a non-empty string. - ignore: Ignore check. Fields will be updated regardless of their value. - Note: After configuring a global strategy, you can still configure individual classes with personalized settings via annotations. Annotation configurations have higher priority than global configurations. refresh-policy: - none: Default policy, no data refresh. - immediate: Immediate refresh. This incurs significant performance overhead and is suitable for scenarios requiring high data real-time accuracy. - wait_until: After the request submits data, it waits for the data to complete refreshing (1 second) before the request ends. Moderate performance overhead. ``` -------------------------------- ### Easy-ES @HighLight Annotation Reference Source: https://www.easy-es.cn/pages/7ead0d/pages/9ba44a Detailed documentation for the `@HighLight` annotation, including its purpose, usage location, example scenarios, and a table of its configurable attributes with types, default values, and descriptions. Also includes details on `HighLightTypeEnum`. ```APIDOC @HighLight Annotation Description: Highlighting annotation Usage Location: Fields in entity classes that need to be highlighted in queries Example Scenario: For example, inputting keyword "老汉" for query, expecting content containing "老汉" to be displayed in red or bold. Attributes: - mappingField: Type: String Required: No Default: "" Description: Name of the field to map the highlighted content to. For example, if you want to assign the highlighted content "老汉" to the field 'pushCar', you can specify this attribute as 'pushCar'. - fragmentSize: Type: int Required: No Default: 100 Description: Length of the highlighted field snippet. Default is 100. - numberOfFragments: Type: int Required: No Default: -1 Description: Number of highlighted fragments to return from the search. Default is all. - preTag: Type: String Required: No Default: < em > Description: Highlight tag. Highlighted content will be after preTag. - postTag: Type: String Required: No Default: < /em > Description: Highlight tag. Highlighted content will be before postTag. - highLightType: Type: HighLightTypeEnum Required: No Default: UNIFIED Description: Type of highlighting strategy. - requireFieldMatch: Type: boolean Required: No Default: true Description: Whether highlighted content needs to match the query field. Default is true. When false, non-query fields containing highlighted content will also be highlighted. HighLightTypeEnum: - UNIFIED: General highlighting strategy, default when no specific configuration. This strategy breaks text into sentences, scores individual sentences using BM25 algorithm, supports precise phrase and multi-term (fuzzy, prefix, regex) highlighting. - PLAIN: Standard highlighting strategy, uses Lucene's standard Lucene highlighter. - FVH: Fast vector highlighter (Fast vector strategy). ``` -------------------------------- ### Easy-ES Java: Field-Specific Prefix Match Query Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Demonstrates `prefixQuery` for finding documents where the value of a specific field starts with a given prefix. For example, searching for '隔壁' (next door) in the 'creator' field will find documents created by '隔壁老王' (Old Wang Next Door) or '隔壁老汉' (Old Man Next Door). ```Java @Test public void prefixQuery() { // Query all data where the creator starts with "隔壁" (next door), e.g., '隔壁老王' or '隔壁老汉' can all be found LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.prefixQuery(Document::getCreator, "隔壁"); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Specify Query Start Position with from() in Easy-ES Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/1c503d The `from` method sets the starting offset for a query, similar to the 'm' parameter in MySQL's `LIMIT (m,n)`. It defines from which data entry the results should begin. ```APIDOC from(Integer from) ``` -------------------------------- ### Easy-ES Java: Match All Documents Query Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Shows how to use `matchAllQuery` to retrieve all documents from the index, functioning similarly to a `SELECT ALL` operation in SQL databases. ```Java @Test public void testMatchAllQuery() { // Query all data, similar to MySQL select all. LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.matchAllQuery(); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Easy-Es Index Creation Test Source: https://www.easy-es.cn/pages/7ead0d/pages/04414d This Java test method demonstrates how to programmatically create an Elasticsearch index using Easy-Es. It calls `documentMapper.createIndex()` which automatically generates the index based on the entity class and its annotations, asserting the success of the operation. ```Java @Test public void testCreateIndex() { // 测试创建索引,框架会根据实体类及字段上加的自定义注解一键帮您生成索引 需确保索引托管模式处于manual手动挡(默认处于此模式),若为自动挡则会冲突 boolean success = documentMapper.createIndex(); Assertions.assertTrue(success); } ``` -------------------------------- ### Easy-ES Basic Connection Configuration Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/9a3e4c Essential configuration for Easy-ES, required for project startup. It defines the Elasticsearch connection address, schema (http/https), and optional username/password for authentication. ```yaml easy-es: enable: true # Whether to enable EE auto-configuration address : 127.0.0.1:9200 # ES connection address + port, format must be ip:port, if it's a cluster, use commas to separate schema: http # Defaults to http username: elastic # If no account password, this line can be omitted password: WG7WVmuNMtM4GwNYkyWH # If no account password, this line can be omitted ``` -------------------------------- ### Java: Basic Statistical Aggregations in Easy-ES Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/ce1922 Provides examples of common statistical aggregations like `min()`, `max()`, `avg()`, and `sum()` for calculating minimum, maximum, average, and sum values. ```Java // 求最小值 wrapper.min(); // 求最大值 wrapper.max(); // 求平均值 wrapper.avg(); // 求和 wrapper.sum(); ``` -------------------------------- ### Easy-ES Index Query Usage Examples Source: https://www.easy-es.cn/pages/7ead0d/pages/e8b9ad Demonstrates how to check if an index exists and how to retrieve its detailed information, including mappings, using the Easy-ES API. ```Java @Test public void testExistsIndex() { // 测试是否存在指定名称的索引 String indexName = Document.class.getSimpleName().toLowerCase(); boolean existsIndex = documentMapper.existsIndex(indexName); Assertions.assertTrue(existsIndex); } ``` ```Java @Test public void testGetIndex() { GetIndexResponse indexResponse = documentMapper.getIndex(); // 这里打印下索引结构信息 其它分片等信息皆可从indexResponse中取 indexResponse.getMappings().forEach((k, v) -> System.out.println(v.getSourceAsMap())); } ``` -------------------------------- ### Easy-ES Index Creation Usage Examples Source: https://www.easy-es.cn/pages/7ead0d/pages/e8b9ad Demonstrates various ways to create indexes using the Easy-ES API, including simple creation based on entity, creation with a specified index name, and advanced creation using a wrapper for custom mappings, settings, aliases, and parent-child relationships. ```Java /** * 方式1 */ @Test public void testCreateIndexByEntity() { // 绝大多数场景推荐使用 简单至上 documentMapper.createIndex(); } ``` ```Java /** * 方式2 */ @Test public void testCreateIndexByEntity() { // 适用于定时任务按日期创建索引场景 String indexName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); documentMapper.createIndex(indexName); } ``` ```Java /** * 方式3 */ @Test public void testCreateIndex() { // 复杂场景使用 LambdaEsIndexWrapper wrapper = new LambdaEsIndexWrapper<>(); // 此处简单起见 索引名称须保持和实体类名称一致,字母小写 后面章节会教大家更如何灵活配置和使用索引 wrapper.indexName(Document.class.getSimpleName().toLowerCase()); // 此处将文章标题映射为keyword类型(不支持分词),文档内容映射为text类型(支持分词查询) wrapper.mapping(Document::getTitle, FieldType.KEYWORD, 2.0f) .mapping(Document::getLocation, FieldType.GEO_POINT) .mapping(Document::getGeoLocation, FieldType.GEO_SHAPE) .mapping(Document::getContent, FieldType.TEXT, Analyzer.IK_SMART, Analyzer.IK_MAX_WORD); // 0.9.8+版本,增加对符串字段名称的支持,Document实体中须在对应字段上加上@Tablefield(value="wu-la")用于映射此字段值 wrapper.mapping("wu-la", FieldType.TEXT, Analyzer.IK_MAX_WORD, Analyzer.IK_MAX_WORD); // 设置分片及副本信息,可缺省 wrapper.settings(3, 2); // 设置别名信息,可缺省 String aliasName = "daily"; wrapper.createAlias(aliasName); // 设置父子信息,若无父子文档关系则无需设置 wrapper.join("joinField", "document", "comment"); // 创建索引 boolean isOk = documentMapper.createIndex(wrapper); Assertions.assertTrue(isOk); } ``` ```Java /** * 方式3 变体,使用难度最高,但灵活性也最高 */ @Test public void testCreateIndexByMap() { // 演示通过自定义map创建索引,最为灵活 可支持es本身能支持的所有索引场景 LambdaEsIndexWrapper wrapper = new LambdaEsIndexWrapper<>(); wrapper.indexName(Document.class.getSimpleName().toLowerCase()); wrapper.settings(3, 2); Map map = new HashMap<>(); Map prop = new HashMap<>(); Map field = new HashMap<>(); field.put("type", FieldType.KEYWORD.getType()); prop.put("this_is_field", field); map.put("properties", prop); wrapper.mapping(map); boolean isOk = documentMapper.createIndex(wrapper); Assertions.assertTrue(isOk); } ``` -------------------------------- ### Easy-ES Extended Performance Configuration Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/9a3e4c Optional settings that do not affect project startup but are recommended for production environments to improve performance. This includes various timeout settings (keep-alive, connect, socket, request, connection request) and maximum connection limits. A larger `socket-timeout` is advised for large data migrations in smooth index management mode to prevent timeouts. ```yaml easy-es: keep-alive-millis: 18000 # Keep-alive policy time Unit: ms connect-timeout: 5000 # Connection timeout Unit: ms socket-timeout: 5000 # Communication timeout Unit: ms request-timeout: 5000 # Request timeout Unit: ms connection-request-timeout: 5000 # Connection request timeout Unit: ms max-conn-total: 100 # Maximum connections Unit: count max-conn-per-route: 100 # Maximum connections per route Unit: count ``` -------------------------------- ### Easy-ES Java: Basic Tokenization Match Query Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Demonstrates the basic `match` query in Easy-ES. This query tokenizes the input, and if any of the tokens match content in the specified field, the data is retrieved, regardless of the token order. For example, `match("content", "老王")` will find content containing '老' or '王' if '老王' is tokenized. ```Java @Test public void testMatch(){ // Will tokenize the input; as long as one of the tokens matches content, the data will be queried, regardless of token order LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.match(Document::getContent,"技术"); List documents = documentMapper.selectList(wrapper); System.out.println(documents.size()); } ``` -------------------------------- ### GeoBoundingBox Query Usage Example (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/39b41e Example demonstrating how to use `geoBoundingBox` to query documents within a defined rectangular area. It initializes `GeoPoint` objects for the top-left and bottom-right corners and applies the query to the `location` field using `LambdaEsQueryWrapper`. ```Java @Test public void testGeoBoundingBox() { // 查询位于左上点和右下点坐标构成的长方形内的所有点 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); // 假设左上点坐标 GeoPoint leftTop = new GeoPoint(41.187328D, 115.498353D); // 假设右下点坐标 GeoPoint bottomRight = new GeoPoint(39.084509D, 117.610461D); wrapper.geoBoundingBox(Document::getLocation, leftTop, bottomRight); // 查不在此长方形内的所有点 // wrapper.notInGeoBoundingBox(Document::getLocation, leftTop, bottomRight); List documents = documentMapper.selectList(wrapper); documents.forEach(System.out::println); } ``` -------------------------------- ### Easy-ES Java Example: Custom Random Sorting with ScriptSortBuilder Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/274da8 This Java example demonstrates how to implement a custom random sort using `ScriptSortBuilder` in Easy-ES. It shows how to create a `LambdaEsQueryWrapper`, apply a match query, and then use a `Script` with `Math.random()` to achieve random data retrieval before executing the query and printing the results. ```Java @Test public void testSort(){ // 测试复杂排序,SortBuilder的子类非常多,这里仅演示一种, 比如有用户提出需要随机获取数据 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.match(Document::getContent,"技术"); Script script = new Script("Math.random()"); ScriptSortBuilder scriptSortBuilder = new ScriptSortBuilder(script, ScriptSortBuilder.ScriptSortType.NUMBER); wrapper.sort(scriptSortBuilder); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Java Example: Streamlined queryStringQuery with QueryUtils Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/1cebb8 Illustrates the use of `cn.easyes.core.toolkit.QueryUtils` to simplify the construction of complex `queryString` for the `queryStringQuery` API. This utility class provides methods like `combine` and `buildQueryString` to create more elegant and readable query strings compared to manual `StringBuilder` concatenation. ```Java @Test public void testQueryStringQueryMulti() { LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); String queryStr = QueryUtils.combine(Link.OR, QueryUtils.buildQueryString(Document::getCreator, "老王", Query.EQ, Link.AND), QueryUtils.buildQueryString(Document::getCreator, "隔壁", Query.MATCH)) + QueryUtils.buildQueryString(Document::getCreator, "*大猪蹄子*", Query.EQ); wrapper.queryStringQuery(queryStr); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Easy-ES Tokenization Matching API Methods Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Defines various methods available in Easy-ES for performing tokenization-based matching queries. Note that some APIs (matchPhase, matchAllQuery, etc.) are only supported in Easy-ES version 0.9.12 and above, requiring an upgrade if needed. ```APIDOC match(boolean condition, R column, Object val); notMatch(boolean condition, R column, Object val, Float boost); // These APIs are only supported in version 0.9.12+; upgrade EE version if needed matchPhase(boolean condition, R column, Object val, Float boost); matchAllQuery(); matchPhrasePrefixQuery(boolean condition, R column, Object val, int maxExpansions, Float boost); multiMatchQuery(boolean condition, Object val, Operator operator, int minimumShouldMatch, Float boost, R... columns); queryStringQuery(boolean condition, String queryString, Float boost); prefixQuery(boolean condition, R column, String prefix, Float boost); ``` -------------------------------- ### Create Index with Easy-Es (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/04414d This snippet demonstrates how to create an Elasticsearch index using Easy-Es's one-click creation mode. The framework automatically generates the index based on entity class annotations, provided the index hosting mode is set to 'manual'. ```Java @Test public void testCreateIndex() { // 测试创建索引,框架会根据实体类及字段上加的自定义注解一键帮您生成索引 需确保索引托管模式处于manual手动挡(默认处于此模式),若为自动挡则会冲突 boolean success = documentMapper.createIndex(); Assertions.assertTrue(success); } ``` -------------------------------- ### Easy-ES Basic Configuration Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/eddebb This snippet shows the essential configuration for Easy-ES, including the Elasticsearch connection address, username, and password. The address (ip:port) is mandatory for the project to start, while username and password are optional. ```YAML easy-es: address : 127.0.0.1:9200 # es连接地址+端口 格式必须为ip:port,如果是集群则可用逗号隔开 username: elastic #如果无账号密码则可不配置此行 password: WG7WVmuNMtM4GwNYkyWH #如果无账号密码则可不配置此行 ``` -------------------------------- ### Java Example: Querying Geo-Distance with Easy-ES Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/775ca1 This Java code demonstrates how to use `geoDistance` to query documents within a specified radius from a given geographical point. It shows various ways to specify distance and coordinates, including `DistanceUnit` and string formats. It also includes a commented-out example for `notInGeoDistance`. ```Java @Test public void testGeoDistance() { // 查询以纬度为41.0,经度为115.0为圆心,半径168.8公里内的所有点 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); // 其中单位可以省略,默认为km wrapper.geoDistance(Document::getLocation, 168.8, DistanceUnit.KILOMETERS, new GeoPoint(41.0, 116.0)); //查询不在圆形内的所有点 // wrapper.notInGeoDistance(Document::getLocation, 168.8, DistanceUnit.KILOMETERS, new GeoPoint(41.0, 116.0)); // 上面语法也可以写成下面这几种形式,效果是一样的,兼容不同用户习惯而已: // wrapper.geoDistance(Document::getLocation,"1.5km",new GeoPoint(41.0,115.0)); // wrapper.geoDistance(Document::getLocation, "1.5km", "41.0,115.0"); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Easy-ES Global Application Configuration Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/9a3e4c Optional global settings that default to specific values if not configured. This section covers banner display, index processing modes (smoothly, not_smoothly, manual), DSL statement printing, distributed project identification, asynchronous index processing behavior, and retry parameters for active index release in distributed environments. It also includes database-related configurations like underscore-to-camelCase mapping, table prefix, ID generation strategy, field update strategy, total hits tracking, data refresh policy, and batch update threshold. ```yaml easy-es: banner: false # Defaults to true. If you don't want to print the banner, set to false global-config: process-index-mode: smoothly # Index processing mode, smoothly: smooth mode, enabled by default; not_smoothly: non-smooth mode; manual: manual mode print-dsl: true # Enable printing DSL statements generated by this framework to the console. Enabled by default, recommended to disable in production after stable testing to improve minor performance distributed: false # Whether the current project is a distributed project. Defaults to true. In non-manual index management mode, if it's a distributed project, a distributed lock will be acquired; non-distributed projects only need a synchronized lock. async-process-index-blocking: true # Whether asynchronous index processing blocks the main thread. Defaults to blocking. Adjust to non-blocking asynchronous for very large data volumes to speed up project startup. active-release-index-max-retry: 60 # In a distributed environment, smooth mode, maximum retry attempts for the current client to activate the latest index. If data volume is too large and index reconstruction data migration time exceeds 60*(180/60)=180 minutes, this parameter can be increased. This parameter determines the maximum number of retries; if still unsuccessful after this number, retries will terminate and an exception log will be recorded. active-release-index-fixed-delay: 180 # In a distributed environment, smooth mode, maximum retry attempts for the current client to activate the latest index. If data volume is too large and index reconstruction data migration time exceeds 60*(180/60)=180 minutes, this parameter can be increased. This parameter determines how often to retry. Unit: seconds. db-config: map-underscore-to-camel-case: false # Whether to enable underscore to camelCase mapping. Defaults to false. table-prefix: daily_ # Index prefix, can be used to distinguish environments. Defaults to empty. Usage is similar to MP. id-type: customize # ID generation strategy. customize means custom, ID value is generated by the user, e.g., taking data ID from MySQL. If this configuration is missing, the default ID strategy is ES auto-generation. field-strategy: not_empty # Field update strategy. Defaults to not_null. enable-track-total-hits: true # Enabled by default, enables querying all matching data. If disabled, total data count cannot be obtained; other functions are unaffected. If query count exceeds 10,000, @IndexName annotation's maxResultWindow also needs to be adjusted to greater than 10,000, and index rebuilt for subsequent queries to take effect (not recommended, pagination query is suggested). refresh-policy: immediate # Data refresh policy. Defaults to no refresh. enable-must2-filter: false # Whether to globally enable conversion of must query type to filter query type. Defaults to false (no conversion). batch-update-threshold: 10000 # Batch update threshold. Default value is 10,000. ``` -------------------------------- ### GeoDistance Query Usage Example (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/39b41e Example demonstrating how to use `geoDistance` to query documents within a specified radius from a central `GeoPoint`. It shows how to define the central point and distance, and applies the query to the `location` field. It also notes alternative syntax for distance and central point. ```Java @Test public void testGeoDistance() { // 查询以经度为41.0,纬度为115.0为圆心,半径168.8公里内的所有点 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); // 其中单位可以省略,默认为km wrapper.geoDistance(Document::getLocation, 168.8, DistanceUnit.KILOMETERS, new GeoPoint(41.0, 116.0)); //查询不在圆形内的所有点 // wrapper.notInGeoDistance(Document::getLocation, 168.8, DistanceUnit.KILOMETERS, new GeoPoint(41.0, 116.0)); // 上面语法也可以写成下面这几种形式,效果是一样的,兼容不同用户习惯而已: // wrapper.geoDistance(Document::getLocation,"1.5km",new GeoPoint(41.0,115.0)); // wrapper.geoDistance(Document::getLocation, "1.5km", "41.0,115.0"); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Delete Document from Easy-Es Index (Java) Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/04414d This example demonstrates how to delete documents from an Elasticsearch index using Easy-Es. It specifically shows deletion based on conditions using `LambdaEsQueryWrapper`, although deletion by ID is also a supported and simpler method. ```Java @Test public void testDelete() { // 测试删除数据 删除有两种情况:根据id删或根据条件删 // 鉴于根据id删过于简单,这里仅演示根据条件删,以老李的名义删,让老李心理平衡些 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); String title = "隔壁老李"; wrapper.eq(Document::getTitle,title); int successCount = documentMapper.delete(wrapper); System.out.println(successCount); } ``` -------------------------------- ### Java: Single-Field Distinct Aggregation Example in Easy-ES Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/ce1922 Provides a practical example of using `distinct()` to query documents, de-duplicate by a specified field (e.g., `creator`), and paginate the results. ```Java @Test public void testDistinct() { // 查询所有标题为老汉的文档,根据创建者去重,并分页返回 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.eq(Document::getTitle, "老汉") .distinct(Document::getCreator); PageInfo pageInfo = documentMapper.pageQuery(wrapper, 1, 10); System.out.println(pageInfo); } ``` -------------------------------- ### Easy-Es Entity ID Field Configuration Examples Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/4c01d7 This Java code snippet illustrates three different approaches for defining the `id` field within an Easy-Es entity class. It highlights the recommended method where Elasticsearch automatically generates the ID, an alternative for custom IDs (not recommended for performance), and a best practice for storing external database IDs without impacting Elasticsearch's internal ID management. ```Java public class Document { /** * 推荐方式1: es中的唯一id,不加任何注解或@IndexId(type=IdType.NONE) 此时id值将由es自动生成 */ private String id; /** * 不推荐方式2:如果你想自定义es中的id为你提供的id,比如MySQL中的id,请将注解中的type指定为customize或直接在全局配置文件中指定,此时你便可以在插入数据时赋值给id */ @IndexId(type = IdType.CUSTOMIZE) private Long id; /** * 推荐方式3:如果你确实有需求用到其它数据库中的id,不妨在加了推荐方式1中的id后,再加一个字段类型为keyword的列,用来存储其它数据库中的id */ @IndexField(fieldType = FieldType.KEYWORD) private Long mysqlId; } ``` -------------------------------- ### Easy-ES Java: Multi-Field Match Query Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Explains `multiMatchQuery` for searching a keyword across multiple specified fields. It also shows how to customize the `Operator` (defaulting to OR) and `minimumShouldMatch` (defaulting to 60%) parameters for fine-grained control over matching logic. For example, `Operator.AND` requires all search tokens to be matched, while `minShouldMatch 80` queries data with a match degree greater than 80%. ```Java @Test public void testMultiMatchQuery() { // Query data containing '老王' from multiple specified fields LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.multiMatchQuery("老王", Document::getTitle, Document::getContent, Document::getCreator, Document::getCustomField); // Among them, the default Operator is OR, and the default minShouldMatch is 60%. Both parameters can be adjusted as needed, and our API supports them. For example: // AND means all search tokens must be matched, OR means only one token needs to match. minShouldMatch 80 means only query data with a match degree greater than 80%. // wrapper.multiMatchQuery("老王",Operator.AND,80,Document::getCustomField,Document::getContent); List documents = documentMapper.selectList(wrapper); System.out.println(documents.size()); System.out.println(documents); } ``` -------------------------------- ### Java: Example of GeoBoundingBox Query in Easy-Es Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/775ca1 This Java example demonstrates how to use the `geoBoundingBox` method with `LambdaEsQueryWrapper` in Easy-Es to query documents whose geo_point field falls within a defined rectangular area. It also shows the commented-out usage of `notInGeoBoundingBox` for inverse queries. ```java @Test public void testGeoBoundingBox() { // 查询位于左上点和右下点坐标构成的长方形内的所有点 LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); // 假设左上点坐标 GeoPoint leftTop = new GeoPoint(41.187328D, 115.498353D); // 假设右下点坐标 GeoPoint bottomRight = new GeoPoint(39.084509D, 117.610461D); wrapper.geoBoundingBox(Document::getLocation, leftTop, bottomRight); // 查不在此长方形内的所有点 // wrapper.notInGeoBoundingBox(Document::getLocation, leftTop, bottomRight); List documents = documentMapper.selectList(wrapper); documents.forEach(System.out::println); } ``` -------------------------------- ### likeRight Method for Starts With Condition Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/1cebb8 Generates a `LIKE 'val%'` condition. The `column` parameter represents the database field. The optional `condition` parameter allows conditional application of the filter. ```APIDOC likeRight(R column, Object val) likeRight(boolean condition, R column, Object val) ``` -------------------------------- ### Easy-ES Index Update Usage Example Source: https://www.easy-es.cn/pages/7ead0d/pages/e8b9ad Demonstrates how to update an existing index in Easy-ES by specifying the index name and adding or modifying field mappings using a wrapper. ```Java /** * 更新索引 */ @Test public void testUpdateIndex() { // 测试更新索引 LambdaEsIndexWrapper wrapper = new LambdaEsIndexWrapper<>(); // 指定要更新哪个索引 String indexName = Document.class.getSimpleName().toLowerCase(); wrapper.indexName(indexName); wrapper.mapping(Document::getCreator, FieldType.KEYWORD); wrapper.mapping(Document::getGmtCreate, FieldType.DATE); boolean isOk = documentMapper.updateIndex(wrapper); Assertions.assertTrue(isOk); } ``` -------------------------------- ### Easy-ES Logging Configuration Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/9a3e4c Configuration for logging, specifically enabling trace-level logs for the 'tracer' category. This allows printing all Elasticsearch request information and DSL statements to the console during development. When this is enabled, it's recommended to set `print-dsl` in Easy-ES to `false` to avoid redundant output. ```yaml logging: level: tracer: trace # Enable trace level logs. This configuration can be enabled during development to print all ES request information and DSL statements to the console. To avoid redundancy, if this is enabled, EE's print-dsl can be set to false. ``` -------------------------------- ### Easy-ES Java: Query String Match Across All Fields Source: https://www.easy-es.cn/pages/7ead0d/pages/v1.x/2688d1 Illustrates `queryStringQuery`, which searches for a specified keyword across all fields within the document. This provides a broad search mechanism. ```Java @Test public void queryStringQuery() { // Query data containing the keyword '老汉' from all fields LambdaEsQueryWrapper wrapper = new LambdaEsQueryWrapper<>(); wrapper.queryStringQuery("老汉"); List documents = documentMapper.selectList(wrapper); System.out.println(documents); } ``` -------------------------------- ### Java: Example of Executing DSL Statement Source: https://www.easy-es.cn/pages/7ead0d/pages/v2.x/5b77a1 Demonstrates how to use the `executeDSL` method in Java. It shows constructing a DSL JSON string and calling the method. The result is returned in JSON format and requires manual parsing by the user. ```Java @Test public void testDSL() { String dsl = "{\"size\":10000,\"query\":{\"bool\":{\"must\":[{\"term\":{\"title.keyword\":{\"value\":\"测试文档2\",\"boost\":1.0}}}],\"adjust_pure_negative\":true,\"boost\":1.0}}\"track_total_hits\":2147483647}"; String jsonResult = documentMapper.executeDSL(dsl); // 注意,执行后是以JSON格式返回,由用户按需自行解析 System.out.println(jsonResult); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.