如何编写ES查询:字段存在且具有值

时间:2017-05-23 20:35:50

标签: python elasticsearch

我需要编写一个ElasticSearch查询来查找某个字段存在且具有特定值的文档。我尝试过以下操作:

query = {
    'query': {
        'bool': {
            'must': [
                {'exists': {'field': 'A'}},
                {'term': {'A': 'value1'}}
            ]
        }
    }
}

es.search('my_index', body=query)

但我回来了:

RequestError: TransportError(400, 'search_phase_execution_exception', 'failed to create query: {\n  "bool" : {\n    "must" : [\n      {\n        "exists" : {\n          "field" : "A",\n          "boost" : 1.0\n        }\n      },\n      {\n        "term" : {\n          "A" : {\n            "value" : "value1",\n            "boost" : 1.0\n          }\n        }\n      }\n    ],\n    "disable_coord" : false,\n    "adjust_pure_negative" : true,\n    "boost" : 1.0\n  }\n}')

...

如何编写此类查询?

更新

看起来我无法构建此查询,因为该字段' A'没有编入索引,所以我无法进行术语查询。如果它有助于其他人,请按照以下方式找到答案:

curl -s -u <user>:<pass> '<address>:9200/my_index/_search?error_trace=true' -d \
'{"query":{"bool":{"must":[{"exists":{"field":"A"}},{"term":{"A":"value1"}}]}}}'

{"error":{"root_cause":[{"type":"query_shard_exception","reason":"failed to create query: 
{\n  \"bool\" : {\n    \"must\" : [\n      {\n        \"exists\" : {\n          \"field\" : \"A\",\n          \"boost\" : 1.0\n        }\n      },\n      {\n        \"term\" : {\n          \"A\" : {\n            \"value\" : \"value1\",\n            \"boost\" : 1.0\n          }\n        }\n      }\n    ],\n    \"disable_coord\" : false,\n    \"adjust_pure_negative\" : true,\n    \"boost\" : 1.0\n  }\n}","index_uuid":"uuid1","index":"my_index","stack_trace":"[my_index/x] 
QueryShardException[failed to create query: {\n  \"bool\" : {\n    \"must\" : [\n      {\n        \"exists\" : {\n          \"field\" : \"A\",\n          \"boost\" : 1.0\n        }\n      },\n      {\n        \"term\" : {\n          \"A\" : {\n            \"value\" : \"value1\",\n            \"boost\" : 1.0\n          }\n        }\n      }\n    ],\n    \"disable_coord\" : false,\n    \"adjust_pure_negative\" : true,\n    \"boost\" : 1.0\n  }\n}]; 
nested: IllegalArgumentException[Cannot search on field [A] since it is not indexed.]

0 个答案:

没有答案