maestro
maestro

Reputation: 671

Elasticsearch Nested Parent-Child mapping

I'd like to map the following structure: - I have blog posts - Blog posts can have comments - Comments can have replies (which are also comments), so it should be a recursive datastructure

POST -----*--> COMMENT

COMMENT -----*---> COMMENT

Here's what I tried:

mappings: {
    "comment": {
        "properties": {
            "content": { "type": "string" },
            "replies": { "type": "comment" }
        }
    },
    "post": {
        "properties": {
            "comments": {
                  "type": "comment"
             }
        }
    }
}

Of course it's not working. How can I achieve this?

Upvotes: 0

Views: 808

Answers (2)

Nishant Kumar
Nishant Kumar

Reputation: 2169

 mappings: {
    "post": {
        "properties": {
            "content": { "type": "string" },
            "comment": {
                "properties" : {
                    "content": { "type": "string" },
                    "replies": {
                      "properties" : {
                          "content": { "type": "string" }
                      }
                  }
        }
    }
}

Upvotes: 0

Val
Val

Reputation: 217304

You're trying to declare the types as you would do in OO programming, that's not how it works in ES. You need to use parent-child relationships like below, i.e. post doesn't have a field called comments but the comment mapping type has a _parent meta field referencing the post parent type.

Also in order to model replies I suggest to simply have another field called in_reply_to which would contain the id of the comment that the reply relates to. Much easier that way!

PUT blogs
{
  "mappings": {
    "post": {
      "properties": {
        "title": { "type": "string"}
      }
    },
    "comment": {
      "_parent": {
        "type": "post" 
      },
      "properties": {
        "id": { 
          "type": "long"
        }
        "content": { 
          "type": "string"
        },
        "in_reply_to": { 
          "type": "long"
        }
      }
    }
  }
}

Upvotes: 1

Related Questions