37.es中批量寫入數據


批量寫入:

# https://www.cnblogs.com/Neeo/articles/10788573.html可以看這個博客
import time
from elasticsearch import Elasticsearch
from elasticsearch import helpers
es = Elasticsearch(["127.0.0.1:9200"])

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        print('共耗時約 {:.2f} 秒'.format(time.time() - start))
        return res
    return wrapper

@timer
def gen():
    """ 使用生成器批量寫入數據 """
    with open("./word.txt", "r", encoding="utf-8") as f:
        actions = ({
                "_index": "word",
                "_type": "doc",
                "_source": {   # 這個字段中寫你需要輸入的數據,因為是一個字典所以可以寫入多個字段
                    "word": line.strip()
                }
            } for line in f)  # 建議這里使用生成器,不要直接使用列表,沒有寫過大數據的可以試一下,如果是一個列表的話,這個時候你查看任務管理器,會發現內存被撐爆了,程序直接停止運行,同時電腦卡主,重啟吧。

        helpers.bulk(es, actions=actions)
gen()

最后我這里寫入了21萬的數據,共耗時約 16.82 秒


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM