2

我有以下代码:

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)

我得到了错误:

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'

然而,这与文档声明的内容直接矛盾: Docs

我究竟做错了什么?如何从响应中正确提取命中和我的值?

编辑

此外,响应对象应该有一个方法“toDict”,但是当我尝试调用它时,我再次得到一个 AttributeError。

4

2 回答 2

4

对于“toDict”问题,response.to_dict()对我有用。不确定此行为在不同的 lib 版本中是否相同。

于 2018-09-17T04:44:28.480 回答
1

显然,“.title”在他们的例子中引用了一个实际的列。当我使用hit.doc.FIRSTTAGFIRSTTAG 作为 MY NoSQL-db 中的一列时,它起作用了。仍然没有解释缺少的方法,但我现在对它很满意。

所以对于任何有同样问题的人:

在评估响应对象时使用您自己的列名,例如在我的示例中:

for hit in response:
  print(hit.doc.FIRSTTAG)
于 2016-06-15T13:39:34.463 回答