0
0
ElasticsearchHow-ToBeginner · 4 min read

How to Use Term Query in Elasticsearch: Syntax and Examples

Use the term query in Elasticsearch to find documents that contain an exact value in a specific field. It matches the exact term without analyzing it, making it ideal for keyword or ID searches. The query syntax includes specifying the field and the exact value to match inside the term object.
📐

Syntax

The term query syntax requires you to specify the field name and the exact value you want to match. It looks like this:

  • field: The name of the field to search.
  • value: The exact term to match in that field.

This query does not analyze the value, so it matches the exact term as stored.

json
{
  "query": {
    "term": {
      "field_name": {
        "value": "exact_value"
      }
    }
  }
}
💻

Example

This example searches for documents where the status field exactly matches the term active. It returns all documents with that exact status.

json
{
  "query": {
    "term": {
      "status": {
        "value": "active"
      }
    }
  }
}
Output
{ "hits": { "total": 2, "hits": [ {"_id": "1", "_source": {"status": "active", "user": "alice"}}, {"_id": "3", "_source": {"status": "active", "user": "bob"}} ] } }
⚠️

Common Pitfalls

One common mistake is using term query on analyzed text fields. Since term matches exact terms, it won't find matches if the field is analyzed (split or lowercased). Use keyword type fields or non-analyzed fields for term queries.

Another pitfall is confusing term with match query. match analyzes the input and is better for full-text search, while term is for exact matches.

json
{
  "query": {
    "term": {
      "description": {
        "value": "Quick Brown Fox"
      }
    }
  }
}

// This may return no results if 'description' is analyzed and stored in lowercase.

// Correct approach:
{
  "query": {
    "term": {
      "description.keyword": {
        "value": "Quick Brown Fox"
      }
    }
  }
}
📊

Quick Reference

Term Query ComponentDescription
field_nameThe exact field to search in the document
valueThe exact term to match in the field
case sensitivityTerm query is case sensitive and matches exact terms
use caseBest for keyword, ID, or exact value searches
not forFull-text search on analyzed text fields

Key Takeaways

Use term query to find exact matches on keyword or non-analyzed fields.
The query matches the exact value without analyzing or tokenizing it.
Avoid using term on analyzed text fields; use keyword subfields instead.
For full-text search, prefer match query over term.
Specify the field and exact value inside the term query object.