05
Baeldung
作者:Diego Torres
發布:02-07 00:57
Difference Between keyword and text in Elasticsearch
Choosing keyword versus text determines whether a field is analyzed for full-text search or stored verbatim for exact matching, affecting search behavior, aggregations, sorting, and performance.
重點摘要
text fields are analyzed for full-text search and relevance scoring
keyword fields store values exactly for exact matches, filtering, sorting, and aggregations
multi-fields let you index the same field as both text and keyword to combine capabilities
Elasticsearch provides two primary string field types: text and keyword. Text fields are analyzed (tokenized, lowercased, and processed by analyzers) to support full-text search and relevance scoring, but they are not suitable for efficient sorting, aggregations, or exact matches because they store analyzed tokens rather than original values. Keyword fields store values verbatim without analysis, making them ideal for exact matching, filters, sorting, and aggregations, though they are case-sensitive and unsuitable for long free-form content. A common pattern is to use multi-fields to index a field as both text (for search) and keyword (for exact operations), giving both search and analytic capabilities at the cost of extra storage. The article includes example mappings and Java client queries to illustrate these differences and best practices.
Elasticsearch 中 keyword 与 text 的区别
选择 keyword 或 text 决定字段是否经过分析以支持全文搜索,或原样存储以支持精确匹配、排序与聚合,影响查询结果与性能。
重點摘要
text 字段会被分析器处理,适合全文检索与相关性评分
keyword 字段按原值存储,适合精确匹配、过滤、排序与聚合
使用 multi-fields 可同时为同一字段建立 text 与 keyword 版本以兼顾需求
本文介绍了 Elasticsearch 两种主要的字符串字段类型:text 与 keyword。text 字段在索引前会被分析(分词、转小写等),用于全文检索与相关性排序,但不适合用于高效排序或聚合,也不利于精确匹配;keyword 字段不做分析,按原值存储,适用于精确匹配、过滤、排序与聚合,但大小写敏感且不适合存放长文本。常见的做法是通过 multi-fields 同时为同一逻辑字段建立 text 和 keyword 版本,以同时支持全文搜索与精确聚合/排序,代价是增加索引存储。文章还给出 mapping 和 Java 客户端查询示例,说明何时选择或组合字段类型以优化查询与性能。
Elasticsearch 中 keyword 與 text 的差異
選擇 keyword 或 text 決定欄位是否經過分析以支援全文搜尋,或以原樣儲存以支援精確比對、排序與聚合,會影響查詢行為與效能。
重點摘要
text 欄位經分析器處理,適合全文檢索與相關性排序
keyword 欄位原樣儲存,適合精確比對、過濾、排序與聚合
使用 multi-fields 可同時建立 text 與 keyword 版本以兼顧搜尋與分析
本文說明 Elasticsearch 的兩種字串欄位類型:text 與 keyword。text 欄位會經過分析器(分詞、轉小寫等),適合全文檢索與相關性排序,但不支援有效的排序或聚合,且不利於精確比對;keyword 欄位則原樣儲存,適合精確比對、過濾、排序與聚合,但大小寫敏感且不適合長篇自由文字。常見做法是以 multi-fields 同時建立 text 與 keyword 版本,既能進行全文搜尋,又能對同一欄位做精確聚合或排序,但會增加索引空間。文章並附上對應的 mapping 與 Java 用戶端查詢範例,說明何時選擇或組合欄位類型以提升準確性與效能。