Search code examples
pythonelasticsearch-dsl

Python elasticsearch-dsl sorting with multiple fields


I'm trying to form the command for sorting using elasticsearch-dsl. However I have trouble passing the variable in correct format in.

The format should be

s=Search()
s = s.sort({"time":{"order":"asc"}}, {"anoter_field":{"order":"desc"}})
s.execute()

The problem is I'm trying to put {"time":{"order":"asc"}}, {"anoter_field":{"order":"desc"}} as a variable, but I can't seem to get this in the right syntax. I tried using dict, list, and string, and none seems to work.

My input would be a dict that looks like

input = {"time":"asc", "another_field":"desc"}

Solution

  • data_input = {"time":"asc", "another_field":"desc"}
    args = [{k:{'order':v}} for k,v in data_input.items()]
    s.sort(*args)
    

    I guess is what you are asking? Its hard to tell ...