简体   繁体   English

可以将 OR 子句与 Haystack for Django 中的距离过滤器结合使用吗?

[英]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:我一直在使用 OR 子句中的常规 django 查询过滤器来使用距离过滤器:

# 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:我想使用 SQ 进行类似的过滤作为 haystack 查询的一部分:

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..)但相反,我得到了错误: not all arguments converted during string formatting - 这只发生在 distance_lt 查询部分,而不是~SQ(type..)

I'm able to apply the distance filtering with my haystack search query by using我可以使用 haystack 搜索查询应用距离过滤

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?我怎样才能为 ElasticSearch 构建这样一个原始查询,并且仍然将它作为我的 haystack 查询的一部分执行?

You can perform the search against the Elasticsearch connection.您可以针对 Elasticsearch 连接执行搜索。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM