如何通过Python获取OpenSearch集群统计及延迟数据?
Python获取OpenSearch集群统计及延迟数据的方法
1. 获取_cluster/stats接口数据
你可以通过两种方式拿到这个接口的数据:
方式一:使用官方opensearch-py客户端
先安装依赖:
pip install opensearch-py
然后写代码连接集群并调用统计接口:
from opensearchpy import OpenSearch # 初始化客户端 client = OpenSearch( hosts=["https://your-opensearch-host:9200"], http_auth=("username", "password"), use_ssl=True, verify_certs=False, # 生产环境建议开启证书验证 ssl_show_warn=False ) # 获取集群统计数据 cluster_stats = client.cluster.stats() # 按需解析或打印完整数据 print(cluster_stats)
方式二:直接发送HTTP请求(用requests库)
如果不想依赖官方客户端,直接发GET请求也能拿到数据:
import requests from requests.auth import HTTPBasicAuth url = "https://your-opensearch-host:9200/_cluster/stats" auth = HTTPBasicAuth("username", "password") # 发送请求 response = requests.get(url, auth=auth, verify=False) cluster_stats = response.json() # 处理返回结果 print(cluster_stats)
2. 提取搜索延迟和索引延迟
这两个延迟数据都包含在_cluster/stats的返回结果里,通过总耗时除以请求次数就能算出平均延迟:
搜索延迟计算
搜索相关统计在indices.search节点下:
total_time_in_millis:所有搜索请求的总耗时(毫秒)query_total:搜索请求的总次数
代码示例:
# 提取搜索延迟相关数据 search_total_time = cluster_stats["indices"]["search"]["total_time_in_millis"] search_total_count = cluster_stats["indices"]["search"]["query_total"] if search_total_count > 0: avg_search_latency = search_total_time / search_total_count print(f"平均搜索延迟:{avg_search_latency:.2f} 毫秒") else: print("暂无搜索请求数据")
索引延迟计算
索引相关统计在indices.indexing节点下:
total_time_in_millis:所有索引请求的总耗时(毫秒)index_total:索引请求的总次数
代码示例:
# 提取索引延迟相关数据 indexing_total_time = cluster_stats["indices"]["indexing"]["total_time_in_millis"] indexing_total_count = cluster_stats["indices"]["indexing"]["index_total"] if indexing_total_count > 0: avg_indexing_latency = indexing_total_time / indexing_total_count print(f"平均索引延迟:{avg_indexing_latency:.2f} 毫秒") else: print("暂无索引请求数据")
注意事项
- 确保你的账号有访问
_cluster/stats接口的权限,否则会返回403错误 - 生产环境中建议开启SSL证书验证,不要设置
verify=False - 如果需要节点级的细粒度延迟数据,可以调用
_nodes/stats接口,返回结果会包含每个节点的单独统计
内容的提问来源于stack exchange,提问作者SomeOneDudOrg
相关产品推荐
相关产品推荐

