0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use Exists Query in Elasticsearch: Syntax and Examples

Use the exists query in Elasticsearch to find documents that contain a specific field. The query checks if the field is present and not null in the document. It is written inside the query part of your search request with the field name specified.
📐

Syntax

The exists query checks if a field exists in documents. It is used inside the query object. You specify the field name to check with field.

  • query: The main search query container.
  • exists: The type of query to check field existence.
  • field: The name of the field to check.
json
{
  "query": {
    "exists": {
      "field": "your_field_name"
    }
  }
}
💻

Example

This example searches for documents where the field user exists. It returns all documents that have the user field with any value.

json
{
  "query": {
    "exists": {
      "field": "user"
    }
  }
}
Output
{ "hits": { "total": {"value": 2, "relation": "eq"}, "hits": [ {"_id": "1", "_source": {"user": "alice", "message": "hello"}}, {"_id": "3", "_source": {"user": "bob", "message": "hi"}} ] } }
⚠️

Common Pitfalls

Common mistakes when using the exists query include:

  • Checking for a field that does not exist in any document returns no results.
  • Using exists on analyzed text fields may behave unexpectedly if the field is missing or empty.
  • Confusing exists with checking for a field value; exists only checks presence, not content.

Example of wrong and right usage:

json
{
  "query": {
    "exists": {
      "field": "nonexistent_field"
    }
  }
}

// This returns no documents because the field does not exist.

{
  "query": {
    "exists": {
      "field": "user"
    }
  }
}

// Correct usage to find documents where 'user' field exists.
📊

Quick Reference

PartDescription
queryMain container for search queries
existsQuery type to check if a field exists
fieldName of the field to check for existence

Key Takeaways

Use the exists query to find documents where a specific field is present.
Specify the field name inside the exists query under the field key.
Exists query only checks for presence, not the value of the field.
If the field does not exist in any document, the query returns no results.
Exists query is useful for filtering documents with optional or missing fields.