python - 如何使用具有不同内容类型的 Python ElasticSearch 库执行索引请求
问题描述
index
是否可以使用Pythonelasticsearch
库中的方法发送具有不同内容类型的数据?该ingest-attachment
插件的文档提到您可以使用 CBOR 编码来避免将附件编码和解码到 BASE64 和从 BASE64 解码。但是,在撰写此问题时,即使是他们的使用示例也使用requests
库而不是 ElasticSearch 客户端执行请求:
import cbor2
import requests
file = 'my-file'
headers = {'content-type': 'application/cbor'}
with open(file, 'rb') as f:
doc = {
'data': f.read()
}
requests.put(
'http://localhost:9200/my-index-000001/_doc/my_id?pipeline=cbor-attachment',
data=cbor2.dumps(doc),
headers=headers
)
是否可以使用库来执行此操作elasticsearch
?
解决方案
最新版本的客户端允许传递自定义 HTTP 标头并接受二进制正文。可以使用自定义Accept
和Content-Type
标头发送不同的数据格式:
from elasticsearch import Elasticsearch
def index_file(
client: Elasticsearch,
index: str,
body: bytes,
content_type: str,
**kwargs: dict,
) -> dict:
return client.index(
index,
body,
headers={
"Accept": "application/json",
"Content-Type": content_type,
},
**kwargs,
)
还需要设置Accept
标头,否则客户端在尝试解码响应时可能会抛出异常。
这是您可以使用此功能使用ingest-attachment
插件索引文件的方式:
index_file(
client,
index="your_index",
body=cbor2.dumps({"data": binary_file_content}),
content_type="application/cbor",
pipeline="attachment", # For the ingest-attachment plugin.
)
推荐阅读
- git - `git stash show` 的输出为空
- css - 我们应该如何使用不同的谷歌字体?
- java - 我映射不正确的是什么?“字段列表”中的未知列
- r - 对 R 闪亮的 dateRangeInput 使用相同的最小/最大日期和开始/结束日期
- javascript - 如何将基于 require.js 的脚本作为组件包含到 Angular 中
- android - 为什么android studio用红色显示这个项目
- javascript - 清除框字段时如何删除无结果消息
- c - 快速,绘制数据集_如何计算绘图的线数
- api - 邮递员:如何从 post 请求 (/oauth2) 中的 get-request 的 url 中获取值?
- c# - 随机化仍然允许验证的文本框文本的方法?