Elasticsearch Python API请求未携带JSON数据,返回空结果求助
问题排查与修复方案
我一眼就发现了两个关键问题,导致你的Elasticsearch查询返回空结果:
1. Elasticsearch客户端初始化错误
你把索引的路径直接拼到了节点URL里,这不符合Python Elasticsearch客户端的使用规范。客户端的节点地址应该是集群的基础访问地址,索引名称需要在search方法中单独指定。
你的原代码里还存在一个语法错误:http_auth=(user', 'pass')里的单引号不匹配,少了开头的单引号。
2. Search方法的index参数带多余斜杠
你在es.search(index="/logstash-browse-access-logs-*", body=data)里给index加了前置斜杠/,Elasticsearch的索引名称不允许带这个前缀。
修正后的完整代码
#!/usr/bin/env python import requests from elasticsearch import Elasticsearch import json from ssl import create_default_context cafile="my.perm.pac" # 若需自定义CA证书验证,需将cafile传入create_default_context context = create_default_context(cafile=cafile) # 修正节点URL:仅保留集群基础地址 url = "https://mydev-elk.dev1.com" user = "your_username" password = "your_password" es = Elasticsearch( [url], http_auth=(user, password), scheme="https", port=443, ssl_context=context, ) data= { "query": { "bool": { "must": [ { "match_all": {} }, { "range": { "log_timestamp": { "gte": 1526916192084, "lte": 1526917092084, "format": "epoch_millis" } } } ], "must_not": [] } }, "size": 0, "_source": { "excludes": [] }, "aggregations": { "2": { "date_histogram": { "field": "log_timestamp", "interval": "5s", "time_zone": "America/Chicago", "min_doc_count": 1 } } } } # 修正index参数:移除前置斜杠 res = es.search(index="logstash-browse-access-logs-*", body=data) print(res)
额外说明
浏览器里的URL能正常工作,是因为它直接调用了Elasticsearch的REST API完整端点(/elasticsearch/logstash-browse-access-logs-*/_search),而Python客户端已经封装了路径逻辑,你只需要提供基础节点地址和索引名称即可。
内容的提问来源于stack exchange,提问作者vas




