Search code examples
pythonelasticsearchpyes

How to use TermQuery to do an AND query across multiple terms?


I'm am using elasticsearch using the pyes Python library.

Suppose I wanted to find all documents with title="Rainbow" AND artist="Kermit". The following returns documents with title="Rainbow" OR artist="Kermit". How do I change this to an AND?

query = pyes.TermQuery()
query.add("title", "rainbow")
query.add("artist","kermit")
search = pyes.Search(query)
results = conn.search(search, index_name, doc_type)

Solution

  • The answer is to wrap two TermQuery in a BooleanQuery

    q1 = pyes.TermQuery("title", "rainbow")
    q2 = pyes.TermQuery("artist", "kermit")
    query = BooleanQuery(must=[q1, q2])
    search = pyes.Search(query)
    results = conn.search(search, index_name, doc_type)