AI Hints
Home›Elasticsearch Tutorial›Nested, Reindex and Aliases
Elasticsearch · Lesson 46 of 120

The nested Type

Lists of objects.

⏱ 2 min read▶ Video at 42:26🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Here's a classic trap. A product has two reviews. Ava gave five stars, and Ben gave one. Ask for products where Ben gave five stars, and Elasticsearch says yes. Why?

  • Ava: 5 stars
  • Ben: 1 star
  • Ben gave 5? Yes!?

The wrong answer

With a normal object list, the users and the stars are flattened into two separate lists. So Ben, and five, are both in there, just not together. Run it. One match, which is wrong.

Dev Tools Consoletext
PUT products/_doc/1?refresh=true&filter_path=result
{ "name": "Storm Rain Jacket",
  "reviews": [
    { "user": "Ava", "stars": 5 },
    { "user": "Ben", "stars": 1 } ] }

GET products/_count?filter_path=count
{ "query": { "bool": { "must": [
  { "match": { "reviews.user": "Ben" } },
  { "match": { "reviews.stars": 5 } } ] } } }
Output
# PUT products/_doc/1 201 Created
{"result": "created"}

# GET products/_count 200 OK
{"count": 1}

nested fixes it

Mapping reviews as nested keeps each review as its own hidden document. A nested query then checks one review at a time. Run it. Zero matches. Ben never gave five stars.

Dev Tools Consoletext
PUT products
{ "mappings": { "properties": { "reviews": { "type": "nested" } } } }

PUT products/_doc/1?refresh=true&filter_path=result
{ "name": "Storm Rain Jacket",
  "reviews": [
    { "user": "Ava", "stars": 5 },
    { "user": "Ben", "stars": 1 } ] }

GET products/_count?filter_path=count
{ "query": { "nested": { "path": "reviews", "query": { "bool": { "must": [
  { "match": { "reviews.user": "Ben" } },
  { "match": { "reviews.stars": 5 } } ] } } } } }
Output
# PUT products 200 OK
{
  "acknowledged": true,
  "shards_acknowledged": true,
  "index": "products"
}

# PUT products/_doc/1 201 Created
{"result": "created"}

# GET products/_count 200 OK
{"count": 0}

Summary

Lists of objects lose which values belong together. The nested type, with a nested query, keeps each object separate. Next, how to change a mapping.

Key takeaways
  • Flattening trap
  • type: nested
  • nested query
Next up: Changing a Mapping: Reindex — you can’t edit, you copy