URL请求模拟curl --data-binary

时间:2013-03-21 15:41:19

标签: python elasticsearch

我想发送一个等同于使用的URL请求到post数据中的json对象,用换行符分隔。 这是为Elasticsearch批量索引两个项目。

这很好用:

curl -XPOST 'localhost:9200/myindex/mydoc?pretty=true' --data-binary @myfile.json

其中myfile.json:

{"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}    
{"title": "hello"}
{"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}
{"title": "world"}

当我尝试使用时:

req = urllib2.Request(url,data=
json.dumps({"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}) + "\n" +
json.dumps({"title":"hello"}) + "\n" + 
json.dumps({"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}) + "\n" +
json.dumps({"title":"world"})

我明白了:

HTTP Error 500: Internal Server Error

2 个答案:

答案 0 :(得分:2)

我的用例实际上是ElasticSearch的批量索引请求。

使用rawes

可以轻松实现这一目标
import rawes
es = rawes.Elastic('localhost:9200')

with open('myfile.json') as f:
   lines = f.readlines()

es.post('someindex/sometype/_bulk', data=lines)

答案 1 :(得分:2)

“HTTP错误500”可能来自忘记包含索引名称或索引类型。

另外:对于批量插入,elasticsearch在最后一条记录后需要一个尾随的“\ n”字符,否则它不会插入该记录。

尝试:

import urllib2
import json

url = 'http://localhost:9200/myindex/mydoc/_bulk?pretty=true'

data = json.dumps({"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}) + "\n" + json.dumps({"title":"hello"}) + "\n" + json.dumps({"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}}) + "\n" + json.dumps({"title":"world"})

req = urllib2.Request(url,data=data+"\n")

f = urllib2.urlopen(req)
print f.read()

或者,通过一些重构:

import urllib2
import json

url = 'http://localhost:9200/myindex/mydoc/_bulk?pretty=true'

data = [
    {"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}},
    {"title":"hello"},
    {"index": {"_parent": "btaCovzjQhqrP4s3iPjZKQ"}},
    {"title":"world"}
]

encoded_data = "\n".join(map(json.dumps,data)) + "\n"

req = urllib2.Request(url,data=encoded_data)

f = urllib2.urlopen(req)
print f.read()