为ElasticSearch索引映射添加索引时脚本字段遇400错误求助
问题解决:创建索引时计算的脚本字段
错误原因
你用普通date类型字段加script参数是错误的——Elasticsearch里只有runtime字段支持通过脚本计算,要让它在索引时就完成计算并存储(而非查询时动态计算),需要给runtime字段加上index: true配置;同时脚本里要访问原始文档数据而非查询时的字段缓存,另外你的脚本还存在语法闭合不全的问题。
修正后的索引创建请求
{ "settings": { "analysis": { "analyzer": { "case_insensitive_analyzer": { "type": "custom", "filter": ["lowercase"], "tokenizer": "keyword" } } } }, "mappings": { "properties": { "id": { "type": "text" }, "events": { "properties": { "fields": { "type": "text" }, "id": { "type": "text" }, "event": { "type": "text" }, "time": { "type": "date" }, "user": { "type": "text" }, "state": { "type": "integer" } } }, "eventLast": { "type": "runtime", "runtime_type": "date", "index": true, "on_script_error": "fail", "script": { "source": """ def events = params._source.events; if (events != null && events.length > 0) { emit(events[events.length - 1].time); } """ } } } } }
关键修正点
- 将
eventLast的类型改为runtime,用runtime_type指定实际数据类型为date - 添加
index: true配置,让Elasticsearch在索引阶段就计算并存储该字段的值,而非查询时动态计算 - 脚本中使用
params._source.events获取原始文档的events数组(索引阶段不存在doc上下文) - 增加空数组判断逻辑,避免数组为空时抛出异常
- 补全了脚本的语法闭合错误
内容的提问来源于stack exchange,提问作者darnitdiy
相关产品推荐
相关产品推荐

