Elasticsearch查询需要存在数组中的所有值

时间:2017-11-04 19:02:27

标签: elasticsearch

下面是一个示例查询:

{
    "query":{
        "constant_score":{
            "filter":{
                "terms":{
                    "genres_slugs":["simulator", "strategy", "adventure"]
                }
            }
        }
    },
    "sort":{
        "name.raw":{
            "order":"asc"
        }
    }
}

映射到genres_slugs属性的值只是一个简单的数组。

我在这里要做的是匹配所有包含数组中所有值的游戏:["simulator","strategy","adventure"]
如同,结果项必须具有所有这些值。相反,返回的结果只有一个值,而不是其他值。

现在已经持续了6个小时:(

1 个答案:

答案 0 :(得分:0)

好的,如果结果项必须包含所有这些值,请使用MUST参数而不是FILTER。

{ "query": 
    { "constant_score" : 
          { "filter" : 
               { "bool" : 
                    { "must" : [ 
                           { "term" : 
                               {"genres_slugs":"simulator"}
                           },
                           { "term" : 
                               {"genres_slugs":"strategy"}
                           },
                           { "term" : 
                               {"genres_slugs":"adventure"}
                           }]
                    }
               }
          }
    }
} 

返回:

{
    "took": 54,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 2,
        "max_score": 1,
        "hits": [
            {
                "_index": "try",
                "_type": "stackoverflowtry",
                "_id": "123",
                "_score": 1,
                "_source": {
                    "genres_slugs": [
                        "simulator",
                        "strategy",
                        "adventure"
                    ]
                }
            },
            {
                "_index": "try",
                "_type": "stackoverflowtry",
                "_id": "126",
                "_score": 1,
                "_source": {
                    "genres_slugs": [
                        "simulator",
                        "strategy",
                        "adventure"
                    ]
                }
            }
        ]
    }
}

文档:

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

https://www.elastic.co/guide/en/elasticsearch/guide/current/_finding_multiple_exact_values.html

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-common-terms-query.html