前言
由于es在java中查询没法像mybatis那样方便,而且es的构造器使用也比较繁琐,理解不是很方便,所以写一篇文章来记录es构造器BoolQueryBuilder查询时各种条件的构造的正确姿势。
教程
1.构造准备
1 2 3 4 5 6 7 8
| SearchRequest searchRequest = new SearchRequest("data_info");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.trackTotalHits(true);
BoolQueryBuilder bqb = QueryBuilders.boolQuery();
JAVA
|
2.条件构造
- must可用filter代替,查询效率会更高,因为must会对结果进行_score评估
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| bqb.must(QueryBuilders.matchQuery("code", 666L);
bqb.must(QueryBuilders.matchPhraseQuery("name", "张");
bqb.must(QueryBuilders.termsQuery("code", new Long[]{1L, 2L, 3L}); bqb.must(QueryBuilders.termsQuery("code", 1L, 2L, 3L);
BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery(); shouldQuery.should(QueryBuilders.matchQuery("code", 1L); shouldQuery.should(QueryBuilders.matchQuery("code", 2L); shouldQuery.minimumShouldMatch(1); bqb.must(shouldQuery);
bqb.must(QueryBuilders.existsQuery("iden"));
bqb.mustNot(QueryBuilders.existsQuery("iden"));
bqb.must(QueryBuilders.rangeQuery("time").gte(new Date());
bqb.must(queryBuilder.matchPhraseQuery("key", value));
bqb.must(queryBuilder.multiMatchQuery(value, key1, key2, key3));
JAVA
|
3.构造完成 准备查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| sourceBuilder.query(bqb);
sourceBuilder.sort("updateTime", SortOrder.DESC);
sourceBuilder.from((dto.getPageNum() - 1) * dto.getPageSize()); sourceBuilder.size(dto.getPageSize());
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
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
|