0

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?

maestro
  • 671
  • 1
  • 13
  • 27

2 Answers2

1

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"
        }
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • Seems to be legit. A reply for a comment is also can be considered as a reply to a post. The `in_reply_to` field joins the replies to the comments. Thanks! – maestro Sep 22 '16 at 09:39
0
 mappings: {
    "post": {
        "properties": {
            "content": { "type": "string" },
            "comment": {
                "properties" : {
                    "content": { "type": "string" },
                    "replies": {
                      "properties" : {
                          "content": { "type": "string" }
                      }
                  }
        }
    }
}
Nishant Kumar
  • 2,199
  • 2
  • 22
  • 43
  • replies can also have replies – maestro Sep 22 '16 at 11:02
  • In that case add one more level of hierarchy same as comment or you can use parent mapping approach if have more levels ( https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-parent-field.html ) – Nishant Kumar Sep 22 '16 at 11:08
  • From the linked documentation: `"The parent and child types must be different — parent-child relationships cannot be established between documents of the same type."` – maestro Sep 22 '16 at 11:50