Python连接ElasticSearch遇连接错误,Postman可正常连接如何解决?
解决Python连接Elasticsearch的域名解析错误问题
我可以通过Postman使用清理索引的URI和Bearer令牌查询Elasticsearch,但用Python代码测试时出现连接错误。
原测试代码
from elasticsearch import Elasticsearch ... token = response['access_token'] url = 'https://cleanindex.staging.xyz.com/' es = Elasticsearch( hosts=[{'host': url, 'port': 9200, 'scheme':'https'}], basic_auth=('bearer_auth', token), request_timeout=10, verify_certs=False )
查询代码
# 执行查询 index = 'staging_index/_search' query = { 'query': { 'match': { 'field_name': 'search_term', }, } } try: results = es.search(index=index, body=query,timeout=5) except Exception as e: print(e)
错误信息
Connection error caused by: ConnectionError(Connection error caused by: NameResolutionError(<urllib3.connection.HTTPSConnection object at 0x000002102BCD4A60>: Failed to resolve 'https://cleanindex.staging.xyz.com/' ([Errno 11001] getaddrinfo failed)))
附加错误

解决步骤
1. 修正host参数格式(核心问题)
你把带https://的完整URL传给了host字段,Elasticsearch客户端会将其当作纯域名解析,直接导致解析失败。修改规则:
- 仅保留域名部分,移除协议前缀和末尾斜杠
scheme参数单独指定即可
修正后的客户端初始化代码:
from elasticsearch import Elasticsearch ... token = response['access_token'] # 仅保留域名,去掉https://和末尾斜杠 host = 'cleanindex.staging.xyz.com' es = Elasticsearch( hosts=[{'host': host, 'port': 9200, 'scheme':'https'}], headers={"Authorization": f"Bearer {token}"}, # 修正Bearer认证方式 request_timeout=10, verify_certs=False )
2. 修正Bearer认证方式
原代码用basic_auth传递Bearer令牌是错误的——basic_auth仅用于用户名+密码的基础认证,Bearer令牌需要通过请求头传递,即使用headers参数添加Authorization: Bearer <token>。
3. 额外排查点
- 测试域名解析:在终端执行
ping cleanindex.staging.xyz.com或nslookup cleanindex.staging.xyz.com,确认本地网络能正常解析该域名 - 核对端口:确认Elasticsearch服务的端口确实是9200,若Postman中使用了其他端口,同步修改代码里的
port参数 - 检查网络连通性:确保运行代码的机器能访问该Elasticsearch服务的端口(可通过telnet或curl测试)
内容的提问来源于stack exchange,提问作者user21525821
相关产品推荐
相关产品推荐

