Elasticsearch 7.17:索引时计算字段数据大小并存储至其他字段
在Elasticsearch 7.17索引阶段计算字段字节大小并存储的方案
完全可行,直接用Elasticsearch的**索引管道(Ingest Pipeline)**就能在文档写入索引前完成字节大小计算,无需在查询阶段或外部预处理数据。
具体实现步骤:
创建索引管道,通过脚本处理器计算目标字段的字节长度
执行以下命令创建管道(以UTF-8编码为例,这是ES默认字符编码,若数据使用其他编码可替换对应参数):PUT _ingest/pipeline/calculate_message_size { "processors": [ { "script": { "source": """ if (ctx.message != null) { ctx.message_size_bytes = ctx.message.getBytes('UTF-8').length; } """ } } ] }脚本中加入了非空判断,避免
message字段不存在时抛出异常。应用管道处理文档
有两种方式让文档经过该管道处理:- 写入时手动指定管道:每次索引文档时通过
pipeline参数指定目标管道PUT my_index/_doc/1?pipeline=calculate_message_size { "message": "hello" } - 设置索引默认管道:让指定索引的所有写入请求自动使用该管道,无需每次手动声明
PUT my_index/_settings { "index.default_pipeline": "calculate_message_size" }
- 写入时手动指定管道:每次索引文档时通过
验证结果
写入文档后执行查询:
GET my_index/_doc/1
返回结果会包含自动生成的字段:
{ "_source": { "message": "hello", "message_size_bytes": 5 } }
内容的提问来源于stack exchange,提问作者dmuensterer
相关产品推荐
相关产品推荐

