Elasticsearch給全部文檔添加新的字段

  • 大致有三種解決方法
    • scan and scroll all documents
    • _update_by_query api
    • re-index and add new fields, use the /_reindex API
  • 首先要設(shè)置允許script運行,修改elasticsearch.yml
script.engine.groovy.inline.aggs: on
script.engine.groovy.inline.search: on
script.engine.groovy.inline.update: on

或者
script.inline: true

  • scan anc scroll all documents
    • use /_search?scroll to fetch the docs
    • perform your operation
    • send /_bulk update requests
POST bt/bt/_update
{
    "script" : "ctx._source.new_field = \"value_of_new_field\""
}
  • _update_by_query API
POST bt/bt/_update_by_query
{
  "script": {
    "inline": "if (ctx._source.bt0 == null || ctx._source.bt1==null) { ctx._source.btNew1=null } else { ctx._source.btNew1 = ctx._source.bt0 + ctx._source.bt1 }"
  }
}
{
  "source": {
    "index": "bt",
    "type": "bt"
  },

  "dest": {
    "index": "new_bt1"
  },
  "script": {
    "inline": "if (ctx._source.bt0 == null || ctx._source.bt1==null) { ctx._source.btPlus=null } else { ctx._source.btPlus = ctx._source.bt0 + ctx._source.bt1 }"
  }
}
  • Difference between _update_by_query and _reindex
    • Just like _update_by_query, _reindex gets a snapshot of the source index but its target must be a different index so version conflicts are unlikely.
    • Unlike _update_by_query, the script is allowed to modify the document’s metadata.

其實_update_and_query和_reindex的實現(xiàn)差不多,性能沒有測過,不過應(yīng)該差不多。所以elasticsearch還有task api可以用來檢測這兩個任務(wù)運行情況。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容