Python elasticsearch-dsl build match query dynamically

Using ElasticSearch 6.x and elasticsearch-dsl python package

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?

Source: Python Questions

LEAVE A COMMENT