我编写了一个简单的 python 脚本,将 JSON 文件放入 Elasticsearch。我想根据我从 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'
PS:ElasticSearch 服务已启动并运行。
问题与id无关。问题出在“json_data”上。它是一个文件流,因此您需要 json.load 而不是 es.index 中的 json.loads
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句