使用 path_match 对嵌套对象自动映射 keyword
解读
国内一线互联网公司在日志、订单、商品等场景大量使用 nested 结构保存明细数组。面试时考官想确认两点:
- 你是否知道 object 与 nested 的本质区别(前者扁平化、后者独立文档);
- 能否用 动态模板(dynamic template) 在索引创建阶段就把“所有叶子字符串”统一加成 keyword 多字段,从而避免后续聚合、排序、脚本异常。
题目限定用 path_match 而非 match_mapping_type,说明嵌套路径可能很深,且只需命中指定路径下的字段,而不是全局字符串。
知识点
- nested 类型:每个数组元素独立 Lucene 文档,父文档只存引用,查询需用 nested query。
- dynamic template 执行时机:文档写入时,若字段未在 mapping 中出现过,则按模板顺序匹配;匹配成功即生成 mapping,后续文档复用。
- path_match vs match:path_match 针对“字段全路径”,支持通配符,可精准定位到 nested 内部;match 仅看字段名本身。
- {name} 与 {dynamic_type} 占位符:模板中可用
{name}引用原始字段名,{dynamic_type}引用 ES 推断的类型。 - 多字段(fields):默认 text 带 keyword 子字段,但单字段聚合仍走 keyword;若关闭 text 可省磁盘。
- 模板优先级:索引显式 mapping > 动态模板 > 默认规则;模板数组按顺序匹配,命中即停止。
- nested 路径限制:path_match 写的路径是“ flattened 视角”,即
items.*.name,而非items.name。
答案
在索引 settings 中预置动态模板,示例把 nested 对象 items 下所有字符串叶子自动加成 keyword 多字段,并关闭 text 以节省空间:
PUT /order
{
"mappings": {
"dynamic_templates": [
{
"nested_string_as_keyword": {
"path_match": "items.*",
"match_mapping_type": "string",
"mapping": {
"type": "keyword",
"ignore_above": 256
}
}
}
],
"properties": {
"items": {
"type": "nested"
}
}
}
}
写入测试:
POST /order/_doc/1
{
"order_id": "A001",
"items": [
{ "sku": "iPhone14", "color": "深空黑" },
{ "sku": "AirPods", "color": "白色" }
]
}
查看 mapping 可见 items.sku 与 items.color 均为 keyword,可直接用于 terms 聚合、nested aggregation、script 排序 而无需再手动更新 mapping。
拓展思考
- 若 nested 层级更深,如
items.attrs.*,可把path_match写成items.attrs.*;若需递归匹配任意深度,可用items.**(7.13+ 支持双星)。 - 对既有索引,可用 PUT _mapping 追加动态模板,但仅对后续新字段生效;历史字段需 reindex 或 update_by_query 重建。
- 如果业务同时需要分词与聚合,可保留 text 并加 keyword 子字段,把模板改成:
"mapping": {
"type": "text",
"analyzer": "ik_max_word",
"fields": {
"keyword": { "type": "keyword", "ignore_above": 256 }
}
}
- 生产环境建议把模板写进 索引模板(index template) 或 component template,由 ILM 统一管理,避免建索引时遗漏。