How to do it...

In the following example, we have two related objects: an Order and an Item.

Their UML representation is as follows:

The final mapping should be a merge of the field definitions of both Order and Item, plus a special field (join_field, in this example) that takes the parent/child relationship.

The mapping will be as follows:

PUT test1/_mapping
{
"properties": {
"join_field": {
"type": "join",
"relations": {
"order": "item"
}
},
"id": {
"type": "keyword"
},
"date": {
"type": "date"
},
"customer_id": {
"type": "keyword"
},
"sent": {
"type": "boolean"
},
"name": {
"type": "text"
},
"quantity": {
"type": "integer"
},
"vat": {
"type": "double"
}
}
}

The preceding mapping is very similar to the one in the previous recipe.

If we want to store the joined records, we will need to save the parent first and then the children in this way:

PUT test/_doc/1?refresh
{
"id": "1",
"date": "2018-11-16T20:07:45Z",
"customer_id": "100",
"sent": true,
"join_field": "order"
}

PUT test/_doc/c1?routing=1&refresh
{
"name": "tshirt",
"quantity": 10,
"price": 4.3,
"vat": 8.5,
"join_field": {
"name": "item",
"parent": "1"
}
}

The child item requires special management because we need to add the routing with the parent i. Furthermore, in the object, we need to specify the parent name and its ID.