Text vs Keyword in Elasticsearch: Key Differences and Usage
text fields are analyzed and broken into tokens for full-text search, while keyword fields are not analyzed and are used for exact matching and sorting. Use text for searching words inside content and keyword for filtering or aggregating exact values.Quick Comparison
This table summarizes the main differences between text and keyword fields in Elasticsearch.
| Aspect | Text Field | Keyword Field |
|---|---|---|
| Purpose | Full-text search with analysis | Exact value matching and sorting |
| Analyzed | Yes, broken into tokens | No, stored as is |
| Use Case | Search inside large text | Filter, sort, and aggregate exact values |
| Storage | Takes more space due to analysis | Compact, stores exact string |
| Performance | Slower for exact matches | Faster for exact matches |
| Example Query | Match query | Term query |
Key Differences
Text fields in Elasticsearch are designed for full-text search. They are analyzed, meaning the text is broken down into smaller pieces called tokens (like words), and these tokens are indexed. This allows Elasticsearch to find documents that contain the search terms anywhere inside the text, supporting features like stemming, stop words, and relevance scoring.
On the other hand, keyword fields are not analyzed. They store the entire string exactly as it is. This makes them ideal for filtering, sorting, and aggregations where you want to match the exact value, such as tags, IDs, or categories. Since they are not tokenized, they cannot be used for full-text search.
Choosing between text and keyword depends on your use case: use text when you want to search inside the content, and keyword when you want to filter or sort by exact values.
Code Comparison
Here is an example of defining and querying a text field for full-text search.
{
"mappings": {
"properties": {
"description": {
"type": "text"
}
}
}
}
POST /my_index/_search
{
"query": {
"match": {
"description": "quick brown fox"
}
}
}Keyword Equivalent
Here is how you define and query a keyword field for exact matching.
{
"mappings": {
"properties": {
"status": {
"type": "keyword"
}
}
}
}
POST /my_index/_search
{
"query": {
"term": {
"status": "active"
}
}
}When to Use Which
Choose text fields when you need to search inside large bodies of text, like articles, descriptions, or comments, where partial matches and relevance matter. Choose keyword fields when you need to filter, sort, or aggregate by exact values, such as tags, IDs, or status codes. Mixing both in your index is common to support both search and filtering efficiently.
Key Takeaways
text fields for full-text search with analyzed content.keyword fields for exact matching, filtering, and sorting.Text fields break content into tokens; keyword fields store exact strings.match for text and term for keyword fields.