0
0
Elasticsearchquery~3 mins

Text vs keyword field types in Elasticsearch - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover why mixing up text and keyword fields can make your searches slow and messy--and how to fix it!

The Scenario

Imagine you have a big list of book titles and author names stored in a database. You want to search for books by exact author names or find all titles containing certain words.

The Problem

If you treat all data the same way, searching becomes slow and confusing. Exact matches fail because the system breaks text into pieces, and searching for parts of words or exact names gets mixed up. It's like trying to find a needle in a haystack without sorting the hay first.

The Solution

Using text fields lets Elasticsearch analyze and break down sentences for full-text search, while keyword fields keep data exact for filtering and sorting. This way, you get fast, accurate searches and precise matches without confusion.

Before vs After
Before
PUT books
{
  "mappings": {
    "properties": {
      "author": { "type": "text" }
    }
  }
}
After
PUT books
{
  "mappings": {
    "properties": {
      "author": {
        "type": "text",
        "fields": {
          "raw": { "type": "keyword" }
        }
      }
    }
  }
}
What It Enables

This lets you search by words inside text and also filter or sort by exact values, making your searches smarter and faster.

Real Life Example

When searching an online store, you want to find products by keywords in descriptions but also filter by exact brand names or categories. Text and keyword fields make this possible.

Key Takeaways

Text fields break down content for full-text search.

Keyword fields store exact values for filtering and sorting.

Using both together makes searching powerful and precise.