Elasticsearch索引时如何将字段部分内容复制到新字段?
在Elasticsearch中实现字段内容截取并生成新字段
你可以通过两种方式实现需求,copy_to确实只能完整复制字段内容,无法做截取处理,以下是可行方案:
方法一:使用Ingest Pipeline(索引前处理,推荐)
Ingest Pipeline能在文档写入索引前对内容做预处理,通过脚本处理器截取description的指定长度字符,生成preview字段。
创建处理Pipeline
比如要截取前20个字符并追加...,创建Pipeline的请求如下:
PUT _ingest/pipeline/generate-preview { "description": "生成description字段的预览内容", "processors": [ { "script": { "source": """ if (ctx.description != null && ctx.description.length() > 20) { ctx.preview = ctx.description.substring(0, 20) + '...'; } else { ctx.preview = ctx.description; } """ } } ] }
索引文档时指定Pipeline
索引文档时带上pipeline参数,就能自动生成preview字段:
PUT books/_doc/1?pipeline=generate-preview { "key": "123", "type": "novel", "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." }
索引完成后查询文档,preview字段会被自动填充为截取后的内容。
方法二:使用Runtime字段(查询时临时生成)
如果不需要将preview持久化存储到索引,只是查询时临时计算返回,可以用Runtime字段:
在索引映射中定义Runtime字段
PUT books { "mappings": { "runtime": { "preview": { "type": "keyword", "script": """ if (doc['description'].size() > 0 && doc['description'].value.length() > 20) { emit(doc['description'].value.substring(0, 20) + '...'); } else { emit(doc['description'].value); } """ } }, "properties": { "key": {"type": "keyword"}, "type": {"type": "keyword"}, "description": {"type": "text"} } } }
之后查询该索引时,preview字段会自动计算并返回,不会占用索引存储资源。
注意事项
- 可根据需求修改脚本中的
20为目标截取长度 - 脚本中处理了
description为空或长度不足的情况,避免运行报错 - Ingest Pipeline生成的字段会被存储,适合需要后续查询或聚合的场景;Runtime字段仅查询时计算,适合无需持久化的场景
内容的提问来源于stack exchange,提问作者Lina
相关产品推荐
相关产品推荐

