简体   繁体   中英

How to store objects/dict in elasticsearch using python

I am trying to save object inside elastic using elasticsearch library in python. Below is my class which I am using

from elasticsearch_dsl import DocType, Date, InnerDoc, Text, Object

    class Child(Object):
        child1 = Text()
        child2 = Text()

    class Parent(DocType):
        parent1 = Object()
        parent2 = Date()
        parent3 = Date()
        parent4 = Text()
        parent5 = Child()

    class Meta:
        index = 'my_index'

And below is my elastic mapping

    {
  "mappings": {
    "doc": {
      "properties": {
        "parent5": {
          "type": "object",
          "child1": {
            "tracking_number": {
              "type": "text"
            },
            "child2": {
              "type": "text"
            },
          }
        },
        "parent1": {
          "type": "object"
        },
        "parent2": {
          "type": "text"
        },
        "parent3": {
          "type": "date"
        },
        "parent4": {
          "type": "date"
        }
      }
    }
  }
}

If I change the type to 'Object' and retrieve the document in python code it gives me below error.

TypeError: Object of type 'InnerDoc' is not JSON serializable

And if I change the type to 'InnerDoc' I am able to retrieve the document but then I am not able to save it in elastic.

I am assuming my mapping are wrong but not really sure. Any kind of help/insights will be appreciated. Thanks in advance

You need to specify:

class Child(InnerDoc):
    ...

class Parent(Document):
    child = Object(Child)

you can also see a complex example in https://github.com/elastic/elasticsearch-dsl-py/blob/master/examples/parent_child.py

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM