如何使用elasticsearch-dsl将命中转换为文档? [英] How to convert a Hit into a Document with elasticsearch-dsl?

查看:108
本文介绍了如何使用elasticsearch-dsl将命中转换为文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为ES中的文档考虑以下映射。

Consider the following mapping for a document in ES.

class MyDoc(elasticseach_dsl.Document):
    id_info = Object(IdInfo)

class IdInfo(elasticseach_dsl.InnerDoc):
    id = Keyword()
    type = Keyword()

使用elasticsearch-dsl,有两种方法(我感兴趣的)检索文档:

Using elasticsearch-dsl, there are 2 ways of retrieving a document (that I am interested in):


  • 使用 MyDoc.search()。query()。execute(),会产生 Hit 对象

  • 使用 MyDoc.get(),生成的 MyDoc 对象

  • Using MyDoc.search().query().execute(), that yields Hit objects
  • Using MyDoc.get(), that yields a MyDoc object

这是我遇到的问题:

当我从ES检索同一文档时,该文档丢失了,例如 type 字段时,我得到了不同的行为:

When I retrieve the same document from ES, and that document is missing, for example, the type field, I get different behaviours:


  • 使用 search()时: doc Hit 对象,访问 doc.type 会引发 KeyError

  • 使用 get()时: doc MyDoc 对象,访问 doc.type 只会返回 None

  • When using search(): doc being a Hit object, accessing doc.type raises a KeyError
  • When using get(): doc being a MyDoc object, accessing doc.type simply returns None

要解决此差异,我想将 Hit 实例转换为 MyDoc 实例,这样我就可以始终使用 doc.type 语法而不会引发任何错误。

To workaround this discrepancy, I would like to convert a Hit instance to a MyDoc instance, so that I can always use the doc.type syntax without any errors being raised.

我该怎么做?

或者,有没有一种方法可以访问 Hit 实例,与 MyDoc 实例相同的行为?

Alternatively, is there a way that I could access Hit instances with the same behaviour as MyDoc instances?

推荐答案

我知道这是一个有点尴尬和烦人,它曾经在低于6的版本上工作。

I know it is a bit awkward and annoying, it used to work with versions below 6.

我找到了一种解决方法,如果您从Elasticsearch响应中提取字典,则可以要求文档类对其进行解释像下面这样。

I found a workaround, if you take the dictionary coming out from elasticsearch response you can then ask the document class to interpret it like the following.

query = MyDoc.search()

response = query.execute()

my_doc = MyDoc.from_es(response.hits.hits[0])

这篇关于如何使用elasticsearch-dsl将命中转换为文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆