如何统计ElasticSearch中的索引、文档类型数量及按类型计数(Python客户端)
用Python客户端统计Elasticsearch的索引、文档类型与文档总数
统计索引总数
有两种简单方法可以获取ES服务器上的索引总数:
方法1:通过别名接口获取
调用indices.get_alias()获取所有索引的别名映射,直接取返回字典的键数量即可:
from elasticsearch import Elasticsearch # 初始化ES连接,根据你的实际配置修改 es = Elasticsearch(["http://your-es-server:9200"]) # 获取所有索引的别名信息 all_indices = es.indices.get_alias("*") index_count = len(all_indices) print(f"ES服务器共有 {index_count} 个索引")
方法2:通过cat接口获取
cat.indices()返回格式化的索引列表,直接取列表长度:
indices = es.cat.indices(format="json") index_count = len(indices)
统计文档类型
注意:Elasticsearch 7.0及以上版本已彻底移除文档类型(type),所有文档默认使用_doc作为唯一类型。如果你的ES版本是7.x+,每个索引只有一种文档类型;6.x及以下版本支持一个索引多类型,需要单独处理。
6.x及以下版本:统计所有唯一文档类型
遍历每个索引,从mapping中提取文档类型:
unique_types = set() for index_name in all_indices.keys(): # 获取当前索引的mapping index_mapping = es.indices.get_mapping(index=index_name) # 提取该索引下的所有文档类型 types_in_index = list(index_mapping[index_name]["mappings"].keys()) unique_types.update(types_in_index) type_count = len(unique_types) print(f"ES服务器共有 {type_count} 种唯一文档类型") # 如需查看每个索引的文档类型数量 for index_name in all_indices.keys(): mapping = es.indices.get_mapping(index=index_name) count = len(mapping[index_name]["mappings"].keys()) print(f"索引 {index_name} 包含 {count} 种文档类型")
7.x及以上版本:
默认每个索引仅存在_doc类型,若需确认,可通过mapping查看:
mapping = es.indices.get_mapping(index="your-index-name") print(mapping["your-index-name"]["mappings"].keys()) # 输出 ['_doc']
统计总文档数
方法1:通过cat接口快速获取总数
total_docs = es.cat.count(format="json") print(f"ES服务器总文档数:{total_docs[0]['count']}")
方法2:遍历索引累加文档数(可查看每个索引的文档数)
total = 0 for index_name in all_indices.keys(): # 获取索引统计信息 stats = es.indices.stats(index=index_name) doc_count = stats["indices"][index_name]["total"]["docs"]["count"] total += doc_count print(f"索引 {index_name} 的文档数:{doc_count}") print(f"ES服务器总文档数:{total}")
内容的提问来源于stack exchange,提问作者An old man in the sea.
相关产品推荐
相关产品推荐

