Chapter 41. Nested Objects
Given the fact that creating, deleting, and updating a single document in
Elasticsearch is atomic, it makes sense to store closely related entities
within the same document. For instance, we could store an order and all of
its order lines in one document, or we could store a blog post and all of its
comments together, by passing an array of comments
:
PUT
/my_index/blogpost/
1
{
"title"
:
"Nest eggs"
,
"body"
:
"Making your money work..."
,
"tags"
:
[
"cash"
,
"shares"
],
"comments"
:
[
{
"name"
:
"John Smith"
,
"comment"
:
"Great article"
,
"age"
:
28
,
"stars"
:
4
,
"date"
:
"2014-09-01"
}
,
{
"name"
:
"Alice White"
,
"comment"
:
"More like this please"
,
"age"
:
31
,
"stars"
:
5
,
"date"
:
"2014-10-22"
}
]
}
If we rely on dynamic mapping, the
comments
field will be autocreated as anobject
field.
Because all of the content is in the same document, there is no need to join blog posts and comments at query time, so searches perform well.
The problem is that the preceding document would match a query like this:
GET
/_search
{
"query"
:
{
"bool"
:
{
"must"
:
[
{
"match"
:
{
"name"
:
"Alice"
}},
{
"match"
:
{
"age"
:
28
}}
]
}
}
}
Alice is 31, not 28!
The reason for this cross-object ...
Get Elasticsearch: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.