0

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.

1 Answer 1

0

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

print(Match(** {field: {"query": tokens[index], "boost": boost}}))
Sign up to request clarification or add additional context in comments.

2 Comments

oh yea, silly me, I could have unpacked the dictionary and included other fields directly into that. Thanks a lot for making it clear.
@inxss, I'm glad I could help. In case this solved your problem, please consider marking it as the correct answer :) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.