Django-Elasticsearch-DSL嵌套范围查询

Django-Elasticsearch-DSL Nested Range Query

我正在尝试使用 django-elasticsearch-dsl 实现以下 Elasticsearch 查询,但遇到了一些困难

查询

  {
   "query":{
      "nested":{
         "path":"ip_addresses",
         "query":{
            "bool":{
               "filter":[
                  {
                     "range":{
                        "ip_addresses.ip":{
                           "gte":"192.168.1.0",
                           "lte":"192.168.1.255"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

代码

  def search_ip_range(self, start: str, end: str):
        range_query = Q('range', gte=start, lte=end)

        search = Search()
        search = search.query('nested', path='ip_addresses', query=range_query)

        try:
            response = search.execute()
            pprint("Found {} results".format(response.hits.total.value))

            for hit in response:
                pprint(hit.detail_url)
        except Exception as e:
            pprint('Search error: {}'.format(e))

错误

RequestError(400, 'parsing_exception', '[range] query does not support [gte]')

正如 elasticsearch-dsl-py 的作者所说,you'll need to use nested filters。一种选择是:

...

range_query = Q('range', ip_addresses__ip={'gte': start, 'lte': end})

search = Search()
search = search.query('nested', path='ip_addresses', query=Q('bool', filter=[range_query]))

pprint(search.to_dict())

...

您可以省略 Q(bool, filter= 部分,但 range 不会包含在其中:

search = search.query('nested', path='ip_addresses', query=range_query)

请记住,如果您 将其包装在 filter 上下文中,no scores will be calculated