当前位置:   article > 正文

Elasticsearch概述和DSL查询总结_查询dsl

查询dsl

目录

Elasticsearch概述

1. 什么是Elasticsearch

2. 作用

3. 特点

DSL(Domain Specifit Language)特定领域语言:

概念和作用

查询代码总结

最后附项目准备

1.创建搜索工程(maven工程)

 2.配置文件 application.yml

3.配置类

4.启动类

测试类代码实现

创建索引、添加、查询、删除、更新文档

DSL查询测试类


Elasticsearch概述

1. 什么是Elasticsearch

Elasticsearch是基于Lucene的搜索服务器,它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用java开发的,开源,是当前流行的企业级搜索引擎。

2. 作用

 Elasticsearch具有极快的搜索速度,可以在几乎实时的时间内对大规模数据进行搜索和查询;它利用倒排索引和分布式搜索技术,使搜索操作变得高效,并能够多种查询方式进行全文搜索、短语匹配、模糊搜索等。

3. 特点

能够实时搜索,稳定,可靠,快速并且安装使用方便。
分布式和可扩展性:Elasticsearch基于分布式架构,可以将数据分布在多台服务器上,实现数据的水平分片和复制。这使得它能够处理海量数据,并具有高可用性和容错能力。通过添加或删除节点,可以轻松地扩展集群的容量和性能。

DSL(Domain Specifit Language)特定领域语言:

概念和作用

DSL查询是一种基于JSON的查询语言,用于构建复杂的查询和过滤条件,以检索和过滤文档。DSL查询提供了丰富的查询语法和灵活的组合方式,可以根据用户需求构建定制化的查询逻辑。

查询代码总结

  1. @Autowired //注入客户端
  2. RestHighLevelClient client;
  3. SearchRequest searchRequest = new SearchRequest("abc"); //参数为索引名
  4. searchRequest.types("doc"); //参数为类型
  5. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //创建查找源构造器
  6. SearchResponse searchResponse = client.search(searchRequest);
  7. 一、分页查询
  8. //分页查询,设置起始下标,从0开始
  9. searchSourceBuilder.from(0); //工作中可以套公式计算出起始值(page-1)*size
  10. //每页显示个数
  11. searchSourceBuilder.size(10);
  12. 二、Term精准查询
  13. searchSourceBuilder.query(QueryBuilders.termQuery("name","spring"));
  14. 三、根据id精准匹配
  15. searchSourceBuilder.query(QueryBuilders.termsQuery("_id", idList));
  16. 四、match全文检索
  17. 先将搜索字符串分词,再使用各个词条从索引中搜索。
  18. searchSourceBuilder.query(
  19. QueryBuilders.matchQuery("description", "spring开发")
  20. .operator(Operator.OR));
  21. 五、multi一次匹配多个字段
  22. 单项匹配是在一个field中去匹配,多项匹配是拿关键字去多个Field中匹配。
  23. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框架", "name", "description") .minimumShouldMatch("50%");
  24. multiMatchQueryBuilder.field("name",10);//提升boost显示级别
  25. //设置过滤字段
  26. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
  27. 六、布尔查询
  28. must:文档必须匹配must所包括的查询条件,相当于 “AND”。 表示必须,多个查询条件必须都满足。
  29. should:文档应该匹配should所包括的查询条件其中的一个或多个,相当于 "OR" 。表示或者,多个查询条件只要有一个满足即可。
  30. must_not:文档不能匹配must_not所包括的该查询条件,相当于 “NOT”。表示非。
  31. boolQueryBuilder.must(multiMatchQueryBuilder); //且的关系用must,或的关系用should
  32. searchSourceBuilder.query(boolQueryBuilder);//放入构造器中,否则不起作用
  33. 七、filter过滤器
  34. boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel", "201001"));
  35. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));
  36. 八、sort排序
  37. searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC));
  38. 九、高亮显示
  39. //高亮设置
  40. HighlightBuilder highlightBuilder = new HighlightBuilder();
  41. highlightBuilder.preTags("<tag>");//设置前缀
  42. highlightBuilder.postTags("</tag>");//设置后缀
  43. // 设置高亮字段
  44. highlightBuilder.fields().add(new HighlightBuilder.Field("name"));//选择想要高亮的字段
  45. searchSourceBuilder.highlighter(highlightBuilder);//放入构造器中,否则不起作用
  46. //取出高亮字段内容
  47. HighlightField nameField = highlightFields.get("name");
  48. Text[] fragments = nameField.getFragments();

注意:设置完毕后一定要加入SearchSourceBuilder 构造器中

注意:设置完毕后一定要加入SearchSourceBuilder 构造器中

注意:设置完毕后一定要加入SearchSourceBuilder 构造器中

最后附项目准备

1.创建搜索工程(maven工程)

添加RestHighLevelClient依赖及junit依赖。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.1.3.RELEASE</version>
  10. </parent>
  11. <groupId>cn.yh</groupId>
  12. <artifactId>yh-service-search</artifactId>
  13. <version>1.0-SNAPSHOT</version>
  14. <properties>
  15. <maven.compiler.source>8</maven.compiler.source>
  16. <maven.compiler.target>8</maven.compiler.target>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-web</artifactId>
  22. </dependency>
  23. <!--elasticsearch-->
  24. <dependency>
  25. <groupId>org.elasticsearch.client</groupId>
  26. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  27. <version>6.2.1</version>
  28. <exclusions>
  29. <exclusion>
  30. <groupId>org.elasticsearch.client</groupId>
  31. <artifactId>elasticsearch-rest-client</artifactId>
  32. </exclusion>
  33. </exclusions>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.elasticsearch.client</groupId>
  37. <artifactId>elasticsearch-rest-client</artifactId>
  38. <version>6.2.1</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.elasticsearch</groupId>
  42. <artifactId>elasticsearch</artifactId>
  43. <version>6.2.1</version>
  44. </dependency>
  45. <!--junit-->
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. </project>

 2.配置文件 application.yml

  1. server:
  2. port: 8080
  3. spring:
  4. application:
  5. name: yh-search-service
  6. yh:
  7. elasticsearch:
  8. hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔

3.配置类

创建 com.yh.search.config 包在其下

  1. package cn.yh.es.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class ElasticsearchConfig {
  10. @Value("${yh.elasticsearch.hostlist}")
  11. private String hostlist;
  12. @Bean
  13. public RestHighLevelClient restHighLevelClient() {
  14. //解析hostlist配置信息
  15. String[] split = hostlist.split(",");
  16. //创建HttpHost数组,其中存放es主机和端口的配置信息
  17. HttpHost[] httpHostArray = new HttpHost[split.length];
  18. for (int i = 0; i < split.length; i++) {
  19. String item = split[i];
  20. httpHostArray[i] =
  21. new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
  22. }
  23. //创建RestHighLevelClient客户端
  24. return new RestHighLevelClient(RestClient.builder(httpHostArray));
  25. }
  26. //项目主要使用RestHighLevelClient,对于低级的客户端暂时不用
  27. @Bean
  28. public RestClient restClient() {
  29. //解析hostlist配置信息
  30. String[] split = hostlist.split(",");
  31. //创建HttpHost数组,其中存放es主机和端口的配置信息
  32. HttpHost[] httpHostArray = new HttpHost[split.length];
  33. for (int i = 0; i < split.length; i++) {
  34. String item = split[i];
  35. httpHostArray[i] =
  36. new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
  37. }
  38. return RestClient.builder(httpHostArray).build();
  39. }
  40. }

4.启动类

  1. @SpringBootApplication
  2. public class SearchApplication {
  3. public static void main(String[] args) throws Exception {
  4. SpringApplication.run(SearchApplication.class, args);
  5. }
  6. }

测试类代码实现

创建索引、添加、查询、删除、更新文档

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class EsTest {
  4. @Autowired
  5. private RestHighLevelClient client;
  6. @Autowired
  7. private RestClient restClient;
  8. /**
  9. * 创建索引库(数据库),创建映射Mapping(字段)
  10. * @throws IOException
  11. */
  12. @Test
  13. public void creatIndex() throws IOException {
  14. CreateIndexRequest createIndexRequest = new CreateIndexRequest("yh_test");
  15. //1.创建索引的客户端
  16. IndicesClient indices = client.indices();
  17. //3.1设置索引参数
  18. createIndexRequest.settings(Settings.builder().put("number_of_shards",1).
  19. put("number_of_replicas",0).build());
  20. //3.2创建映射
  21. createIndexRequest.mapping("doc","{\n" +
  22. " \"properties\": { \n" +
  23. " \"name\": {\n" +
  24. " \"type\": \"text\",\n" +
  25. " \"analyzer\":\"ik_max_word\",\n" +
  26. " \"search_analyzer\":\"ik_smart\"\n" +
  27. " },\n" +
  28. " \"description\": {\n" +
  29. " \"type\": \"text\",\n" +
  30. " \"analyzer\":\"ik_max_word\",\n" +
  31. " \"search_analyzer\":\"ik_smart\"\n" +
  32. " },\n" +
  33. " \"studymodel\": {\n" +
  34. " \"type\": \"keyword\"\n" +
  35. " },\n" +
  36. " \"price\": {\n" +
  37. " \"type\": \"float\"\n" +
  38. " },\n" +
  39. " \"timestamp\": {\n" +
  40. " \"type\": \"date\", \n" +
  41. " \"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis\"\n" +
  42. " }\n" +
  43. " }\n" +
  44. "}", XContentType.JSON);
  45. //2.创建响应对象
  46. CreateIndexResponse response = indices.create(createIndexRequest);
  47. //得到响应对象
  48. boolean responseAcknowledged = response.isAcknowledged();
  49. System.out.println(responseAcknowledged);
  50. }
  51. /**
  52. * 添加文档(向表doc中添加记录)
  53. * @throws IOException
  54. */
  55. @Test
  56. public void addDoc() throws IOException {
  57. //准备json数据
  58. Map<String, Object> jsonMap = new HashMap<>();
  59. jsonMap.put("name", "spring MVC开源框架1");
  60. jsonMap.put("description", "本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud基础入门 3.实战Spring Boot 4.注册中心eureka。");
  61. jsonMap.put("studymodel", "201001");
  62. SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  63. jsonMap.put("timestamp", dateFormat.format(new Date()));
  64. jsonMap.put("price", 5.6f);
  65. //获取索引对象
  66. IndexRequest indexRequest = new IndexRequest("yh_test","doc","6");
  67. //向索引中添加数据
  68. indexRequest.source(jsonMap);
  69. //客户端添加索引
  70. IndexResponse index = client.index(indexRequest);
  71. System.out.println(index.getResult());
  72. }
  73. /**
  74. * 查询文档
  75. * @throws IOException
  76. */
  77. @Test
  78. public void searchDoc() throws IOException {
  79. GetRequest getRequest = new GetRequest("yh_test","doc","N7gytIkBjqFbH1htibgh");
  80. GetResponse response = client.get(getRequest);
  81. System.out.println(response);
  82. boolean exists = response.isExists();
  83. System.out.println(exists);
  84. Map<String, Object> sourceAsMap = response.getSourceAsMap();
  85. System.out.println(sourceAsMap);
  86. }
  87. /**
  88. * 更新文档
  89. */
  90. @Test
  91. public void updateDoc() throws IOException {
  92. UpdateRequest updateRequest = new UpdateRequest("yh_test","doc","N7gytIkBjqFbH1htibgh");
  93. Map<String, String> map = new HashMap<>();
  94. map.put("name","spring boot");
  95. updateRequest.doc(map); //将修改内容放到对象中
  96. UpdateResponse update = client.update(updateRequest);
  97. System.out.println(update);
  98. }
  99. /**
  100. * 删除文档
  101. */
  102. @Test
  103. public void deleteDoc() throws IOException {
  104. //获取文档id
  105. String id = "N7gytIkBjqFbH1htibgh";
  106. DeleteRequest deleteRequest = new DeleteRequest("yh_test","doc","1"); //id为记录id
  107. DeleteResponse delete = client.delete(deleteRequest);
  108. System.out.println(delete);
  109. }
  110. }

DSL查询测试类

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class EsDSLSearchTest {
  4. @Autowired
  5. private RestHighLevelClient client;
  6. @Autowired
  7. private RestClient restClient;
  8. /**
  9. * 自定义打印输出方法
  10. * @param search
  11. * @throws IOException
  12. */
  13. public void myPrint(SearchResponse search) {
  14. SearchHits hits = search.getHits();
  15. for (SearchHit hit : hits) {
  16. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  17. float score = hit.getScore();
  18. Double price = (Double)sourceAsMap.get("price");
  19. String name = (String) sourceAsMap.get("name");
  20. String studymodel = (String) sourceAsMap.get("studymodel");
  21. String description = (String) sourceAsMap.get("description");
  22. System.out.println("name:"+name+",studymodel:"+studymodel+",score:"
  23. +score+",price:"+price+",description:"+description);
  24. }
  25. }
  26. /**
  27. * 一:查询文档,所有记录,指定字段
  28. */
  29. @Test
  30. public void selectDocBy() throws IOException {
  31. //2.
  32. SearchRequest searchRequest = new SearchRequest("yh_test");
  33. searchRequest.types("doc");
  34. //4.查找源构造器
  35. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  36. //ctrl+h查看接口实现类列表
  37. //查询所有
  38. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  39. //source源字段过滤
  40. searchSourceBuilder.fetchSource(new String[]{"name", "studymodel"}, new String[]{});
  41. //3.
  42. searchRequest.source(searchSourceBuilder);
  43. //1.
  44. SearchResponse search = client.search(searchRequest);
  45. //输出
  46. this.myPrint(search);
  47. }
  48. // /**
  49. // * 查所有记录DSL
  50. // */
  51. // @Test
  52. // public void selectAll() throws IOException {
  53. // SearchRequest searchRequest = new SearchRequest("yh_test");
  54. // searchRequest.types("doc");
  55. // SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  56. // searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  57. // searchSourceBuilder.fetchSource(new String[] {"name"},new String[]{} ); //exclude排除
  58. // searchRequest.source(searchSourceBuilder);
  59. //
  60. // SearchResponse search = client.search(searchRequest);
  61. //
  62. // //输出
  63. // SearchHits hits = search.getHits();
  64. // for (SearchHit hit : hits) {
  65. // String index = hit.getIndex();
  66. // float score = hit.getScore();
  67. // String id = hit.getId();
  68. // String type = hit.getType();
  69. // Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //获取_source集合,该集合是上面过滤的字段
  70. // System.out.println(sourceAsMap);
  71. // }
  72. // }
  73. /**
  74. * 二:分页查询
  75. */
  76. @Test
  77. public void splitPageSearch() throws IOException {
  78. SearchRequest searchRequest = new SearchRequest("yh_test");
  79. searchRequest.types("doc");
  80. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  81. //分页
  82. searchSourceBuilder.from(0);
  83. searchSourceBuilder.size(2);
  84. //限制输出字段
  85. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  86. searchSourceBuilder.fetchSource(new String[]{"name"}, new String[]{});
  87. searchRequest.source(searchSourceBuilder);
  88. SearchResponse search = client.search(searchRequest);
  89. //打印输出
  90. this.myPrint(search);
  91. }
  92. /**
  93. * 三:term精准查询
  94. * {
  95. * "query": {
  96. * "term" : {
  97. * "name": "spring"
  98. * }
  99. * },
  100. * "_source" : ["name","studymodel"]
  101. * }
  102. */
  103. @Test
  104. public void termQuery() throws IOException {
  105. SearchRequest searchRequest = new SearchRequest("yh_test");
  106. searchRequest.types("doc");
  107. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  108. //设置精准匹配字段
  109. searchSourceBuilder.query(QueryBuilders.termQuery("name", "spring"));
  110. //限制输出字段
  111. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"}, new String[]{});
  112. searchRequest.source(searchSourceBuilder);
  113. SearchResponse search = client.search(searchRequest);
  114. //输出
  115. this.myPrint(search);
  116. }
  117. /**
  118. * 四:根据id精准匹配
  119. * {
  120. * "query": {
  121. * "ids" : {
  122. * "type" : "doc",
  123. * "values" : ["3", "4", "100"]
  124. * }
  125. * }
  126. * }
  127. */
  128. @Test
  129. public void accurateQueryById() throws IOException {
  130. SearchRequest searchRequest = new SearchRequest("yh_test");
  131. searchRequest.types("doc");
  132. String[] ids = {"3", "4", "100"};
  133. List<String> idsList = Arrays.asList(ids); //将字符数组转换为集合
  134. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  135. searchSourceBuilder.query(QueryBuilders.termsQuery("_id", idsList));
  136. searchRequest.source(searchSourceBuilder);
  137. SearchResponse search = client.search(searchRequest);
  138. //输出
  139. this.myPrint(search);
  140. }
  141. /**
  142. * 五:match全文检索
  143. * 先将搜索字符串分词,再使用各个词条从索引中搜索
  144. * {
  145. * "query": {
  146. * "match" : {
  147. * "description" : {
  148. * "query" : "spring开发",
  149. * "operator" : "or"
  150. * }
  151. * }
  152. * }
  153. * }
  154. */
  155. @Test
  156. public void matchQuery() throws IOException {
  157. SearchRequest searchRequest = new SearchRequest("yh_test");
  158. searchRequest.types("doc");
  159. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  160. //查询字段为name,name:spring的记录; Operator.OR操作数意思是分词满足其中任一记录的都可以
  161. searchSourceBuilder.query(QueryBuilders.matchQuery("name","spring").operator(Operator.OR));
  162. searchRequest.source(searchSourceBuilder);
  163. SearchResponse search = client.search(searchRequest);
  164. //输出
  165. this.myPrint(search);
  166. }
  167. /**
  168. * 六:multi关键字匹配多个字段
  169. * 单项匹配是在一个field中去匹配,多项匹配是拿关键字去多个Field中匹配
  170. * {
  171. * "query": {
  172. * "multi_match" : {
  173. * "query" : "spring css",
  174. * "minimum_should_match": "50%",
  175. * "fields": [ "name", "description" ]
  176. * }
  177. * }
  178. * }
  179. */
  180. @Test
  181. public void multiQuery() throws IOException {
  182. SearchRequest searchRequest = new SearchRequest();
  183. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  184. searchSourceBuilder.query(QueryBuilders.multiMatchQuery
  185. //spring css匹配字段; name、description匹配字段; minimumShouldMatch匹配度50%,分次数*50%向下取整; field提升优先级;
  186. ("spring css","name","description").minimumShouldMatch("50%").field("name",10));
  187. searchRequest.source(searchSourceBuilder);
  188. SearchResponse search = client.search(searchRequest);
  189. //输出
  190. this.myPrint(search);
  191. }
  192. /**
  193. * 七:布尔查询
  194. * 布尔查询对应于Lucene的BooleanQuery查询,实现将多个查询组合起来。
  195. * 三个参数:
  196. * must:文档必须匹配must所包括的查询条件,相当于 “AND”
  197. * should:文档应该匹配should所包括的查询条件其中的一个或多个,相当于 "OR"
  198. * must_not:文档不能匹配must_not所包括的该查询条件,相当于 “NOT”
  199. * {
  200. * "_source" : [ "name", "studymodel", "description"],
  201. * "from" : 0, "size" : 1,
  202. * "query": {
  203. * "bool" : {
  204. * "must":[
  205. * {
  206. * "multi_match" : {
  207. * "query" : "spring框架",
  208. * "minimum_should_match": "50%",
  209. * "fields": [ "name^10", "description" ]
  210. * }
  211. * },
  212. * {
  213. * "term":{
  214. * "studymodel" : "201001"
  215. * }
  216. * }
  217. * ]
  218. * }
  219. * }
  220. * }
  221. */
  222. @Test
  223. public void boolQuery() throws IOException {
  224. SearchRequest searchRequest = new SearchRequest();
  225. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  226. //查询一
  227. MultiMatchQueryBuilder multiMatchQueryBuilder =QueryBuilders.multiMatchQuery
  228. ("spring框架","name","description").minimumShouldMatch("50%").field("name",10);
  229. //查询二
  230. TermsQueryBuilder termsQuery = QueryBuilders.termsQuery("studymodel", "201001");
  231. //获取bool查询对象
  232. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  233. boolQueryBuilder.must(multiMatchQueryBuilder);
  234. boolQueryBuilder.must(termsQuery);
  235. searchSourceBuilder.query(boolQueryBuilder);
  236. //设置过滤字段
  237. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
  238. //设置分页
  239. searchSourceBuilder.from(0);
  240. searchSourceBuilder.size(2);
  241. searchRequest.source(searchSourceBuilder);
  242. SearchResponse search = client.search(searchRequest);
  243. //输出
  244. this.myPrint(search);
  245. }
  246. /**
  247. * 八:filter过滤器
  248. * 过滤是针对搜索的结果进行过滤,过滤器主要判断的是文档是否匹配,不去计算和判断文档的匹配度得分,所以过
  249. * 虑器性能比查询要高,且方便缓存,推荐尽量使用过滤器去实现查询或者过滤器和查询共同使用。
  250. */
  251. @Test
  252. public void filterQuery() throws IOException {
  253. SearchRequest searchRequest = new SearchRequest();
  254. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  255. //查询一
  256. MultiMatchQueryBuilder multiMatchQueryBuilder =QueryBuilders.multiMatchQuery
  257. ("spring框架","name","description").minimumShouldMatch("50%").field("name",10);
  258. //获取bool查询对象
  259. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  260. boolQueryBuilder.must(multiMatchQueryBuilder);
  261. //filter过滤器
  262. boolQueryBuilder.filter(QueryBuilders.termsQuery("studymodel","201001"));
  263. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));
  264. searchSourceBuilder.query(boolQueryBuilder);
  265. //设置过滤字段
  266. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","description"},new String[]{});
  267. //设置分页
  268. searchSourceBuilder.from(0);
  269. searchSourceBuilder.size(6);
  270. searchRequest.source(searchSourceBuilder);
  271. SearchResponse search = client.search(searchRequest);
  272. //输出
  273. this.myPrint(search);
  274. }
  275. /**
  276. * 九:sort排序
  277. */
  278. @Test
  279. public void sortQuery() throws IOException {
  280. SearchRequest searchRequest = new SearchRequest();
  281. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  282. //查询一
  283. MultiMatchQueryBuilder multiMatchQueryBuilder =QueryBuilders.multiMatchQuery
  284. ("spring框架","name","description").minimumShouldMatch("50%").field("name",10);
  285. //获取bool查询对象
  286. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  287. boolQueryBuilder.must(multiMatchQueryBuilder);
  288. //filter过滤器
  289. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
  290. searchSourceBuilder.query(boolQueryBuilder);
  291. //sort排序
  292. searchSourceBuilder.sort("studymodel", SortOrder.DESC);
  293. searchSourceBuilder.sort("price",SortOrder.ASC);
  294. //设置过滤字段
  295. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","description"},new String[]{});
  296. //设置分页
  297. searchSourceBuilder.from(0);
  298. searchSourceBuilder.size(6);
  299. searchRequest.source(searchSourceBuilder);
  300. SearchResponse search = client.search(searchRequest);
  301. //输出
  302. this.myPrint(search);
  303. }
  304. /**
  305. * 十:高亮显示highlight
  306. * {
  307. * "_source" : [ "name", "studymodel", "description","price"],
  308. * "query": {
  309. * "bool" : {
  310. * "must":[
  311. * {
  312. * "multi_match" : {
  313. * "query" : "开发框架",
  314. * "minimum_should_match": "50%",
  315. * "fields": [ "name^10", "description" ],
  316. * "type":"best_fields"
  317. * }
  318. * }
  319. * ],
  320. * "filter": [
  321. * { "range": { "price": { "gte": 0 ,"lte" : 100}}}
  322. * ]
  323. * }
  324. * },
  325. * "sort" : [
  326. * {
  327. * "price" : "asc"
  328. * }
  329. * ],
  330. * "highlight": {
  331. * "pre_tags": ["<tag1>"],
  332. * "post_tags": ["</tag1>"],
  333. * "fields": {
  334. * "name": {},
  335. * "description":{}
  336. * }
  337. * }
  338. * }
  339. */
  340. @Test
  341. public void highLightQuery() throws IOException {
  342. SearchRequest searchRequest = new SearchRequest("yh_test");
  343. searchRequest.types("doc");
  344. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  345. //指定查询字段
  346. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description","price"},new String[]{});
  347. //multi查询
  348. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(
  349. "开发","name","description").field("name",10).minimumShouldMatch("50%");
  350. searchSourceBuilder.query(multiMatchQueryBuilder); //给查询资源构造器传过去
  351. //布尔查询
  352. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  353. boolQueryBuilder.must(searchSourceBuilder.query());
  354. //filter过滤器
  355. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
  356. //price升序排列
  357. searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC));
  358. //高亮
  359. HighlightBuilder highlighter =new HighlightBuilder();
  360. highlighter.preTags("<tag1>");
  361. highlighter.postTags("</tag1>");
  362. //设置高光字段
  363. highlighter.fields().add(new HighlightBuilder.Field("name"));
  364. highlighter.fields().add(new HighlightBuilder.Field("description"));
  365. searchSourceBuilder.highlighter(highlighter); //给查询资源构造器传过去
  366. searchRequest.source(searchSourceBuilder);
  367. SearchResponse search = client.search(searchRequest);
  368. //输出
  369. SearchHits hits = search.getHits();
  370. SearchHit[] searchHits = hits.getHits();
  371. for (SearchHit hit : searchHits) {
  372. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  373. //名称
  374. String name = (String) sourceAsMap.get("name");
  375. //取出高亮字段内容
  376. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  377. if (highlightFields != null) { //如果高光对象存在,获取一下name字段的高光内容
  378. HighlightField nameField = highlightFields.get("name");
  379. // System.out.println("++++++++"+nameField+"++++++++++++++");
  380. if (nameField != null) {
  381. Text[] fragments = nameField.getFragments(); //得到片段数组
  382. StringBuffer stringBuffer = new StringBuffer();
  383. for (Text str : fragments) {
  384. stringBuffer.append(str.string());
  385. }
  386. name = stringBuffer.toString();
  387. }
  388. }
  389. String index = hit.getIndex();
  390. String type = hit.getType();
  391. String id = hit.getId();
  392. float score = hit.getScore();
  393. String sourceAsString = hit.getSourceAsString();
  394. String studymodel = (String) sourceAsMap.get("studymodel");
  395. String description = (String) sourceAsMap.get("description");
  396. System.out.println(name);
  397. System.out.println(studymodel);
  398. System.out.println(description);
  399. }
  400. }
  401. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/547394
推荐阅读
相关标签
  

闽ICP备14008679号