What it does
The Term Query matches documents that contain the exact term specified in the query. It does not analyze the search term, making it ideal for finding precise values in fields like identifiers, zip codes, or status fields.
Syntax
{
"query": {
"term": {
"FIELD": {
"value": "EXACT_TERM"
}
}
}
}
For more details, refer to the official Elasticsearch Term Query documentation.
Example Query
POST my_index/_search
{
"query": {
"term": {
"user.id": {
"value": "pulse"
}
}
}
}
This query will match documents where the user.id
field exactly equals "pulse".
Common Issues
- Using Term Query on analyzed text fields: This can lead to unexpected results as the Term Query looks for the exact term, while analyzed fields may have been tokenized or modified.
- Case sensitivity: Term queries are case-sensitive. Ensure the exact case is used when searching.
- Forgetting to use the "value" key in the query structure.
Best Practices
- Use Term Query for exact matches on keyword fields or non-analyzed fields.
- For text fields that are analyzed, consider using a Match Query instead.
- When searching across multiple fields for an exact term, consider using a Terms Query.
- Use the
boost
parameter to adjust the relevance of the Term Query in multi-query searches.
Frequently Asked Questions
Q: Can I use Term Query on text fields?
A: You can use Term Query on text fields but you'd have to remember text
fields are typically analyzed, which means the original text is tokenized and possibly modified. Term Query looks for an exact match, which may not align with the analyzed tokens. For text fields, a Match Query is usually more appropriate.
Q: How does Term Query differ from Match Query?
A: Term Query looks for an exact match of the entire term, while Match Query analyzes the query string and looks for matches based on the resulting tokens. Term Query is best for keyword fields, while Match Query is better for full-text search on analyzed fields.
Q: Is Term Query case-sensitive?
A: Yes, Term Query is case-sensitive. It looks for an exact match, including the case of the characters. Make sure to use the correct case when constructing your query.
Q: Can I use wildcards in a Term Query?
A: No, Term Query does not support wildcards. If you need partial matching or pattern matching, consider using a Wildcard Query or a Prefix Query instead.
Q: How can I improve the performance of Term Queries?
A: To optimize Term Queries, ensure that you're querying on fields that are indexed and not analyzed. Using keyword fields can also improve performance. Additionally, consider using filter context instead of query context when you don't need scoring, as this can leverage caching for better performance.