pythonelasticsearchelasticsearch-dslelasticsearch-dsl-py

Python elasticsearch-dsl build match query dynamically


Using ElasticSearch 6.x and elasticsearch-dsl python package

I am trying to generate a match query with its options form, with the query element.

I have a list of fields fields = ['field_1', 'field_2'] and I am trying to build a leaf match query using the following method

from elasticsearch_dsl.query import MultiMatch, Match, ConstantScore

def _get_match(tokens, fields, boost):        
        for index in range(len(fields)):
                field = fields[index]
                print(Match(field={"query": tokens[index], "boost": boost}))


tokens = ['token_1', 'token_2']
fields = ['field_1', 'field_2']
boost = 3
_get_match(tokens, fields, boost) 
     

Generated output:

Match(field={'query': 'token_1', 'boost': 3})
Match(field={'query': 'token_2', 'boost': 3})

Expected output:

Match(field_1={'query': 'token_1', 'boost': 3})
Match(field_2={'query': 'token_2', 'boost': 3})

Notice, the field values instead of the field values passed in the array, the query generated used the variable name directly. How can I generate the Match query dynamically?

If I use the ** as mentioned in this SO Post it does create a dynamic query but it is in the simplified format.


Solution

  • You already mentioned the ** for unpacking a dictionary. Works fine, I only changed one line:

    print(Match(** {field: {"query": tokens[index], "boost": boost}}))