如何使用弹性搜索和python高效地索引json文件



我是Elasticsearch的新手。我正在尝试索引一个包含100000多个对象的json文件。我的json文件的格式是:

[{"ingredients": [{"text": "Butter"}, {"text": "Strawberries"}, {"text": "Granola"}], 
"url": "http://tastykitchen.com/recipes/breakfastbrunch/yogurt-parfaits/", 
"title": "Yogurt Parfaits", 
"id": "000095fc1d", 
"instructions": [{"text": "Layer all ingredients in a serving dish."}]},
{"ingredients":
.....]

这是以列表的形式出现的。我现在使用write来索引文件的python代码是:

from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'localhost','port': 9200}])
f = open('data.json')
import json
data = json.load(f)
for i in data:
res = es.index(index='food',doc_type='Recipe',id=i["id"],body=i)

这种方法耗费大量时间,而且效率低下。我阅读的其他方法需要以下格式的文件:

{"index": {"_index": "index_name", "_type": "index_type", "_id": "doc_id"}}
{"ingredients:....

你能建议一种有效的方法来索引文件吗?

尝试使用Elasticsearch批量Api

在单个API调用中执行多个索引或删除操作。这减少了开销,并且可以大大提高索引速度。

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-散装https://elasticsearch-py.readthedocs.io/en/master/helpers.html

最新更新