【问题标题】:How to access the response object using elasticsearch DSL for python如何使用 elasticsearch DSL for python 访问响应对象
【发布时间】:2016-10-16 15:08:27
【问题描述】:

我有以下代码:

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。

【问题讨论】:

    标签: python elasticsearch elasticsearch-dsl


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多