批量索引django模型到弹性搜索

时间:2017-12-20 08:52:12

标签: django elasticsearch

我正在尝试将我的django模型批量索引到弹性搜索6,我的计划是每天运行一次作为cron来更新索引。 导入请求

data = serialize('json', CapitalSheet.objects.all())

data += "\n"

r = requests.post("http://127.0.0.1:9200/capitalsheet/_bulk", json = data)

print(r.content)

我收到此错误: b'{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"}],"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"},"status":400}'

如果你能提出更好的建议,我会很高兴。

1 个答案:

答案 0 :(得分:0)

我建议查看elasticsearch提供的python库。这将使批量插入更容易。以下是文档的链接:

https://elasticsearch-py.readthedocs.io/en/master/helpers.html#bulk-helpers

如果您想手动执行此操作,ES bulk API实际上需要为要插入的每个记录使用两行。第一行详细说明了索引和操作类型,第二行是要插入的记录。例如,您的请求正文看起来像这样:

{ "index" : { "_index" : "test", "_type" : "type1" } }
{ "field1" : "value1" }
{ "index" : { "_index" : "test", "_type" : "type1" } }
{ "field1" : "value2" }

ES文档在这里解释得很好: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html