A term query is a query type in Elasticsearch that is used to search for documents that contain an exact term in a field. It matches the exact term, including its case.
The term query is often used for searching fields that contain exact values, such as IDs, dates, or keywords. Unlike the match query, which analyzes the search term to generate a list of terms that are used to search the index, the term query searches for an exact match.
Here is an example of a term query in Elasticsearch:
GET /my_index/_search { "query": { "term": { "category": "books" } } }
In this example, we are searching the `category` field in the `my_index` index for the exact term “books”. The term query will return any documents that contain the exact term “books” in the `category` field.
It is important to note that the term query is case-sensitive, meaning that it will only match documents that contain the exact term, including its case. If you need to perform a case-insensitive search, you can use a combination of the term query and the lowercase filter to convert the search term to lowercase before searching:
GET /my_index/_search { "query": { "term": { "category.keyword": { "value": "BOOKS" } } }, "script_fields": { "category_lower": { "script": "params['_source']['category'].toLowerCase()" } } }
In this example, we are using the `category.keyword` field, which is not analyzed and is case-sensitive. We are also using a script field to convert the `category` field to lowercase, which can be useful for displaying the search results in a consistent format.