pythondjangoopensearch

How to search by multiple fields on django_opensearch_dsl


I have an opensearch server in which I want to search items and apply some filters to the search:

search = Item.search().query("match", name="test")

I need to search items by multiple filters, like name, date, location, etc. For this I will need some other kind of queries like "range" or "terms".

Now the issue is I've trying using opensearch-dsl package like this:

 search_1 = Q("match", name="test")
 search_2 = Q("terms", name="location")
 search_3 = Q("range", name="date")
 filters = [search_1, search_2, search_3]
 query =  Q("bool", should=filters)
 search = Item.search().query(query)

This is not working, constantly returning errors like:

{"error":"unhashable type: 'Bool'"}

Event if I try to run the query individually like this:

 query = Q("match", name="test")
 search = Item.search().query(query)

How can I do a search by multiple fields?


Solution

  • I've been getting the unhashable error too - other have been unable to replicate it. However I found changing

     search = Item.search().query(query)
    

    to

     search = Item.search().query(query.to_dict())
    

    solved the problem.

    Again, those I spoke to found this confusing as django-opensearch-dsl is supposed to perform the to_dict() automatically but it wasn't doing so for me, so I would guess it's the same for you too.