赞
踩
当你的需求是condition A & condition B & (condition C || condition D)时,在ES中使用must与should组合可解决,话不都说,直接上正确的查询语句:
{ "query":{ "bool":{ "must":[ { "bool":{ "should":[ { "match":{ "conditionA":{ "query":"A" } } } ] } }, { "bool":{ "should":[ { "match":{ "conditionB":{ "query":"B" } } } ] } }, { "bool":{ "should":[ { "constant_score":{ "filter":{ "match":{ "conditionC":{ "query":"C" } } } } }, { "constant_score":{ "filter":{ "match":{ "conditionD":{ "query":"D" } } } } } ] } } ] } } }
重点就是所有条件都包含在must中,将or的条件放到一个should中,而不是must和should平级。
Java 代码:
BoolQueryBuilder queryBuilder = boolQuery();
BoolQueryBuilder mustQueryBuilderA = boolQuery();
mustQueryBuilderA.must().add(matchQuery("conditionA", "A"));
queryBuilder.must(mustQueryBuilderA);
BoolQueryBuilder mustQueryBuilderB = boolQuery();
mustQueryBuilderB.must().add(matchQuery("conditionB", "B"));
queryBuilder.must(mustQueryBuilderA);
BoolQueryBuilder mustQueryBuilderOr = boolQuery();
mustQueryBuilderOr.should().add(matchQuery("conditionC", "C"));
mustQueryBuilderOr.should().add(matchQuery("conditionD", "D"));
queryBuilder.must(mustQueryBuilderOr);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。