Using term and terms query API, you can find documents that match accurate values within a specified field.
Let us learn how to use the term and terms queries in Elasticsearch.
Basic Usage
Suppose we have an index containing e-commerce information, and we want to retrieve the documents where the customer’s first name is Jim.
We can do a query similar to the one shown below:
{
"query": {
"term": {
"customer_first_name": {
"value": "jim"
}
}
}
}
Elasticsearch will go through the specified field and search for all the documents that match the set value. Below is an example output:
When using the term query, you must specify the field and the value under which to search.
Using Terms Query
The terms query is similar to the term query. However, it returns documents matching one or more precise terms.
{
"query": {
"terms": {
"customer_first_name": [
"john",
"jim"
]
}
}
}
In the example query, we get the documents matching either jim or john in the customer’s first name field.
Closing
This guide showed you how to use terms and terms queries to get documents matching single or multiple precise terms.