Search code examples
pythonelasticsearchindexingelasticsearch-py

How do I properly construct a query using the elasticsearch python API?


I've got some code that looks like this

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()

Examining the exception

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

And further down

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

The stack trace was huge so I just grabbed snippets of it, but the main error appears to be that "must" is not supported, at least the way I have constructed my query.

I was using this and this for guidance on constructing the query.

I can post a more complete stack trace, but I was hoping someone is able to see a very obvious error that I have made inside the "body" parameter inside the "search" method.

Can anyone see anything that I have clearly done wrong as far as constructing the query body for the python API?


Solution

  • The syntax of the query doesn't look correct to me. Try this:

    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
    )