首页 > 解决方案 > 如何使用具有不同内容类型的 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

标签: pythonelasticsearch

解决方案


最新版本的客户端允许传递自定义 HTTP 标头并接受二进制正文。可以使用自定义AcceptContent-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.
)

推荐阅读