问题描述
为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 yieldsHit
objects - Using
MyDoc.get()
, that yields aMyDoc
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 aHit
object, accessingdoc.type
raises aKeyError
- When using
get()
:doc
being aMyDoc
object, accessingdoc.type
simply returnsNone
要解决此差异,我想将 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将命中转换为文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!