我在elasticsearch中有这样的查询:
"query": {
"bool": {
"should": [
{"bool": {
"must": [
{"term": {
"field1": "value1"
}},
{"term": {
"field2": "value2"
}}
]}
},
{"bool": {
"should": [
{"term":{
"field1": "value3"
}}
]}
}
]
}
}
基本上,它是((field1 == value1 AND field2 == value2) OR (field1 == value3))
。但我还没有找到在Java API中实现它的方法。我尝试过这样的事情:
BoolQueryBuilder filter = new BoolQueryBuilder()
.should(QueryBuilders.termQuery(field1, value3)
.should(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(field1, value1))
.must(QueryBuilders.termQuery(field2, value2)))
);
但should
方法没有BoolQueryBuilder
。做正确的方法是什么?非常感谢你。
答案 0 :(得分:4)
你几乎在那里,你搞砸了一个括号。但是,让我们用更易读的代码重写您的查询:
BoolQueryBuilder first = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery(field1, value1))
.must(QueryBuilders.termQuery(field2, value2));
BoolQueryBuilder second = QueryBuilders.termQuery(field1, value3);
BoolQueryBuilder filter = new BoolQueryBuilder()
.should(first)
.should(second);