使用python给ElasticSearch批量添加数据

批量向ElasticSearch添加数据:

import datetime
import time

from elasticsearch import Elasticsearch
from elasticsearch.helpers import parallel_bulk
import random

# 创建 Elasticsearch 客户端
es = Elasticsearch([{'host': 'localhost', 'port': 9200, 'scheme': 'http'}], http_auth=('username', 'password'))

start_current_time = datetime.datetime.now()
start_time = time.time()
# 准备要插入的数据
data = {
    "young": 0,
    "teenager": 0,
    "mask": 0,
    "activeDirection": 0,
}

# 定义插入函数
def generate_actions(data):
    for _ in range(50000):
        doc = data.copy()
        for key in doc:
            doc[key] = random.choice([0, 1])
        action = {
            "_index": "testtest01",  # 替换为你的索引名称
            "_source": doc
        }
        yield action


# 执行并行批量插入
for success, info in parallel_bulk(es, generate_actions(data), thread_count=4, chunk_size=1000):
    if not success:
        print('A document failed:', info)

end_time = time.time()
total_time = end_time - start_time
end_current_time = datetime.datetime.now()
print(f"开始时间为:{start_current_time},结束时间是:{end_current_time},时长为:{total_time}")

删除ES数据:

# 删除某个索引
delete_index = "test03"
if es.indices.exists(index=delete_index):
    es.indices.delete(index=delete_index)
    print(f"The index {delete_index} has been deleted.")
else:
    print(f"The index {delete_index} does not exist.")



# 删除所有test开头的索引
# 获取所有以 'index' 开头的索引名称
indices = es.indices.get('*test*').keys()
# 删除所有以 'index' 开头的索引
for index in indices:
    if index.startswith('test'):
        es.indices.delete(index=index)
print('All indices starting with "index" have been deleted.')

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值