0
0
ElasticsearchHow-ToBeginner · 4 min read

How to Use Nested Query in Elasticsearch: Syntax and Examples

Use the nested query in Elasticsearch to search fields inside nested objects. It requires specifying the path to the nested field and a query that runs on the nested documents. This lets you match nested data accurately within arrays of objects.
📐

Syntax

The nested query has three main parts:

  • path: The nested field path you want to search inside.
  • query: The query to run on the nested documents.
  • score_mode (optional): How to combine scores from nested matches (e.g., avg, max).
json
{
  "query": {
    "nested": {
      "path": "nested_field",
      "query": {
        "match": {
          "nested_field.subfield": "value"
        }
      },
      "score_mode": "avg"
    }
  }
}
💻

Example

This example searches for documents where the nested field comments has a message containing "great".

json
{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "match": {
          "comments.message": "great"
        }
      },
      "score_mode": "avg"
    }
  }
}
Output
{ "hits": { "total": 2, "hits": [ { "_id": "1", "_source": { "comments": [ {"message": "This is great!"}, {"message": "Not bad"} ] } }, { "_id": "3", "_source": { "comments": [ {"message": "Great work"} ] } } ] } }
⚠️

Common Pitfalls

Common mistakes when using nested query include:

  • Not mapping the field as nested in the index mapping, which causes the query to fail or return wrong results.
  • Using the wrong path that does not match the nested field.
  • Forgetting to prefix nested fields with the full path in the query.
json
{
  "query": {
    "match": {
      "comments.message": "great"
    }
  }
}

// Wrong: This will not work correctly if 'comments' is nested.

{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "match": {
          "comments.message": "great"
        }
      }
    }
  }
}

// Right: Use nested query with correct path and query.
📊

Quick Reference

TermDescription
nestedQuery type to search nested objects
pathThe nested field path to query
queryThe query to run inside nested documents
score_modeHow to combine nested query scores (avg, max, none)
mappingField must be mapped as nested in index

Key Takeaways

Use the nested query to search inside nested objects accurately.
Always map fields as nested in your index before querying nested data.
Specify the correct path to the nested field in the nested query.
Prefix nested fields with their full path in the query clauses.
Use score_mode to control how nested matches affect document scores.