elasticsearch,Python 3.x,elasticsearch" /> elasticsearch,Python 3.x,elasticsearch" />

Python 3.x 在Python 3中的Elasticsearch中存储PDF文件的字节内容

Python 3.x 在Python 3中的Elasticsearch中存储PDF文件的字节内容,python-3.x,elasticsearch,Python 3.x,elasticsearch,我读了一个类似这样的PDF文件: with open(filename, 'rb') as file: bytes_content = file.read() print(type(bytes_content)) 我试图在Elasticsearch中存储“bytes\u content”,但出现错误: TypeError: Object of type 'bytes' is not JSON serializable 我该怎么办?我试图将“bytes_content”转换为字符串变量

我读了一个类似这样的PDF文件:

with open(filename, 'rb') as file:
    bytes_content = file.read()
print(type(bytes_content))
我试图在Elasticsearch中存储“bytes\u content”,但出现错误:

TypeError: Object of type 'bytes' is not JSON serializable

我该怎么办?我试图将“bytes_content”转换为字符串变量,但无法将字符串变量转换回bytes变量以再次创建PDF文件(我得到:UnicodeDecodeError:'utf-8'编解码器无法解码字节…)

错误不在elastic上,而是在使用发送给elastic的数据创建json时发生的。在json中,您只能放置字符串、列表、数值和dict,即javascript原语类型。因此,在将字节字符串发送到es服务器之前,应将其编码为字符串:

bytes_content.encode('utf-8')
然后您可以将该值作为字符串存储在不支持字节值的elastic中-