【问题标题】:Elastic search DSL python issue弹性搜索 DSL python 问题
【发布时间】:2020-10-02 17:47:14
【问题描述】:

我一直在使用 ElasticSearch DSL python 包来查询我的弹性搜索数据库。查询方法非常直观,但我在检索文档时遇到问题。这是我尝试过的:

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
es = Elasticsearch(hosts=[{"host":'xyz', "port":9200}],timeout=400)
s = Search(using=es,index ="xyz-*").query("match_all")
response = s.execute()
for hit in response:
    print hit.title

我得到的错误:

AttributeError: 'Hit' object has no attribute 'title'

我用谷歌搜索了错误并找到了另一个 SO:How to access the response object using elasticsearch DSL for python

解决方案提到:

for hit in response:
     print hit.doc.firstColumnName

不幸的是,我又遇到了与“doc”相同的问题。我想知道访问我的文档的正确方法是什么?

任何帮助将不胜感激!

【问题讨论】:

  • 您可以 print(s.to_dict()) 和 print(response.to_dict()) 来查看对象
  • 谢谢!那确实奏效了!

标签: python elasticsearch


【解决方案1】:

我遇到了同样的问题,因为我发现了不同的版本,但这似乎取决于您使用的 elasticsearch-dsl 库的版本。您可能会探索response 对象,它是子对象。例如,使用 5.3.0 版本,我使用以下循环查看预期数据。

for hit in RESPONSE.hits._l_:
    print(hit)

for hit in RESPONSE.hits.hits:
    print(hit)

注意,出于某种奇怪的原因,这些数据元素仅限于 10 个数据元素。

print(len(RESPONSE.hits.hits))
10
print(len(RESPONSE.hits._l_))
10

如果我使用print('Total {} hits found.\n'.format(RESPONSE.hits.total)) 打印点击数,这与总点击数不匹配

祝你好运!

【讨论】:

  • 10 次命中,因为您没有在查询中提供 size 参数。 10 是默认大小。
【解决方案2】:

从版本 6 开始,响应不再返回您填充的 ​​Document 类,这意味着您的字段只是一个 AttrDict,它基本上是一个字典。

要解决这个问题,您需要有一个 Document 类来表示您要解析的文档。然后,您需要使用.from_es() 方法使用您的文档类解析命中字典。

就像我在这里回答的那样。

https://stackoverflow.com/a/64169419/5144029

还可以在这里查看Document

https://elasticsearch-dsl.readthedocs.io/en/7.3.0/persistence.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多