How to access the response object using elasticsearch DSL for python

倾然丶 夕夏残阳落幕 提交于 2019-12-25 16:42:16

问题


I have the following code:

s = Search(using=Elasticsearch('http://user:passwd@ipaddress'), index="myindex")
q = Q("multi_match", query='some query', fields=['_all'])
s = s.query(q)

response = s.execute()
print('Total %d hits found.' % response.hits.total)
for hit in response:
    print(hit.title)

And I get the error:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/utils.py", line 102, in __getattr__
return _wrap(self._d_[attr_name])
KeyError: 'title'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "FindImage.py", line 89, in <module>
main(args.image_file)
File "FindImage.py", line 82, in main
query_db([1], [2])
File "FindImage.py", line 77, in query_db
print(hit.title)
File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/utils.py", line 105, in __getattr__
'%r object has no attribute %r' % (self.__class__.__name__, attr_name))
AttributeError: 'Result' object has no attribute 'title'

However that is in direct contradiction to what the docs state: Docs

What am I doing wrong? How can I correctly extract the hits and my values from the response?

EDIT

Also the response object ist supposed to have a method "toDict" but when I try to call it I again get an AttributeError.


回答1:


For the "toDict" question, response.to_dict() works for me. Not sure if this behaviour is the same across lib versions.




回答2:


Apparently the ".title" references an actual column in their example. When I used hit.doc.FIRSTTAG, FIRSTTAG being a column in MY NoSQL-db it worked. Still does not explain the missing method, but I am happy with it for now.

So to anyone having the same problem:

Use your own columns names when evaluating the response object e.g. in my example:

for hit in response:
  print(hit.doc.FIRSTTAG)


来源:https://stackoverflow.com/questions/37836490/how-to-access-the-response-object-using-elasticsearch-dsl-for-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!