Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Term Query in Elasticsearch

Introduction

Elasticsearch is a powerful search engine that allows you to store, search, and analyze large amounts of data quickly and in near real-time. One of the fundamental building blocks for searching data in Elasticsearch is the Term Query.

What is a Term Query?

A Term Query in Elasticsearch is used to search for exact matches in a text field. Unlike a Match Query, which performs a full-text search, a Term Query looks for the exact term provided. This makes it particularly useful for structured data, such as keywords, tags, IDs, and other non-analyzed fields.

Syntax of a Term Query

A Term Query is represented in JSON format and has a straightforward syntax:

{ "term": { "field_name": { "value": "search_term" } } }

Where:

  • field_name: The name of the field you want to search.
  • search_term: The exact value you are looking for in the specified field.

Example of a Term Query

Suppose you have an Elasticsearch index named products with a field called category. You want to find all products in the "electronics" category. Here's how you can do it using a Term Query:

{ "term": { "category": { "value": "electronics" } } }

To run this query, you can use the following cURL command:

curl -X GET "localhost:9200/products/_search" -H 'Content-Type: application/json' -d' { "query": { "term": { "category": { "value": "electronics" } } } }'

Expected Output

{ "took": 30, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 1.0, "hits": [ { "_index": "products", "_type": "_doc", "_id": "1", "_score": 1.0, "_source": { "name": "Smartphone", "category": "electronics", "price": 699 } }, { "_index": "products", "_type": "_doc", "_id": "2", "_score": 1.0, "_source": { "name": "Laptop", "category": "electronics", "price": 999 } } ] } }

Use Cases

Term Queries are particularly useful in the following scenarios:

  • Searching for exact matches in keyword fields such as tags, categories, or IDs.
  • Filtering documents based on structured data.
  • Used in combination with other queries to narrow down search results.

Conclusion

The Term Query is a powerful tool in Elasticsearch for retrieving documents that contain exact matches. While it is not suitable for full-text search, it excels in situations where precise matching is required. Understanding how to use Term Queries effectively can significantly enhance your ability to filter and retrieve the right data in Elasticsearch.