编程笔记

lifelong learning & practice makes perfect

ES|索引中text和keyword的区别

Elasticsearch 中 textkeyword 是两种常用的字符串字段类型,它们的主要区别在于是否进行分词,进而影响索引和查询行为。

1. textkeyword 的区别

特性 text keyword
是否分词 会分词,进行全文分析 不分词,整体作为一个词项索引
适用场景 需要全文检索、模糊查询、相关度排序 需要精确匹配、过滤、排序、聚合
支持的查询类型 matchmatch_phrase 等全文查询 termterms 精确查询
支持聚合/排序 不支持(性能差且不合理) 支持
存储限制 无字符长度限制 默认最大长度256字符,超过不索引(可配置)
典型用途 文章内容、评论、描述等长文本 用户名、邮箱、标签、状态、ID等

2. 使用案例

2.1 Mapping 示例(含 multi-fields)

通常为了兼顾全文检索和精确匹配,字段会定义成 text 类型,同时添加一个 keyword 子字段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PUT my_index
{
"mappings": {
"properties": {
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}

这样,title 字段既可以全文检索,也可以做精确匹配和聚合。

2.2 查询示例

  • 全文检索(text 字段)
1
2
3
4
5
6
7
8
GET my_index/_search
{
"query": {
"match": {
"title": "Elasticsearch tutorial"
}
}
}
  • 精确匹配(keyword 字段)
1
2
3
4
5
6
7
8
GET my_index/_search
{
"query": {
"term": {
"title.keyword": "Elasticsearch tutorial"
}
}
}
  • 聚合示例(keyword 字段)
1
2
3
4
5
6
7
8
9
10
11
GET my_index/_search
{
"size": 0,
"aggs": {
"titles": {
"terms": {
"field": "title.keyword"
}
}
}
}

2.3 修改 Mapping

Elasticsearch 不支持直接修改已有字段的类型。如果想给已有索引新增 keyword 子字段,需要使用 动态模板或在创建索引时定义好,或者新建索引并重建数据。

示例:新增字段时定义 multi-fields

1
2
3
4
5
6
7
8
9
10
11
12
13
14
PUT my_index/_mapping
{
"properties": {
"new_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}

如果字段已存在且类型不同,修改会失败,需要新建索引。

3. 总结

  • text 适合全文检索,支持分词和相关度评分,不能用于聚合和排序。
  • keyword 适合精确匹配、过滤、排序和聚合,不分词。
  • 多数字符串字段建议用 text + keyword 多字段映射,兼顾两种需求。
  • 查询时全文检索用 match 查询 text 字段,精确匹配用 term 查询 keyword 字段。

以上内容基于 Elasticsearch 官方设计理念及社区实践总结[1][2][3][4][6]。如果需要,我可以帮你写具体的 mapping 和查询模板。

[1] https://www.cnblogs.com/hahaha111122222/p/12177377.html
[2] https://blog.csdn.net/UbuntuTouch/article/details/128904528
[3] https://cloud.tencent.com/developer/article/2357713
[4] https://bbs.huaweicloud.com/blogs/410730
[5] https://www.cnblogs.com/Rawls/p/10069670.html
[6] https://blog.csdn.net/weixin_41860630/article/details/126471632
[7] https://blog.51cto.com/u_15730090/5510216
[8] https://blog.51cto.com/u_15278282/2933670

欢迎关注我的其它发布渠道