python - 如何使用 API key 和 python 库正确连接到 Elasticsearch 云?

标签 python elasticsearch

Elastic cloud 下创建 API key (托管在 aws 上)。
文件declare应附上适当的身份验证 header :

Authorization: ApiKey $EC_API_KEY
使用 curl有用:
curl -i -H "authorization: ApiKey LONG_KEY_STRING=="  https://12345.us-east-2.aws.elastic-cloud.com:9243/_health

HTTP/2 200 
x-cloud-request-id: 1234abc
content-type: text/plain; charset=utf-8
content-length: 34
date: Thu, 22 Oct 2020 12:36:54 GMT

{
  "ok": true,
  "status": 200
}

但是以下 python 代码 ( elasticsearch-7.9.1 ) 失败:
es = Elasticsearch(['https://12345.us-east-2.aws.elastic-cloud.com:9243'], api_key="LONG_KEY_STRING==")
print(es.cluster.health())
有错误:
{
    "errorMessage": "AuthenticationException(401, 'security_exception', 'missing authentication credentials for REST request [/_cluster/health]')",
    "stackTrace": [
        "  File \"/path/venv/lib64/python3.7/site-packages/lambda_local/main.py\", line 153, in execute\n    result = func(event, context._activate())\n",
        "  File \"main.py\", line 35, in handler\n    post_ping_doc(ping, msg[KEY_ID])\n",
        "  File \"main.py\", line 45, in post_ping_doc\n    print(es.cluster.health())\n",
        "  File \"/path/elasticsearch/client/utils.py\", line 152, in _wrapped\n    return func(*args, params=params, headers=headers, **kwargs)\n",
        "  File \"/path/elasticsearch/client/cluster.py\", line 69, in health\n    headers=headers,\n",
        "  File \"/path/elasticsearch/transport.py\", line 392, in perform_request\n    raise e\n",
        "  File \"/path/elasticsearch/transport.py\", line 365, in perform_request\n    timeout=timeout,\n",
        "  File \"/path/elasticsearch/connection/http_urllib3.py\", line 269, in perform_request\n    self._raise_error(response.status, raw_data)\n",
        "  File \"/path/elasticsearch/connection/base.py\", line 301, in _raise_error\n    status_code, error_message, additional_info\n"
    ],
    "errorType": "AuthenticationException"
}
浏览网络时尝试了其他变体,结果都一样。
启动了本地 ncat -l 1234并将请求重定向到它。请求似乎合法...
GET / HTTP/1.1
Host: 127.0.0.1:1234
Accept-Encoding: identity
connection: keep-alive
content-type: application/json
user-agent: elasticsearch-py/7.9.1 (Python 3.7.5)
authorization: ApiKey LONG_KEY_STRING==
Python 代码确实适用于 docker 上的本地不安全 ES(不需要任何 key )。
目前没有想法,任何帮助表示赞赏。

最佳答案

根据docs您不需要指定主机。我已经尝试过了,它对我有用。

es = Elasticsearch(api_key="LONG_KEY_STRING==")
print(es.cluster.health()) # should print a healthy status!

关于python - 如何使用 API key 和 python 库正确连接到 Elasticsearch 云?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64482647/

相关文章:

python - Airflow DAG - 使用 SimpleHttpOperator 访问上下文以启用 XCOM 拉取

Elasticsearch 使字段成为一个数组

php - Php Elasticsearch 按地理距离排序

elasticsearch - 跨多个字段的multi_match模糊查询

python - 在列表中查找特定模式

python - 如何在具有 60 个功能的 1000 万行数据库上加速 Django 查询聚合?

python - 在每次迭代中使用列表中的两个连续值

Python Folium Topojson 文件未渲染

python - 使用策展人python API无法过滤和删除Elasticsearch的旧索引

elasticsearch - 更改多个文档字段在ES 2.3.3中不起作用