How to Use Terms Query in Elasticsearch: Syntax and Examples
Use the
terms query in Elasticsearch to find documents where a field matches any value from a list of values. It accepts a field name and an array of values to match exactly. This query is useful for filtering documents by multiple exact terms efficiently.Syntax
The terms query requires specifying the field to search and an array of values to match. It looks like this:
{
"terms": {
"field_name": ["value1", "value2", "value3"]
}
}Here, field_name is the field you want to filter on, and the array contains the exact values to match. Documents with the field matching any of these values will be returned.
json
{
"terms": {
"user": ["kimchy", "elastic", "john"]
}
}Example
This example searches an Elasticsearch index for documents where the status field is either active or pending. It returns all documents matching any of these statuses.
json
{
"query": {
"terms": {
"status": ["active", "pending"]
}
}
}Output
{
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"hits": [
{"_source": {"status": "active", "user": "alice"}},
{"_source": {"status": "pending", "user": "bob"}}
]
}
}
Common Pitfalls
Common mistakes when using terms query include:
- Using a single string instead of an array of values.
- Trying to match analyzed text fields instead of keyword or exact fields.
- Confusing
term(single value) withterms(multiple values).
Always ensure the field is not analyzed or use a keyword subfield for exact matching.
json
{
"query": {
"terms": {
"status": "active"
}
}
}
// Correct usage:
{
"query": {
"terms": {
"status": ["active"]
}
}
}Quick Reference
| Feature | Description |
|---|---|
| Field | The exact field to match values on |
| Values | Array of exact values to match |
| Use case | Filter documents matching any of the given values |
| Field type | Best used on keyword or non-analyzed fields |
| Difference from term | term matches one value, terms matches multiple |
Key Takeaways
Use
terms query to match any of multiple exact values in a field.Always provide an array of values, even if matching one value.
Use on keyword or non-analyzed fields for exact matching.
Do not confuse
term (single value) with terms (multiple values).The query returns documents where the field matches any value in the list.