Skip to main content

On This Page

Difference Between Keyword and Text in Elasticsearch

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Difference Between Keyword and Text in Elasticsearch

Elasticsearch provides two primary field types for storing string data: keyword and text, each serving distinct purposes such as exact matching and full-text search. The keyword type stores values exactly as provided, making it ideal for filtering, sorting, and aggregations, while the text type is optimized for full-text search but lacks support for sorting and aggregations due to its analyzed nature.

Why This Matters

The distinction between keyword and text field types in Elasticsearch is crucial for achieving efficient and accurate search results, as well as for enabling proper data analysis through aggregations and sorting. Misusing these field types can lead to performance issues, incorrect search results, and difficulties in data analysis, highlighting the importance of understanding their technical realities and ideal use cases.

Key Insights

  • Elasticsearch’s keyword field type is case-sensitive and requires exact matches, making it suitable for filtering and aggregations.
  • The text field type in Elasticsearch is analyzed and tokenized, optimizing it for full-text search but limiting its use for sorting and aggregations.
  • Utilizing multi-fields in Elasticsearch allows for indexing the same field as both keyword and text, providing flexibility for both search and analytical needs.

Working Example

public record Article(String type, String title, String status) {
}

// Example of searching using the Elasticsearch Java API Client
SearchResponse<Article> response = client.search(s -> s
        .index("index")
        .query(q -> q
                .match(m -> m
                        .field("title")
                        .query("spring elasticsearch")
                        .operator(Operator.And) // require both terms
                )
        ),
        Article.class
);

Practical Applications

  • Use Case: Using the keyword type for fields like status or category in an e-commerce application to enable efficient filtering and aggregations.
  • Pitfall: Incorrectly using the text field type for fields requiring exact matching or sorting, such as usernames or product SKUs, which can lead to unexpected search results or performance issues.

References:

Continue reading

Next article

Google AI Introduces PaperBanana for Automated Publication-Ready Diagrams

Related Content