防踩坑日记(一)(ES)elasticsearch中的对象QueryBuilder同时使用should和must查询不成功
错误代码
- 下述中用用到的api方法 .should() 相当于 or, .must() 相当于 and
@Autowired private ElasticsearchTemplate elasticsearchTemplate; ... List<Integer> list = Arrays.asList(25,256,155); //查询满足list集合任意一个条件的数据 BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); list.forEach(x->{ queryBuilder.should(QueryBuilders.termQuery("id.keyword",x)); }); //查询同时满足一下条件的数据 queryBuilder.must(QueryBuilders.termsQuery("goodsClassId","5469464641646")); queryBuilder.must(QueryBuilders.termsQuery("goodsName","野草")); //查询 elasticsearchTemplate.sreach(queryBuilder ,EsGoodsData.class)
- 查询结果 使用 .should()方法的条件未生效,只查询出了使用满足 .must()方法的数据
失效原因
- should在和must同时使用的时候es内部属性 minumum_should_match 默认是 0
- 单独使用should时 minumum_should_match 默认是 1
解决方案
- 方案一:为minumum_should_match 手动设值
//代码承接上述错误代码,新增下面一行 boolQueryBuilder.minimumShouldMatch(1);
企业中实战
indexSortVO.setKeywordMerchantName(indexSortVO.getKeyword()); BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery(); nestedBoolQueryBuilder.must(QueryBuilders.matchQuery("productList.name",indexSortVO.getKeyword())); NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("productList", nestedBoolQueryBuilder, ScoreMode.None); boolQueryBuilder.should(nestedQueryBuilder); boolQueryBuilder.should(QueryBuilders.matchQuery("name",indexSortVO.getKeyword())); boolQueryBuilder.minimumShouldMatch(1);
- 方案二:将should查询对象设置到must方法中
//主查询对象 BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); List<Integer> list = Arrays.asList(25,256,155); //should查询对象 BoolQueryBuilder shouldQ= QueryBuilders.boolQuery(); list.forEach(x->{ shouldQ.should(QueryBuilders.termQuery("id.keyword",x)); }); //将should查询对象设置到 must 方法中 queryBuilder.must(shouldQ) queryBuilder.must(QueryBuilders.termsQuery("goodsClassId","5469464641646")); queryBuilder.must(QueryBuilders.termsQuery("goodsName","野草")); //查询 elasticsearchTemplate.sreach(queryBuilder ,EsGoodsData.class)
早年同窗始相知,三载瞬逝情却萌。年少不知愁滋味,犹读红豆生南国。别离方知相思苦,心田红豆根以生。