Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Hit into a Document with elasticsearch-dsl?

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()

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

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

Here is the issue I am experiencing:

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

  • 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

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.

How can I do that?

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

like image 465
Gunee Avatar asked Sep 06 '25 17:09

Gunee


1 Answers

dict_hit = hit.to_dict()
doc = YourDocument(**dict_hit)
doc.property1 # you can access the property here
like image 158
Kiều Tâm Đỉnh Avatar answered Sep 09 '25 13:09

Kiều Tâm Đỉnh