如何使用elasticsearch python API正确构造查询?

时间:2016-04-29 20:25:44

标签: python elasticsearch indexing elasticsearch-py

我有一些看起来像这样的代码

from elasticsearch import Elasticsearch

client = Elasticsearch(hosts = [myhost])
try:
    results = es_client.search(
        body = {
            'query' : {
                'bool' : {
                    'must' : {
                        'term' : {
                            'foo' : 'bar',
                            'hello' : 'world'
                        }
                    }
                }
            }
        },
        index = 'index_A,index_B',
        size = 10,
        from_ = 0
    )
except Exception as e:
    ## my code stops here, as there is an exception
    import pdb
    pdb.set_trace()

检查异常

SearchPhaseExecutionException[Failed to execute phase [query], all shards failed;

进一步向下

Parse Failure [Failed to parse source [{"query": {"bool": {"must": {"term": {"foo": "bar", "hello": "world"}}}}}]]]; nested: QueryParsingException[[index_A] [bool] query does not support [must]];

堆栈跟踪很大,所以我抓住了它的片段,但主要的错误似乎是"必须"不支持,至少我构建查询的方式。

我使用thisthis作为构建查询的指导。

我可以发布更完整的堆栈跟踪,但我希望有人能够看到我在" body"中发现的一个非常明显的错误。 "搜索"内的参数方法

在构建python API的查询体时,任何人都可以看到我明显做错的事吗?

1 个答案:

答案 0 :(得分:1)

查询的语法对我来说看起来不正确。试试这个:

results = es_client.search(
    body = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "foo": {
                  "value": "bar"
                }
              }
            },
            {
              "term": {
                "hello": {
                  "value": "world"
                }
              }
            }
          ]
        }
      }
    },
    index = 'index_A,index_B',
    size = 10,
    from_ = 0
)
相关问题