0

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

zubug55
  • 729
  • 7
  • 27

2 Answers2

0

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

Honza Král
  • 2,982
  • 14
  • 11
0

My solution to perform the & operation was to produce match query for every item in the list.

must = []
for item in my_list:    
    must.append({'match': {'field_name': item}})
query = Q('bool', must=must)
zubug55
  • 729
  • 7
  • 27