我编写了一个简单的python脚本来将JSON文件放到Elasticsearch.I想要根据我从JSON文件中提取的id字段来存储它。
但是当我尝试插入弹性搜索时,它会引发错误TypeError: expected string or buffer
以下是我正在处理的代码......
#! /usr/bin/python
import requests
from elasticsearch import Elasticsearch
import json
es = Elasticsearch([{'host':'localhost','port':9200}])
r = requests.get('http://127.0.0.1:9200')
i = 1
if r.status_code == 200:
with open('d1.json') as json_data:
d = json.load(json_data)
for i in d['tc'][0]['i]['f']['h']:
if i['name'] == 'm':
m = i['value']
dope=str(m)
print dope
print type(dope)
#print type(md5)
es.index(index='lab', doc_type='report',id=dope,body=json.loads(json_data))
错误日志:
44d88612fea8a8f36de82e1278abb02f
<type 'str'>
Traceback (most recent call last):
File "elastic_insert.py", line 22, in <module>
es.index(index='labs', doc_type='report',id=dope,body=json.loads(json_data))
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
有关如何解决此错误的任何建议。我甚至尝试将m转换为int
,但它又出现了另一个错误。
int(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '44d88612fea8a8f36de82e1278abb02f'
P.S:ElasticSearch服务已启动并正在运行。
答案 0 :(得分:2)
问题与id无关。问题在于 &#34; json_data&#34 ;.它是一个文件流,因此您需要在es.index
中使用json.load而不是json.loads