elasticsearch-dsl-py icon indicating copy to clipboard operation
elasticsearch-dsl-py copied to clipboard

response#hits will raise a KeyError if use filter_path=hits.hits._id on an empty result

Open BrickXu opened this issue 2 years ago • 0 comments

Hi all,

My query specify the filter_path=hits.hits.<some_fields>, response will be an empty json object like the following if no documents matched:

curl http://127.0.0.1:9200/twitter/_search\?filter_path\=hits.hits._id
{}

And I use high-level client to execute this query, it will raise a KeyError instead.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

client = Elasticsearch('http://localhost:9200')
s = Search(using=client, index='twitter').params(filter_path='hits.hits._id')
response = s.execute(ignore_cache=True)

print response.hits

=====================
Traceback (most recent call last):
  File "/Users/brick/Workspaces/python/elasticsearch-py-demo/demo.py", line 8, in <module>
    print response.hits
  File "/Users/brick/.venv/elasticsearch-py-demo/lib/python2.7/site-packages/elasticsearch_dsl/response/__init__.py", line 64, in hits
    h = self._d_["hits"]
KeyError: 'hits'

I think it would use h.get("hits", []) instead of h["hits"]:

https://github.com/elastic/elasticsearch-dsl-py/blob/dd0101042ecc0256e02e72182d6f4c62aa7cf365/elasticsearch_dsl/response/init.py#L67

BrickXu avatar Jun 02 '22 11:06 BrickXu