前言
由于es在java中查询没法像mybatis那样方便,而且es的构造器使用也比较繁琐,理解不是很方便,所以写一篇文章来记录es构造器BoolQueryBuilder查询时各种条件的构造的正确姿势。
教程
1.构造准备
//1.构建SearchRequest请求对象,指定索引库SearchRequest searchRequest = new SearchRequest("data_info");//2.构建SearchSourceBuilder查询对象SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//2.1 这个条件用于返回所有命中条件的数据数量, 不设置则返回大概数值sourceBuilder.trackTotalHits(true);//3.检索条件构造BoolQueryBuilder bqb = QueryBuilders.boolQuery();
2.条件构造
- must可用filter代替,查询效率会更高,因为must会对结果进行_score评估
//3.1 完全匹配bqb.must(QueryBuilders.matchQuery("code", 666L); //3.2 模糊匹配bqb.must(QueryBuilders.matchPhraseQuery("name", "张"); //3.3 in的效果 传单个参数就是完全匹配bqb.must(QueryBuilders.termsQuery("code", new Long[]{1L, 2L, 3L});bqb.must(QueryBuilders.termsQuery("code", 1L, 2L, 3L); //3.4 or条件BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();shouldQuery.should(QueryBuilders.matchQuery("code", 1L);shouldQuery.should(QueryBuilders.matchQuery("code", 2L);shouldQuery.minimumShouldMatch(1); //至少满足一个bqb.must(shouldQuery); //3.5 非nullbqb.must(QueryBuilders.existsQuery("iden"));//是null bqb.mustNot(QueryBuilders.existsQuery("iden"));//3.6 大于等于gte (gt-大于 lt-小于 lte-小于等于)bqb.must(QueryBuilders.rangeQuery("time").gte(new Date()); //3.7 中文完全匹配bqb.must(queryBuilder.matchPhraseQuery("key", value));//3.8 匹配多个字段bqb.must(queryBuilder.multiMatchQuery(value, key1, key2, key3));
3.构造完成 准备查询
//4.将QuseryBuilder对象设置到SearchSourceBuilder对象中sourceBuilder.query(bqb);//5.排序sourceBuilder.sort("updateTime", SortOrder.DESC);//6.分页sourceBuilder.from((dto.getPageNum() - 1) * dto.getPageSize());sourceBuilder.size(dto.getPageSize());//7.将SearchSourceBuilder设置到SearchRequest中searchRequest.source(sourceBuilder);//8.调用方法查询数据SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); //9.解析返回结果SearchHit[] hits = searchResponse.getHits().getHits();for (int i = 0; i < hits.length; i++) { System.out.println("返回的结果: " + hits[i].getSourceAsString());}log.info("返回总数为:" + searchResponse.getHits().getTotalHits());int total = (int)searchResponse.getHits().getTotalHits().value;
原文地址: Java中使用es条件构造器BoolQueryBuilder
来源地址:https://blog.csdn.net/u011507134/article/details/128470306