You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Azure SearchClient报错,如何获取RBAC控制的索引总大小?

获取RBAC控制的Azure搜索服务索引总大小的方法

问题原因

你遇到的SearchClient没有get_index_statistics方法的问题,是因为该方法属于SearchIndexClient而非SearchClient——后者仅负责文档级操作,前者才是用于索引管理的客户端。

解决方法

方法一:使用SearchIndexClient直接获取

通过SearchIndexClient调用get_index_statistics方法,可直接获取索引的存储大小、文档数等统计数据,代码示例如下:

from azure.core.credentials import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

# 初始化索引管理客户端
credential = DefaultAzureCredential()
index_client = SearchIndexClient(endpoint="你的搜索服务端点", credential=credential)

# 获取目标索引的统计信息
index_stats = index_client.get_index_statistics(index_name="你的索引名称")

# 提取并转换索引大小(单位:字节转MB)
index_size_bytes = index_stats["storage_size"]
index_size_mb = index_size_bytes / (1024 * 1024)
print(f"索引总大小: {index_size_mb:.2f} MB")

权限要求

由于是RBAC控制的搜索服务,需确保你的身份拥有搜索服务数据读取者或更高权限(如搜索服务参与者),才能成功调用索引统计接口。

方法二:直接调用REST API

若偏好直接调用API,可通过DefaultAzureCredential获取访问令牌后发起请求,代码示例如下:

import requests
from azure.core.credentials import DefaultAzureCredential

credential = DefaultAzureCredential()
# 获取Azure搜索服务的访问令牌
token = credential.get_token("https://search.azure.com/.default").token

endpoint = "你的搜索服务端点"
index_name = "你的索引名称"
api_version = "2023-11-01"
url = f"{endpoint}/indexes/{index_name}/stats?api-version={api_version}"

headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

response = requests.get(url, headers=headers)
response.raise_for_status()
index_stats = response.json()
print(f"索引总大小(字节): {index_stats['storageSize']}")

内容的提问来源于stack exchange,提问作者user3732793

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:56:06