es数据迁移脚本(python)

时间:2021-07-01 04:40:52
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:indiceCreate.py
import sys
import base64
import time
import httplib
import json
## 老集群host(ip+port)
oldClusterHost = "192.168.1.85:9200"
## 老集群用户名,可为空
oldClusterUserName = "elastic"
## 老集群密码,可为空
oldClusterPassword = "elastic"
## 新集群host(ip+port)
newClusterHost = "192.168.1.118:9200"
## 新集群用户名,可为空
newClusterUser = ""
## 新集群密码,可为空
newClusterPassword = ""
DEFAULT_REPLICAS = 0
def httpRequest(method, host, endpoint, params="", username="", password=""):
conn = httplib.HTTPConnection(host)
headers = {}
if (username != "") :
'Hello {name}, your age is {age} !'.format(name = 'Tom', age = '')
base64string = base64.encodestring('{username}:{password}'.format(username = username, password = password)).replace('\n', '')
headers["Authorization"] = "Basic %s" % base64string;
if "GET" == method:
headers["Content-Type"] = "application/x-www-form-urlencoded"
conn.request(method=method, url=endpoint, headers=headers)
else :
headers["Content-Type"] = "application/json"
conn.request(method=method, url=endpoint, body=params, headers=headers)
response = conn.getresponse()
res = response.read()
return res
def httpGet(host, endpoint, username="", password=""):
return httpRequest("GET", host, endpoint, "", username, password)
def httpPost(host, endpoint, params, username="", password=""):
return httpRequest("POST", host, endpoint, params, username, password)
def httpPut(host, endpoint, params, username="", password=""):
return httpRequest("PUT", host, endpoint, params, username, password)
def getIndices(host, username="", password=""):
endpoint = "/_cat/indices"
indicesResult = httpGet(oldClusterHost, endpoint, oldClusterUserName, oldClusterPassword)
indicesList = indicesResult.split("\n")
indexList = []
for indices in indicesList:
if (indices.find("open") > 0):
indexList.append(indices.split()[2])
return indexList
def getSettings(index, host, username="", password=""):
endpoint = "/" + index + "/_settings"
indexSettings = httpGet(host, endpoint, username, password)
print index + " 原始settings如下:\n" + indexSettings
settingsDict = json.loads(indexSettings)
## 分片数默认和老集群索引保持一致
number_of_shards = settingsDict[index]["settings"]["index"]["number_of_shards"]
## 副本数默认为0
number_of_replicas = DEFAULT_REPLICAS
newSetting = "\"settings\": {\"number_of_shards\": %s, \"number_of_replicas\": %s}" % (number_of_shards, number_of_replicas)
return newSetting
def getMapping(index, host, username="", password=""):
endpoint = "/" + index + "/_mapping"
indexMapping = httpGet(host, endpoint, username, password)
print index + " 原始mapping如下:\n" + indexMapping
mappingDict = json.loads(indexMapping)
mappings = json.dumps(mappingDict[index]["mappings"])
newMapping = "\"mappings\" : " + mappings
return newMapping
def createIndexStatement(oldIndexName):
settingStr = getSettings(oldIndexName, oldClusterHost, oldClusterUserName, oldClusterPassword)
mappingStr = getMapping(oldIndexName, oldClusterHost, oldClusterUserName, oldClusterPassword)
createstatement = "{\n" + str(settingStr) + ",\n" + str(mappingStr) + "\n}"
return createstatement
def createIndex(oldIndexName, newIndexName=""):
if (newIndexName == "") :
newIndexName = oldIndexName
createstatement = createIndexStatement(oldIndexName)
print "新索引 " + newIndexName + " 的setting和mapping如下:\n" + createstatement
endpoint = "/" + newIndexName
createResult = httpPut(newClusterHost, endpoint, createstatement, newClusterUser, newClusterPassword)
print "新索引 " + newIndexName + " 创建结果:" + createResult
## main
indexList = getIndices(oldClusterHost, oldClusterUserName, oldClusterPassword)
systemIndex = []
for index in indexList:
if (index.startswith(".")):
systemIndex.append(index)
else :
createIndex(index, index)
if (len(systemIndex) > 0) :
for index in systemIndex:
print index + " 或许是系统索引,不会重新创建,如有需要,请单独处理~"
以上同步的时候设置的副本数是0,目的是加快同步速度,同步完成后需要设置副本数,如下:
curl -H "Content-Type: application/json" -XPUT 'http://192.168.1.118:9200/db_customer/_settings' -d '{
   "number_of_replicas" : 1
}'
 

es数据迁移脚本(python)的更多相关文章

  1. 运维脚本-elasticsearch数据迁移python3脚本

    elasticsearch数据迁移python3脚本 #!/usr/bin/python3 #elsearch 数据迁移脚本 #迁移工具路径 import time,os #下面命令是用到了一个go语 ...

  2. ELK数据迁移,ES快照备份迁移

    通过curl命令或者kibana快照备份,恢复的方式进行数据迁移 环境介绍 之前创建的ELK 因为VPC环境的问题,需要对ELK从新部署,但是还需要保留现有的数据,于是便有了这篇文档. 10.0.20 ...

  3. Entity Framework Code First Migrations--EF 的数据迁移

    1. 为了演示方便,首先新建一个控制台项目,然后添加对entityframework的引用 使用nuget控制台执行: Install-Package EntityFramework 2.新建一个实体 ...

  4. Mycat 分片规则详解--数据迁移及节点扩容

    使用的是 Mycat 提供的 dataMigrate 脚本进行对数据进行迁移和节点扩容,目前支持的 Mycat 是1.6 版本,由于 Mycat 是由 Java 编写的因此在做数据迁移及节点扩容时需要 ...

  5. MySQL 到 ES 数据实时同步技术架构

    MySQL 到 ES 数据实时同步技术架构 我们已经讨论了数据去规范化的几种实现方式.MySQL 到 ES 数据同步本质上是数据去规范化多种实现方式中的一种,即通过"数据迁移同步" ...

  6. 使用rdb文件进行redis数据迁移--python脚本

    查找了一些redis迁移的方法,一般做法就是 1. 从源数据库把rdb文件保存,然后传到新的主机上,启动新的redis即可 2. 把新的redis当做源数据库的slave,同步数据 今天开发提了一个测 ...

  7. 【Python】Django删除数据迁移记录

    find . -path "*migrations*" -name "*.py" -not -path "*__init__*" -exec ...

  8. Python进行Redis数据迁移

    Python进行Redis数据迁移 由于开发时的误操作,导致redis数据损坏,所以需要进行redis的数据迁移,网上大佬的教程基本都是需要下载附加工具,亦或是需要一些复杂的操作,个人觉得麻烦还不如写 ...

  9. elasticsearch-dump 迁移es数据 (elasticdump)

    elasticsearch 部分查询语句 # 获取集群的节点列表: curl 'localhost:9200/_cat/nodes?v' # 列出所有索引: curl 'localhost:9200/ ...

随机推荐

  1. phonegap3.5了结

    搞了三天的phonegap3.5.最后怎么搞都搞不好了.修改了www中的index.html的内容,clean也不行,在node.js中cordova build也不行. 反正就是apk没有更新啦.至 ...

  2. C# 日期格式转【转】

    使用:DateTime.ToString的方法(String, IFormatProvider)转换格式 using System; using System.Globalization; Strin ...

  3. Portal

    https://chenliang0571.wordpress.com/2013/12/08/openwrt-wifidog-wifi-hotspots/http://www.h3c.com.cn/M ...

  4. 改变HTML

    改变HTML 1.改变HTML输出流 JavaScript可以创建动态的HTML内容.(注意:不要在加载文档后使用document.write(),这会覆盖文档.) <%@ page langu ...

  5. Object类型

    Object类型 我们看到的大多数引用类型值都是Object类型的实例,虽然Object类型不具备多少功能,但是在储存和传输数据上的确是不错的选择. 2.对象字面量表示法 调用Object构造函数: ...

  6. HTML5与CSS3权威指南&period;pdf9

    第21章 Media Queries相关样式 该模块中允许添加媒体查询(media query)表达式,用以指定媒体类型,根据媒体类型来选择使用的样式(显示器.便携设备.电视机) 使用方法@media ...

  7. Combine Two Tables

    Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | PersonId ...

  8. Java 9 揭秘(19&period; 平台和JVM日志)

    Tips 做一个终身学习的人. 在这章中,主要介绍以下内容: 新的平台日志(logging)API JVM日志的命令行选项 JDK 9已经对平台类(JDK类)和JVM组件的日志系统进行了大整. 有一个 ...

  9. &lbrack;Swift&rsqb;LeetCode1036&period;逃离大迷宫 &vert; Escape a Large Maze

    In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y & ...

  10. server&period;xml配置介绍

    server.xml位于$TOMCAT_HOME/conf目录下,是Tomcat中最重要的配置文件,server.xml的每一个元素都对应了Tomcat中的一个组件:通过对xml文件中元素的配置,可以 ...