ElasticSearch增加字段并对历史数据赋初始值
程序员文章站
2022-04-04 12:17:29
...
elasticsearch如何为指定索引中类型添加字段并赋初值,就像数据库中添加字段为老的数据赋初始值一样。
用update_by_query结合script可以办到,例如:
POST my_index/_update_by_query
{
"script": {
"lang": "painless",
"inline": "if (ctx._source.like== null) {ctx._source.like= 'i like it'}"
}
}
@Test
public void testInitUpdateByQuery() {
String like = "i like it";
UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(INDEX_NAME);
updateByQueryRequest.setDocTypes("_doc");
/// updateByQueryRequest.setQuery(QueryBuilders.termQuery("gameId", 55555));
// 修改操作
// script 为更新内容 切记若为字符类型需要加单引号 "'" 拼接
updateByQueryRequest.setScript(new Script( "if (ctx._source.like == null) {ctx._source.like= '" + like + "'}"));
/// indexRequest.script(new Script("ctx._source.like = \"i like it\""))
try {
BulkByScrollResponse response = client.updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT);
logger.info("testInitUpdateByQuery response:{}", JSON.toJSONString(response));
System.out.println("testInitUpdateByQuery response=" + JSON.toJSONString(response));
} catch (Exception e) {
logger.error("testInitUpdateByQuery e:{}", e);
}
}
ElasticSearch 已存在mapping文档新增字段( 参考链接 https://blog.csdn.net/MrLiar17/article/details/108245497)
上一篇: 天空有点暗怎么办?教你5秒换天空!
下一篇: ps扣出来的图怎么缩小