How to write ES query: field exists AND has value

I need to write an ElasticSearch query that finds documents where a certain field exists AND has a particular value. I've tried doing the following:

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

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

But this breaks for me with a TransportError.

How can I write this type of query?

hi,

What is you language ? Does you query works in Curl ? What is the TransportError ?

thx
Xavier

I'm writing in Python. I haven't figured out how to express this in any way. The TransportError is:

RequestError: TransportError(400, 'search_phase_execution_exception', 'failed to create query: 
...

Does a simple call works :

res = es.search(index="my_index", body={"query": {"match_all": {}}})

Yes, and I can do searches like:

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

I just can't figure out the syntax for "field must exist AND value must be X".

Ok, is there error in the elasticsearch log too or only in your Python ? Can you past the full stacktrace if possible ?

Turns out the issue was that field A was not indexed, so although 'exists' worked, any sort of term search failed.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.