当前位置:   article > 正文

es : java 查询_java es 查询

java es 查询

1. POM 配置

  1. <dependency>
  2. <groupId>org.elasticsearch.client</groupId>
  3. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  4. <version>7.6.2</version>
  5. </dependency>

2. 建立ES集群连接

  1. RestHighLevelClient client = new RestHighLevelClient(
  2. RestClient.builder(
  3. new HttpHost(IP, PORT, "http")));
  4. 同样,如果我们要连接集群中多个ES节点时,只需要在RestClient 的 builder 方法中多添加几个HttpPost对象即可
  5. String ipPort = "10.xx:9200,10.xx:9200,10.xx:9200";
  6. String[] ipPortArry = ipPort.split(",");
  7. List<HttpHost> httpHostsList = new ArrayList();
  8. for(String ips : ipPortArry){
  9. String[] ipArray = ips.split(":");
  10. httpHostsList.add(new HttpHost(ipArray[0], Integer.parseInt(ipArray[1]), "http"));
  11. }
  12. RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(httpHostsList.toArray(new HttpHost[httpHostsList.size()])));
  13. 补充:
  14. Java配置多个ES节点时,请求的时候会随机选一个节点作为协调节点负责分发请求和处理结果,所以Java链接ES节点数量的多少,不会影响到Java请求ES查询结果的速度,只是其中某个节点宕机时,其他节点可以保证正常的查询和操作。
  15. ES 端口92009300的区别:
  16. 9200作为Http协议,主要用于外部通讯
  17. 9300作为Tcp协议,jar之间就是通过tcp协议通讯
  18. ES集群之间是通过9300进行通讯

3. 简单的查询并获取查询结果

  1. RestHighLevelClient client = new RestHighLevelClient(
  2. RestClient.builder(
  3. new HttpHost("localhost", 9200, "http")));
  4. SearchRequest searchRequest = new SearchRequest("my_index");
  5. //或者
  6. /*
  7. SearchRequest searchRequest = new SearchRequest();
  8. searchRequest.indices("my_index");
  9. */
  10. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  11. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  12. //配置source源字段过虑,1显示的,2排除的
  13. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
  14. searchRequest.source(searchSourceBuilder);
  15. SearchResponse searchResponse = client.search(searchRequest);
  16. //获取所有搜索结果、总匹配数量
  17. SearchHits hits = searchResponse.getHits();
  18. long totalHits = hits.getTotalHits(); //如果总是超过1万, index没有设置,则返回1
  19. SearchHit[] searchHits = hits.getHits();
  20. //遍历结果
  21. for(SearchHit searchHit:searchHits){
  22. String index = searchHit.getIndex();
  23. String type = searchHit.getType();
  24. String id = searchHit.getId();
  25. float score = searchHit.getScore();
  26. String sourceAsString = searchHit.getSourceAsString();
  27. Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
  28. String name = (String) sourceAsMap.get("name");
  29. String studymodel = (String) sourceAsMap.get("studymodel");
  30. String description = (String) sourceAsMap.get("description");
  31. System.out.println(name);
  32. System.out.println(studymodel);
  33. System.out.println(description);
  34. }
  35. //关闭链接
  36. client.close()
  37. es的dsl:
  38. {
  39. "query": {
  40. "match_all": {}
  41. },
  42. "_source" : ["name","studymodel","description"]
  43. }

4. 使用es的json 拼接查询语句

  1. StringBuffer dsl = new StringBuffer();
  2. dsl.append("{\"bool\": {");
  3. dsl.append(" \"must\": [");
  4. dsl.append(" {");
  5. dsl.append(" \"term\": {");
  6. dsl.append(" \"mdid.keyword\": {");
  7. dsl.append(" \"value\": \"2fa9d41e1af460e0d47ce36ca8a98737\"");
  8. dsl.append(" }");
  9. dsl.append(" }");
  10. dsl.append(" }");
  11. dsl.append(" ]");
  12. dsl.append(" }");
  13. dsl.append("}");
  14. SearchRequest searchRequest = new SearchRequest();
  15. searchRequest.indices("my_index");
  16. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  17. searchSourceBuilder.query(ueryBuilders.wrapperQuery(dsl.toString()));
  18. //配置source源字段过虑,1显示的,2排除的
  19. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
  20. searchRequest.source(searchSourceBuilder);
  21. SearchResponse searchResponse = client.search(searchRequest);

5. query 

5.0 QueryBuilders转换为JSON字符串,方便调试
  1. QueryBuilder query = QueryBuilders.termQuery("name", "John");
  2. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  3. sourceBuilder.query(query);
  4. String json = sourceBuilder.toString();
  5. System.out.println(json);
  6. 并将其转换为JSON字符串
  7. toString()方法返回的字符串是格式化的,可以在控制台中方便地查看和调试。
5.1 Term Query
  1. {
  2. "query": {
  3. "term" : {
  4. "name": "spring"
  5. }
  6. },
  7. "_source" : ["name","studymodel"]
  8. }
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. searchSourceBuilder.query(QueryBuilders.termQuery("name","spring"));
  11. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"}, new String[]{});
5.2  terms query ES提供根据多个id值匹配的方法
  1. {
  2. "query": {
  3. "terms": {
  4. "systemAssignedTo.keyword": [
  5. "1",
  6. "2"
  7. ]
  8. }
  9. }
  10. }
  11. select * from mr_zcy where systemAssignedTo in ('1','2')
  12. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  13. String[] ids = {"1", "2"};
  14. searchSourceBuilder.query(QueryBuilders.termsQuery("systemAssignedTo.keyword",ids));
5.3 match query (匹配单个字段)
  1. {
  2. "query": {
  3. "match": {
  4. "name": {
  5. "query": "spring开发",
  6. "operator": "or"
  7. }
  8. }
  9. },
  10. "_source" : ["name"]
  11. }
  12. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  13. searchSourceBuilder.query(QueryBuilders.matchQuery("name","spring开发").operator(Operator.OR));
  14. searchSourceBuilder.fetchSource(new String[]{"name"}, new String[]{});

5.4 minimum_should_match
  1. {
  2. "query": {
  3. "match": {
  4. "description": {
  5. "query": "spring开发框架",
  6. "minimum_should_match": "80%"
  7. }
  8. }
  9. }
  10. }
  11. spring开发框架 会被分为三个词:spring、开发、框架
  12. 设置 minimum_should_match:80% 表示,三个词在文档的匹配占比为 80%,即 3 * 0.8=2.4,向上取整得2,表示至少有 两个词 在文档中要匹配成功。
  13. searchSourceBuilder.query(QueryBuilders.matchQuery("description","spring开发框架").minimumShouldMatch("80%"));
5.5 multi query (匹配多个字段)
  1. {
  2. "query": {
  3. "multi_match": {
  4. "query": "spring框架",
  5. "minimum_should_match": "50%",
  6. "fields": [
  7. "name^10",
  8. "description"
  9. ]
  10. }
  11. }
  12. }
  13. 拿关键字 spring css去匹配 name 和 description 字段。
  14. name^10 表示权重提升 10 倍,执行上边的查询,发现 name 中包括 spring 关键字的文档排在前边
  15. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框架", "name", "description").minimumShouldMatch("50%");
  16. multiMatchQueryBuilder.field("name",10);
  17. searchSourceBuilder.query(multiMatchQueryBuilder);
 5.6 布尔查询
  1. {
  2. "_source": [
  3. "name",
  4. "studymodel",
  5. "description"
  6. ],
  7. "from": 0,
  8. "size": 1,
  9. "query": {
  10. "bool": {
  11. "must": [
  12. {
  13. "multi_match": {
  14. "query": "spring框架",
  15. "minimum_should_match": "50%",
  16. "fields": [
  17. "name^10",
  18. "description"
  19. ]
  20. }
  21. },
  22. {
  23. "term": {
  24. "studymodel": "201001"
  25. }
  26. }
  27. ]
  28. }
  29. }
  30. }
  31. //创建multiMatch查询
  32. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框架", "name", "description").minimumShouldMatch("50%");
  33. multiMatchQueryBuilder.field("name",10);
  34. //创建term查询
  35. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("studymodel", 201001);
  36. //创建布尔查询
  37. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  38. boolQueryBuilder.must(multiMatchQueryBuilder);
  39. boolQueryBuilder.must(termQueryBuilder);
5.7 过滤器 
  1. {
  2. "_source": [
  3. "name",
  4. "studymodel",
  5. "description",
  6. "price"
  7. ],
  8. "query": {
  9. "bool": {
  10. "must": [
  11. {
  12. "multi_match": {
  13. "query": "spring框架",
  14. "minimum_should_match": "50%",
  15. "fields": [
  16. "name^10",
  17. "description"
  18. ]
  19. }
  20. }
  21. ],
  22. "filter": [
  23. {
  24. "term": {
  25. "studymodel": "201001"
  26. }
  27. },
  28. {
  29. "range": {
  30. "price": {
  31. "gte": 60,
  32. "lte": 100
  33. }
  34. }
  35. }
  36. ]
  37. }
  38. }
  39. }
  40. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  41. //创建multiMatch查询
  42. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框架", "name", "description").minimumShouldMatch("50%");
  43. multiMatchQueryBuilder.field("name",10);
  44. //布尔查询
  45. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  46. boolQueryBuilder.must(multiMatchQueryBuilder);
  47. //过虑条件
  48. boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel", "201001"));
  49. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));
  50. searchSourceBuilder.query(boolQueryBuilder);
 5.8 排序

可以在字段上添加一个或多个排序,支持在 keyword、date、float 等类型上添加,text 类型的字段上不允许添加排序。

  1. {
  2. "_source": [
  3. "name",
  4. "studymodel",
  5. "description",
  6. "price"
  7. ],
  8. "query": {
  9. "bool": {
  10. "filter": [
  11. {
  12. "range": {
  13. "price": {
  14. "gte": 0,
  15. "lte": 100
  16. }
  17. }
  18. }
  19. ]
  20. }
  21. },
  22. "sort": [
  23. {
  24. "studymodel": "desc"
  25. },
  26. {
  27. "price": "asc"
  28. }
  29. ]
  30. }
  31. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  32. //boolQuery搜索方式
  33. //定义一个boolQuery
  34. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  35. //定义过虑器
  36. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
  37. searchSourceBuilder.query(boolQueryBuilder);
  38. //添加排序
  39. searchSourceBuilder.sort("studymodel", SortOrder.DESC);
  40. searchSourceBuilder.sort("price", SortOrder.ASC);
  41. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"}, new String[]{});
  42. //向搜索请求对象中设置搜索源
  43. searchRequest.source(searchSourceBuilder);
 5.9 高亮
  1. public void testHighlight() throws IOException, ParseException {
  2. //搜索请求对象
  3. SearchRequest searchRequest = new SearchRequest("xc_course");
  4. //指定类型
  5. searchRequest.types("doc");
  6. //搜索源构建对象
  7. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  8. //boolQuery搜索方式
  9. //先定义一个MultiMatchQuery
  10. MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("开发框架", "name", "description")
  11. .minimumShouldMatch("50%")
  12. .field("name", 10);
  13. //定义一个boolQuery
  14. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  15. boolQueryBuilder.must(multiMatchQueryBuilder);
  16. //定义过虑器
  17. boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));
  18. searchSourceBuilder.query(boolQueryBuilder);
  19. //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
  20. searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
  21. //设置高亮
  22. HighlightBuilder highlightBuilder = new HighlightBuilder();
  23. highlightBuilder.preTags("<tag>");
  24. highlightBuilder.postTags("</tag>");
  25. highlightBuilder.fields().add(new HighlightBuilder.Field("name"));
  26. // highlightBuilder.fields().add(new HighlightBuilder.Field("description"));
  27. searchSourceBuilder.highlighter(highlightBuilder);
  28. //向搜索请求对象中设置搜索源
  29. searchRequest.source(searchSourceBuilder);
  30. //执行搜索,向ES发起http请求
  31. SearchResponse searchResponse = client.search(searchRequest);
  32. //搜索结果
  33. SearchHits hits = searchResponse.getHits();
  34. //匹配到的总记录数
  35. long totalHits = hits.getTotalHits();
  36. //得到匹配度高的文档
  37. SearchHit[] searchHits = hits.getHits();
  38. //日期格式化对象
  39. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  40. for(SearchHit hit:searchHits){
  41. //文档的主键
  42. String id = hit.getId();
  43. //源文档内容
  44. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  45. //源文档的name字段内容
  46. String name = (String) sourceAsMap.get("name");
  47. //取出高亮字段
  48. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  49. if(highlightFields!=null){
  50. //取出name高亮字段
  51. HighlightField nameHighlightField = highlightFields.get("name");
  52. if(nameHighlightField!=null){
  53. Text[] fragments = nameHighlightField.getFragments();
  54. StringBuffer stringBuffer = new StringBuffer();
  55. for(Text text:fragments){
  56. stringBuffer.append(text);
  57. }
  58. name = stringBuffer.toString();
  59. }
  60. }
  61. //由于前边设置了源文档字段过虑,这时description是取不到的
  62. String description = (String) sourceAsMap.get("description");
  63. //学习模式
  64. String studymodel = (String) sourceAsMap.get("studymodel");
  65. //价格
  66. Double price = (Double) sourceAsMap.get("price");
  67. //日期
  68. Date timestamp = dateFormat.parse((String) sourceAsMap.get("timestamp"));
  69. System.out.println(name);
  70. System.out.println(studymodel);
  71. System.out.println(description);
  72. }
  73. }
 5.10 聚合
  1. #聚合搜索 address 中包含 mill 的所有人的年龄分布以及平均薪资
  2. GET bank/_search
  3. {
  4. "query":{
  5. "match": {
  6. "address": "mill"
  7. }
  8. },
  9. "aggs": {
  10. "ageAgg": {
  11. "terms": {
  12. "field": "age",
  13. "size": 10
  14. }
  15. },
  16. "balanceAvg":{
  17. "avg":{
  18. "field": "balance"
  19. }
  20. }
  21. },
  22. "size": 0
  23. }
  24. SearchRequest searchRequest = new SearchRequest();
  25. //指定索引
  26. searchRequest.indices("bank");
  27. //指定DSL 检索条件
  28. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  29. searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
  30. //按照年龄只分布进行聚合
  31. TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
  32. searchSourceBuilder.aggregation(ageAgg);
  33. //计算平均薪资
  34. AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("blance");
  35. searchSourceBuilder.aggregation(balanceAvg);
  36. //打印检索条件
  37. System.out.println("检索条件:"+searchSourceBuilder);
  38. searchRequest.source(searchSourceBuilder);
  39. //执行检索
  40. SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
  41. SearchHits hits = search.getHits();
  42. SearchHit[] searchHits = hits.getHits();
  43. for (SearchHit hit: searchHits){
  44. String sourceAsString = hit.getSourceAsString();
  45. Accout accout = JSON.parseObject(sourceAsString, Accout.class);
  46. System.out.println(accout.toString());
  47. }
  48. //获取检索的分析信息
  49. Aggregations aggregations = search.getAggregations();
  50. // for (Aggregation aggregation : aggregations.asList()) {
  51. // System.out.println("当前聚合名字:"+aggregation.getName());
  52. // }
  53. //分类聚合
  54. Terms ageAgg1 = aggregations.get("ageAgg");
  55. for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
  56. String keyAsString = bucket.getKeyAsString();
  57. System.out.println("年龄:" + keyAsString + "人数:"+bucket.getDocCount());
  58. }
  59. //平局值
  60. Avg balanceAvg1 = aggregations.get("balanceAvg");
  61. System.out.println("平均薪资"+ balanceAvg1.getValue());

6.分页查询

6.1  from,size
  1. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  2. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  3. //分页查询,设置起始下标,从0开始
  4. searchSourceBuilder.from(0);
  5. //每页显示个数
  6. searchSourceBuilder.size(10);
  7. //source源字段过虑
  8. searchSourceBuilder.fetchSource(new String[]{"name","studymodel"}, new String[]{});
  9. searchRequest.source(searchSourceBuilder);
  10. SearchResponse searchResponse = client.search(searchRequest);

6.2 searchAfter
  1. searchSourceBuilder.query(QueryBuilders.wrapperQuery(dsl.toString()));
  2. searchSourceBuilder.size(10);
  3. searchSourceBuilder.sort("id", SortOrder.ASC);
  4. searchRequest.source(searchSourceBuilder);
  5. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  6. SearchHit[] searchHits = searchResponse.getHits().getHits();
  7. while (searchHits.length > 0) {
  8. SearchHit last = searchHits[searchHits.length - 1];
  9. sourceBuilder.searchAfter(last.getSortValues());
  10. searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  11. searchHits = searchResponse.getHits().getHits();
  12. }
6.3 Scroll分页 

Elasticsearch-Scroll分页-Java示例-CSDN博客

  1. searchSourceBuilder.query(QueryBuilders.wrapperQuery(dsl.toString()));
  2. searchSourceBuilder.size(10);
  3. searchSourceBuilder.sort("id", SortOrder.ASC);
  4. searchRequest.source(searchSourceBuilder);
  5. // 指定超时时间
  6. searchRequest.scroll(new TimeValue(5000));
  7. SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  8. long length = searchResponse.getHits().getHits().length;
  9. String scrollId = null;
  10. while (length > 0) {
  11. consumer.accept(searchResponse);
  12. scrollId = searchResponse.getScrollId();
  13. SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId)
  14. .scroll(keepAlive);
  15. searchResponse = highLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
  16. length = searchResponse.getHits().getHits().length;
  17. }
  18. // 清空快照记录,避免内存占用
  19. if (isClearScroll && scrollId != null) {
  20. ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
  21. clearScrollRequest.addScrollId(scrollId);
  22. highLevelClient.clearScrollAsync(clearScrollRequest, RequestOptions.DEFAULT, new ActionListener<ClearScrollResponse>() {
  23. @Override
  24. public void onResponse(ClearScrollResponse clearScrollResponse) {
  25. }
  26. @Override
  27. public void onFailure(Exception e) {
  28. throw new ElasticsearchException(e);
  29. }
  30. });
  31. }

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

闽ICP备14008679号