有没有一种方法可以使用ElasticSearch script_fields的输出来更新索引中的另一个变量?
我在ElasticSearch 1.x中有一个已启用时间戳但未存储的索引。 (有关映射,请参见下文)
这意味着可以通过搜索或使用script_fields(例如-
GET twitter/_search
{
"script_fields": {
"script1": {
"script": "_fields['_timestamp']"
}
}
}
我需要提取此时间戳字段,并将其存储在索引中。编写脚本来复制任何其他字段非常容易,例如(我正在使用更新API)
ctx._source.t1=ctx._source.message
但是,如何使用script_fields输出中的值来更新索引中的另一个字段?我希望字段“tcopy”获取每个文档的时间戳记值。
此外,我尝试使用java来获取以下值,但它返回null。
SearchResponse response = client.prepareSearch("twitter")
.setQuery(QueryBuilders.matchAllQuery())
.addScriptField("test", "doc['_timestamp'].value")
.execute().actionGet();
映射
{
"mappings": {
"tweet": {
"_timestamp": {
"enabled": true,
"doc_values" : true
},
"properties": {
"message": {
"type": "string"
},
"user": {
"type": "string"
},
"tcopy": {
"type": "long"
}
}
}
}
}
最佳答案
您需要分两次运行:
因此,要从
twitter
索引中提取时间戳数据,您可以例如使用elasticdump这样:elasticdump \
--input=http://localhost:9200/twitter \
--output=$ \
--searchBody '{"script_fields": {"ts": {"script": "doc._timestamp.value"}}}' > twitter.json
这将产生一个名为
twitter.json
的文件,其内容如下:{"_index":"twitter","_type":"tweet","_id":"1","_score":1,"fields":{"ts":[1496806671021]}}
{"_index":"twitter","_type":"tweet","_id":"2","_score":1,"fields":{"ts":[1496807154630]}}
{"_index":"twitter","_type":"tweet","_id":"3","_score":1,"fields":{"ts":[1496807161591]}}
然后,您可以轻松地使用该文件来更新文档。首先创建一个名为
read.sh
的shell脚本#!/bin/sh
while read LINE; do
INDEX=$(echo "${LINE}" | jq '._index' | sed "s/\"//g");
TYPE=$(echo "${LINE}" | jq '._type' | sed "s/\"//g");
ID=$(echo "${LINE}" | jq '._id' | sed "s/\"//g");
TS=$(echo "${LINE}" | jq '.fields.ts[0]');
curl -XPOST "http://localhost:9200/$INDEX/$TYPE/$ID/_update" -d "{\"doc\":{\"tcopy\":"$TS"}}"
done
最后,您可以像这样运行它:
./read.sh < twitter.json
脚本运行完毕后,您的文档将带有
tcopy
值的_timestamp
字段。
关于elasticsearch - Elasticsearch script_fields更新另一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44400906/