ElasticSearch Query:查询必须匹配多个值中的至少一个



我需要帮助一个ElasticSearch查询,我需要结合应该和必须,但我不知道如何做到这一点:

这是我想要做的一个查询示例:

ap_code= ["ta", "All"] (OR condition)
AND
ra_code= ["ph", "All"] (OR condition)
AND
city = ["London"] 

这是查询,但它从ES

获取所有结果
"bool" : {
"must" : [
{
"match_phrase" : {
"city" : {
"query" : "London",
"slop" : 0,
"zero_terms_query" : "NONE",
"boost" : 1.0
}
}
}
],
"should" : [
{
"match_phrase" : {
"ra_code" : {
"query" : "ph",
"slop" : 0,
"zero_terms_query" : "NONE",
"boost" : 1.0
}
}
},
{
"match_phrase" : {
"ra_code" : {
"query" : "All",
"slop" : 0,
"zero_terms_query" : "NONE",
"boost" : 1.0
}
}
},
{
"match_phrase" : {
"ap_code" : {
"query" : "All",
"slop" : 0,
"zero_terms_query" : "NONE",
"boost" : 1.0
}
}
},
{
"match_phrase" : {
"ap_code" : {
"query" : "ta",
"slop" : 0,
"zero_terms_query" : "NONE",
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}

我使用Java API创建查询(JDK 11)

请帮忙好吗?提前感谢

可以在must子句中使用should查询,如下所示。

{
"query": {
"bool": {
"must": [
{
"match_phrase": {
"city": {
"query": "London",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
},
{
"bool": {
"should": [
{
"match_phrase": {
"ra_code": {
"query": "ph",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
},
{
"match_phrase": {
"ra_code": {
"query": "All",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
}
],
"minimum_should_match": 1
}
},
{
"bool": {
"should": [
{
"match_phrase": {
"ap_code": {
"query": "ta",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
},
{
"match_phrase": {
"ap_code": {
"query": "All",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
}
],
"minimum_should_match": 1
}
}
]
}
}
}

对于Java api,您可以尝试如下内容

BoolQueryBuilder first = QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery(field1, value1))
.should(QueryBuilders.matchQuery(field2, value2));
BoolQueryBuilder second= QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery(field1, value1))
.should(QueryBuilders.matchQuery(field2, value2));

BoolQueryBuilder filter = new BoolQueryBuilder()
.must(first)
.must(second);

相关内容

  • 没有找到相关文章

最新更新