Skip to content Skip to sidebar Skip to footer

Dynamic Queries In Elasticsearch And Issue Of Keywords

I'm currently running into a problem, trying to build dynamic queries for Elasticsearch in Python. To make a query I use Q shortсut from elasticsearch_dsl. This is something I try

Solution 1:

Suppose, filters = {'condition1':['value1'],'condition2':['value3','value4']}

Code:

    filters = data['filters_data'] 

    must_and = list() # The condition that has only one value
    should_or = list() # The condition that has more than 1 valuefor key in filters:
        if len(filters[key]) > 1:
            for item in filters[key]:
                should_or.append(Q("match", **{key:item})) 
        else:       
            must_and.append(Q("match", **{key:filters[key][0]})) 

    q1 = Bool(must=must_and)
    q2 = Bool(should=should_or)

    s = s.query(q1).query(q2) 
    result = s.execute()

One can also use terms, that can directly accept the list of values and no need of complicated for loops,

Code:

for key in filters:
        must_and.append(Q("terms", **{key:filters[key]}))

    q1 = Bool(must=must_and)

Post a Comment for "Dynamic Queries In Elasticsearch And Issue Of Keywords"