'Can OR-clauses be combined with distance filters in Haystack for Django?

I've been using a distance filter using regular django query filters within an OR-clause:

# either it's within the preset distance of the location
# OR it's not an in-person event
self.filter(Q(location__distance_lt=(geometry, LOCATION_WITHIN_D)) | ~Q(type=Event.IN_PERSON))

I want to do a similar filtering as part of a haystack query, using SQ:

queryset = queryset.filter(SQ(location__distance_lt=(geometry, LOCATION_WITHIN_D)) | ~SQ(type=Event.IN_PERSON))

but instead I get back the error: not all arguments converted during string formatting - and that only happens with the distance_lt query part, not the ~SQ(type..)

I'm able to apply the distance filtering with my haystack search query by using

queryset = queryset.dwithin('location', geometry, LOCATION_WITHIN_D)`

but I want to be able to have that 'or' condition in this sub-clause.

Is this even possible with raw querying? How can I construct such a raw query for ElasticSearch and still execute it as part of my haystack query?



Solution 1:[1]

You can perform the search against the Elasticsearch connection.

from django.contrib.gis.measure import D
from haystack.query import SearchQuerySet

sqs = SearchQuerySet('default')
be = sqs.query.backend
LOCATION_WITHIN_D = D(km=0.1)
geometry = {
    "lat": 60.1939,
    "lon": 11.1003
}

raw_query = {
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "match": {
                  "type": Event.IN_PERSON
                }
              },
              {
                "geo_distance": {
                  "distance": str(LOCATION_WITHIN_D),
                  "location": geometry
                }
              }
            ]
          }
        }
      ]
    }
  }
}
result = be.conn.search(body=raw_query, index='name-of-your-index')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1