Elasticsearch給所有記錄新增一個字段:(1)字段是固定值 (2)字段是其他字段計算值
1. 固定值: _update_by_query加固定值字段
新增一個speaker_bak字段,值是'HAMLET'
方法1:
POST hamlet/_update_by_query
{
"script": {
"source": "ctx._source.speaker_bak='HAMLET'",
"lang": "painless"
},
"query": {
"match_all": {}
}
}
現在我們刪掉這個字段, 用pipeline再試一次
POST hamlet/_update_by_query
{
"script": {
"source": "ctx._source.remove('speaker_bak')",
"lang": "painless"
}
}
擴展 如果存在字段 talked, 則將它的值增加increment;否則賦值為1:
POST hamlet/_update_by_query
{
"script": {
"lang": "painless",
"source": """
if(ctx._source.talked != null){
ctx._source.talked += params.increment;
} else {
ctx._source.talked = 1;
}
""",
"params": {
"increment": 3
}
}
}
方法2:通過 pipeline
PUT _ingest/pipeline/addSpeakerBak
{
"description": "增加字段的pipeline",
"processors": [
{
"set": {
"field": "speaker_bak",
"value": "HAMLET"
}
}
]
}
POST hamlet/_update_by_query?pipeline=addSpeakerBak
2. 新加一個計算值字段(通過其他字段)
新增一個entry_len字段,值是text_entry字段的長度
POST hamlet/_update_by_query
{
"script": {
"source": "ctx._source.entry_len=ctx._source.text_entry.length()",
"lang": "painless"
},
"query": {
"match_all": {}
}
}
3.已有字段改名:舊字段改名
貌似只能通過pipeline
PUT _ingest/pipeline/renameField
{
"description": "舊字段改名",
"processors": [
{
"rename": {
"field": "text_entry",
"target_field": "textEntry"
}
}
]
}
POST hamlet/_update_by_query?pipeline=renameField