should
在使用es时,如果需要用到or逻辑,可以使用should。
minimum_should_match
should,可以配合 minimum_should_match 使用。
minimum_should_match是最低匹配度, minimum_should_match为1, 表示should条件中,至少有一项符合。
注意,should和must一起用,should会失效,加上minimum_should_match 就可以了。
示例1
比如, a && (b or c) ,可以如下所示:
{
"bool" : {
"filter" : [
{
"terms" : {
"查询条件a" : [
"a值"
],
"boost" : 1.0
}
}
],
"should" : [
{
"terms" : {
"查询条件b" : [
"b值"
],
"boost" : 1.0
}
},
{
"terms" : {
"查询条件c" : [
"c值"
],
"boost" : 1.0
}
}
],
"disable_coord" : false,
"adjust_pure_negative" : true,
"minimum_should_match" : "1",
"boost" : 1.0
}
}
对应的java代码如下:
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.filter(QueryBuilders.termsQuery("查询条件a", "a值"));
boolQuery.should(QueryBuilders.termsQuery("查询条件b", "b值"))
.should(QueryBuilders.termsQuery("查询条件c", "c值"))
.minimumShouldMatch(1);
示例2
比如, a && ((b && c) or (d && e)) ,可以如下所示:
{
"bool" : {
"filter" : [
{
"terms" : {
"查询条件a" : [
"值a"
],
"boost" : 1.0
}
}
],
"should" : [
{
"bool" : {
"must" : [
{
"terms" : {
"查询条件b" : [
"值b"
],
"boost" : 1.0
}
},
{
"term" : {
"查询条件c" : {
"value" : "值c",
"boost" : 1.0
}
}
}
],
"disable_coord" : false,
"adjust_pure_negative" : true,
"boost" : 1.0
}
},
{
"bool" : {
"must" : [
{
"terms" : {
"查询条件d" : [
"值d"
],
"boost" : 1.0
}
},
{
"term" : {
"查询条件e" : {
"value" : "值e",
"boost" : 1.0
}
}
}
],
"disable_coord" : false,
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"disable_coord" : false,
"adjust_pure_negative" : true,
"minimum_should_match" : "1",
"boost" : 1.0
}
}
对应的java代码如下:
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.filter(QueryBuilders.termsQuery("查询条件a", "值a"));
boolQuery.should(QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("查询条件b", "值b"))
.must(QueryBuilders.termQuery("查询条件c", "值c")))
.should(QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("查询条件d", "值d"))
.must(QueryBuilders.termQuery("查询条件e", "值e")))
.minimumShouldMatch(1);
System.out.println(boolQuery);
小技巧: 直接写dsl,会比较麻烦,用代码去把dsl打印出来,会方便很多。
参考资料
http://events.jianshu.io/p/84789dd89dcf
https://blog.csdn.net/qq_31748587/article/details/101449613