1. 程式人生 > >python批量匯入資料進Elasticsearch

python批量匯入資料進Elasticsearch

ES在之前的部落格已有介紹,提供很多介面,本文介紹如何使用python批量匯入。ES官網上有較多說明文件,仔細研究並結合搜尋引擎應該不難使用。

先給程式碼

#coding=utf-8
from datetime import datetime

from elasticsearch import Elasticsearch
from elasticsearch import helpers

es = Elasticsearch()

actions = []

f=open('index.txt')
i=1
for line in f:
    line = line.strip().split(' ')
    action={
        "_index":"image",
        "_type":"imagetable",
        "_id":i,
        "_source":{
                u"圖片名":line[0].decode('utf8'),
                u"來源":line[1].decode('utf8'),
                u"權威性":line[2].decode('utf8'),
                u"大小":line[3].decode('utf8'),
                u"質量":line[4].decode('utf8'),
                u"類別":line[5].decode('utf8'),
                u"型號":line[6].decode('utf8'),
                u"國別":line[7].decode('utf8'),
                u"採集人":line[8].decode('utf8'),
                u"所屬部門":line[9].decode('utf8'),
                u"關鍵詞":line[10].decode('utf8'),
                u"訪問許可權":line[11].decode('utf8')    
            }
        }
    i+=1
    actions.append(action)
    if(len(actions)==500):
        helpers.bulk(es, actions)
        del actions[0:len(actions)]

if (len(actions) > 0):
    helpers.bulk(es, actions)
    
 


每句話的含義還是很明顯的,這裡需要說幾點,首先是index.txt是以utf8編碼的,所以需要decode('utf8')轉換成unicode物件,並且“圖片名”前需要加u,否則ES會報錯

匯入的速度還是很快的,2000多條記錄每秒