ES在之前的博客已有介紹,提供很多接口,本文介紹如何使用python批量導入。ES官網上有較多說明文檔,仔細研究并結合搜索引擎應該不難使用。
先給代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#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多條記錄每秒。
以上這篇python批量導入數據進Elasticsearch的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/u012236368/article/details/51284587