ES使用QueryBuilder时must和should无法同时生效的问题

大概的代码类似这样:

List<Integer> list = Arrays.asList(25,256,155);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termsQuery("field1","111"));

//查询满足list集合任意一个条件的数据
list.forEach(x->{                    
  queryBuilder.should(QueryBuilders.termQuery("field2",x));
             });

queryBuilder.must(QueryBuilders.termsQuery("field3","333"));
queryBuilder.must(QueryBuilders.termsQuery("field4","444"));

但是发现must能生效,should过滤是不生效的,原因是这里should是or逻辑,没限定至少有一个should成功,需要加一句:

minimumShouldMatch(1);

据说还有个方法是,把should嵌套到must里,但是我试的时候有问题,死循环了

//主查询对象
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
List<Integer> list = Arrays.asList(25,256,155);

queryBuilder.must(QueryBuilders.termsQuery("field1","111"));

//should查询对象
BoolQueryBuilder shouldQ= QueryBuilders.boolQuery();
list.forEach(x->{                    
  shouldQ.should(QueryBuilders.termQuery("field2",x));
             });
//将should查询对象设置到 must 方法中
queryBuilder.must(shouldQ)
queryBuilder.must(QueryBuilders.termsQuery("field3","333"));
queryBuilder.must(QueryBuilders.termsQuery("field4","444"));

 

Leave a Reply

Your email address will not be published. Required fields are marked *