在elasticsearch-py中设置内容类型标头

May*_*Lal 5 python elasticsearch

我正在尝试通过 python 代码将数据上传到 Elasticsearch。但我收到以下错误:

TransportError(406, 'Content-Type header [] is not supported')

有关我的系统上安装的elasticsearch(服务器和客户端)的详细信息 -

elasticsearch(服务器):7.2.0 elasticsearch-py(客户端):7.0.2

我已经查看了此处提到的其他解决方案(ElasticHttpError: 406, Elastic Search Error While indexing Data)和此处(https://github.com/elastic/elasticsearch-py/issues/718)。

我已经升级了系统中安装的库。但错误仍然存​​在。

我一直在使用的代码:

from datetime import datetime
from elasticsearch import Elasticsearch

try:
    es = Elasticsearch(['http://localhost:9200/'],verify_certs=True)
except Exception as err:
    if not es.ping():
        raise ValueError("Connection failed")

doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)
print(res['result'])

res = es.get(index="test-index", doc_type='tweet', id=1)
print(res['_source'])

es.indices.refresh(index="test-index")

res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
Run Code Online (Sandbox Code Playgroud)

根据elasticsearch-py文档,它应该自动添加Content-Type标头,但它似乎不起作用。

请让我知道如何通过 python 代码手动添加标头。

use*_*953 0

这在我的旧系统上发生过。我安装了新的 ES 客户端,但该系统上的默认 python 是 python2,因此它加载了一些旧的 python2 客户端。

您可以像这样打印 ES 客户端版本和位置:

import elasticsearch
print(elasticsearch.__versionstr__)
print(elasticsearch.__path__)
Run Code Online (Sandbox Code Playgroud)