Elasticsearch 对索引字段的操作

1,011 阅读1分钟
  1. 增加新字段,参考方法如下,这是为索引 p_sc_one 中的所有 document 新增了一个名为 new_field 的字段,内容是“新字段”:

     POST /p_sc_one/_update_by_query
     {
       "query": { 
         "bool": { 
           "must": [
             { "match": { "guid":"0af13854-1524-48cf-82ed-48631bc6a0f5"        }}
           ]
       }
       },
       "script": {
         "source": "ctx._source.new_field = '新字段'"
       }
     }
    
  2. 修改已经存在的字段内容,参考方法如下,这是将索引 p_sc_one 中的所有 document 的 addtype 字段的内容都改为 ADDRESS :

     POST /p_sc_one/_update_by_query
     {
      "query": { 
           "match_all":{}
       },
       "script": {
         "source": "ctx._source['addtype'] = 'ADDRESS'"
       }
     }
    
  3. 删除已经存在的字段,参考方法如下,这是将索引 p_sc_one 中的所有 document 的 new_field 字段删除:

     POST /p_sc_one/_update_by_query
     {
        "query": { 
           "match_all":{}
       },
         "script" : "ctx._source.remove('new_field')"
     }
    

说明:以上命令在单机上测试,使用 kibana 对一个索引中的一万个 document 进行操作时,耗时平均都在 10s 左右,测试更大的数据,可能会出现超时报错。但是使用代码运行在比较大的数据量(如20 万)上操作基本可以进行,最大可运行上限数据量没有测试过,耗时平均在 160s 左右,参考代码如下:

from elasticsearch import Elasticsearch
updateBody = {
 "query": { 
      "match":{
          "new_field":"new_field"
      }
  },
    "script" : "ctx._source.remove('new_field')"
}
es = Elasticsearch("http://localhost:9200/",timeout = 600)
es.update_by_query(index="p_sc_one",body=updateBody)