Fork me on GitHub

Learning Elasticsearch (ii)

动态更新Elasticsearch部分配置

如果需要不停机更新Elasticsearch的配置,可以使用Elasticsearch的动态配置修改机制。在Python中,使用ClusterClient实例完成:

cc = elasticsearch.client.ClusterClient(es)
setting_body = {
    'transient': {
        'setting_name': 'setting_value', #Available before next startup
    },
    'persistent': {
        'setting_name': 'setting_value', #Available permanently
    },
}
cc.put_settings(body=setting_body)

Elasticsearch快照

当我们需要定期为数据做备份时,可以使用Elasticsearch提供的快照(snapshot)功能。要如此,我们需要先注册一个快照的仓库(repository).在Python SDK中,快照的操作由快照实例完成:

sc = elasticsearch.client.SnapshotClient(es)
#Get a repo
repo = sc.get_repository()
if not repo:
    #Create a repo
    repo_settings = {
        'type': 'fs',
        'settings': {
            'compress': 'true',
            'location': '/tmp/back',
        },
    }
    sc.create_repository(repository='repo_name', body=repo_settings)

返回{acknowlegement: True}表示创建成功。注意:location属性所指定的位置必须在配置文件的path.repo列表中。例如:path.repo: ['/tmp/back', '/root/back']path.repo属性不支持动态更新

之后,为指定的索引创建快照:

snapshot_body = {
    'indices': '_all', #indices that need backup
    'ignore_unavailable': True,
    'includ_global_state': True, #Also snapshot the global state of indices
}
sc.create(repository='repo_name', snapshot='snap_name', body=snapshot_body, wait_for_completion=True)

wait_for_completion=True将等待快照完全创建结束后获取创建结果。

快照恢复

通过restore()可以将索引恢复至某个快照状态。首先需要将想要恢复的索引close掉:

#Need index instances
indices = elasticsearch.client.IndicesClient(es)
indices.close(index='index_name')

之后,恢复快照:

extra_settings = {
    'indices': 'index_name', #Specify index name that needs to be restored
    'ignore_unavailable': True,
    'includ_global_state': True, #Also restore the global state of indices
    'rename_pattern': 'rename' #Rename indices with regular expressions
    'rename_replacement': 'rename' #Rename by replacing
}
sc.restore(repository='repo_name', snapshot='snap_name', body=extra_settings)

links

social