1. 程式人生 > >es的資料遷移批量指令碼

es的資料遷移批量指令碼

有大約幾種遷移方式

snapshot
reindex
logstash
elasticsearch-dump
elasticsearch-migration
Elasticsearch-Exporter

上面的方式中 snapshot 和reindex 是es自帶, snapshot適合資料量比較大
logstash 直接是工具傳輸, 和reindex一樣,只能傳資料不傳mapping
dump 是一個node 下的工具,可傳setting,mapping,data. 如果 目標庫有這個索引了,則不會同步,所以記得遷移之前,先delete到目標庫要遷移的索引
其它兩個不瞭解

本文采用的方式及前置準備

我個人是傾向於reindex的,因為這個是自帶工具且方便簡單,但其不能傳mapping.
傳mapping用dump,其需要node環境,由於mapping都比較小,在dump來傳送也OK,

reindex需要在執行此語句的es中配置下白名單
即在elasticsearch.yml中配置

 reindex.remote.whitelist: "另一臺es的ip:9200"

dump則是需要 node環境進行安裝

npm install elasticdump -g

指令碼執行

if __name__ == '__main__':
    print("----------------")

    source_es_url = "http://xxx:9200"
    target_es_url = "http://xx:9200"

    index_name_list = ["aaa","bbb"]

    for index_name in index_name_list:
        # delete 此index

        url = "{}/{}".format(target_es_url,index_name)
        t = requests.delete(url)
        print("--------------------當前遷移索引:"+index_name)
        print(index_name+"刪除結果:"+str(t.content))

        # 用dump遷移mapping
        cmd = "elasticdump --input={}/twitter --output={}/twitter --type=mapping".format(source_es_url,target_es_url)
        cmd_result = os.popen(cmd)
        print(cmd_result.read())

        # 遷移資料
        cmd3_text = """
            {"source": {
                      "remote": {
                        "host": \""""+source_es_url+"""\"
                      },                              
                      "index": \""""+index_name+"""\"
                    },
                    "dest": {
                      "index": \""""+index_name+"""\"
                    }
                  }
              """

        url = "{}/_reindex?pretty".format(target_es_url)
        t = requests.post(url,data=cmd3_text)
        print(index_name+"遷移結果:"+str(t.content))

說明:
這個指令碼是自已的機器執行
遷移mapping的cmd 是要有elasiticdump工具的環境
遷移資料用reindex 是需要 源es和目標es的網路能共通,並不是由本機去做轉發

為什麼資料不用dump來遷移呢?dump有個問題,是要用執行dump的機器做轉發,如果資料量比較可觀,那傳輸會比較慢。但其實如果把dump工具裝在其中一個es伺服器上,速度也是OK的。這邊由於伺服器沒有 node環境,所以用reindex.

如果兩臺機網路不通,則可以使用dump.
dump的一些簡單使用:
遷移單個:

elasticdump --input=http://source_ip:port/test_index --output=http://target_ip:port/test_index --type=settings
elasticdump --input=http://source_ip:port/test_index --output=http://target_ip:port/test_index --type=mapping
elasticdump --input=http://source_ip:port/test_index --output=http://target_ip:port/test_index --type=data

批量

elasticdump --input=http://source_ip:port --output=http://target_ip:port

參考