Search code examples
pythonelasticsearchelasticsearch-dslelasticsearch-queryelasticsearch-dsl-py

Generate elastic search AND query based upon list size i.e no. of AND's in the query will be based on no. of items in the list


I have a list whose size is not fixed and can contain any no. of items.

Based on the number of items in the list, I have to generate an elastic search AND query to find the exact match of values.

For eg:

If my list contains 2 items : ['a', 'b'], my elastic search query should look like this :

Q('term', field='a') & Q('term', field='b')

Similary, if my list contains 4 items : ['a', 'b','c','d'] ;my query will look like this :

Q('term', field='a') & Q('term', field='b') & Q('term', field='c') & Q('term', field='d')

What's the right approach to generate this kind of query based upon list size?

PS : I am using elasticsearch_dsl module's Q library to generate elastic search queries.

https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html


Solution

  • the easiest is to examine what query the & operation produces and reproduce that directly. In this case: Q('bool', must=[Q('term', field=x) for x in my_list])