python - 如何使用python在Elasticsearch中将索引修改后的内容复制到另一个内容

标签 python elasticsearch

经过一些修改后,我需要将my_index中的内容复制到另一个索引中。怎么做
以下是示例数据和用于插入索引的代码。

test = [{'id':1,'name': 'A', 'subject': ['Maths', 'Accounting'],
        'type':'Contract', 'Location':'NY'},
    { 'id':2,  'name': 'AB', 'subject': ['Physics', 'Engineering'],
    'type':'Permanent','Location':'NY'},
    {'id':3,   'name': 'ABC',   'subject': ['Maths', 'Engineering'],
    'type':'Permanent','Location':'NY'}]

from elasticsearch import Elasticsearch
es = Elasticsearch()
es.indices.create(index='myindex', ignore=400)
for e in test:
        es.index(index="myindex", body=e, id=e['id'])
myindex我需要提取idname并复制到另一个索引my_index_1

最佳答案

如果“myindex”中的文档数量不是很高,则可以使用搜索API来获取所有数据并提取所需的数据并对它们进行索引。为此,您可以使用如下代码:

res = es.search(index="myindex", body={"query":{"match_all":{}}})
for item in res.get("hits").get("hits"):
    es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
如果您的数据数量较多(通常少于10000),则可以使用较高的代码,但最好使用以下限制和偏移量:
limit = 30
total_count = es.count(index="my_index", body={"query":{"match_all":{}}}).get("count")
offset = 0
while offset < total_count:
    res = es.search(index="myindex", body={"query":{"match_all":{}}}, size=limit, from_=offset)
    offset+=limit
    for item in res.get("hits").get("hits"):
        es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
如果您的数据量很大,则需要使用滚动API来获取所有文档:
es = es.search(index="myindex",body={"query":{"match_all":{}}},scroll="1m")
scroll_id = res.get("_scroll_id")
items = es.get("hits").get("hits")
while len(items):
    for item in items:
        es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
    query = {
             "scroll": "1m",
             "scroll_id": scroll_id
          }
    res =es.scroll(scroll_id=scroll_id, body=query)
    items = res.get("hits").get("hits")
    

关于python - 如何使用python在Elasticsearch中将索引修改后的内容复制到另一个内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64379063/

相关文章:

elasticsearch - Elasticsearch:通过时间戳过滤聚合

elasticsearch - 这个 Elasticsearch 查询叫什么?

elasticsearch - Elasticsearch-这个网址怎么了?

python - 如何跟踪多线程软件?

Python:简化许多 if 语句

python - 在单独的进程中读取 USB 摄像头时,OpenCV 在 OS X 上崩溃

python - 如何在可等待的子类中使用 super()?

python - python-3.6 中带有 'f' 前缀的字符串

asp.net - Elasticsearch 结合聚合

url - 从 elasticsearch 查询创建一个 Kibana URL