0
0
Elasticsearchquery~5 mins

Text vs keyword field types in Elasticsearch

Choose your learning style9 modes available
Introduction

We use text and keyword fields to store words differently so we can search and sort data easily.

When you want to search inside a sentence or paragraph, like searching words in a book.
When you want to filter or sort exact values, like filtering by country name or sorting by product code.
When you want to do full-text search with relevance scoring, like searching blog posts by keywords.
When you want to group data by exact matches, like grouping users by their exact email addresses.
Syntax
Elasticsearch
{
  "mappings": {
    "properties": {
      "field_name": {
        "type": "text" | "keyword"
      }
    }
  }
}

text fields are analyzed and broken into words for full-text search.

keyword fields are not analyzed and stored as exact values for filtering and sorting.

Examples
This defines a description field as text for full-text search.
Elasticsearch
{
  "mappings": {
    "properties": {
      "description": {
        "type": "text"
      }
    }
  }
}
This defines a country field as keyword for exact matching and sorting.
Elasticsearch
{
  "mappings": {
    "properties": {
      "country": {
        "type": "keyword"
      }
    }
  }
}
This example shows both text and keyword fields in one mapping.
Elasticsearch
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "status": {
        "type": "keyword"
      }
    }
  }
}
Sample Program

This mapping sets comment as text for searching words inside comments, and user_id as keyword for exact user ID filtering.

Elasticsearch
{
  "mappings": {
    "properties": {
      "comment": {
        "type": "text"
      },
      "user_id": {
        "type": "keyword"
      }
    }
  }
}
OutputSuccess
Important Notes

Use text fields when you want to search inside the content.

Use keyword fields when you want to filter, sort, or aggregate exact values.

Sometimes you can use both types on the same data by using multi-fields.

Summary

Text fields break content into words for searching.

Keyword fields store exact values for filtering and sorting.

Choose the field type based on how you want to use the data.