Todos os produtos
Search
Central de documentação

Object Storage Service:Data indexing (OSS SDK for Python 1.0)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) oferece o recurso de indexação de dados para consultar objetos que correspondem a condições específicas de metadados, como nome, ETag, classe de armazenamento, tamanho e hora da última modificação. Esse recurso classifica e agrega os resultados da consulta conforme as necessidades de negócio, o que aumenta a eficiência na busca por objetos específicos em grandes volumes de dados.

Observações

  • Somente o OSS SDK for Python 2.1.6.0 ou versões posteriores oferecem suporte ao recurso de indexação de dados.

  • O recurso de indexação de dados é compatível apenas com buckets localizados na região China (Hangzhou). Para mais informações, consulte MetaSearch.

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.

Ativar o recurso de gerenciamento de metadados para um bucket

O código de exemplo a seguir mostra como ativar o recurso de gerenciamento de metadados para um bucket. Após a ativação desse recurso, o OSS cria uma biblioteca de índices de metadados e gera índices para todos os objetos existentes no bucket. Depois que a biblioteca é criada, o OSS continua a realizar varreduras quase em tempo real nos objetos incrementais e cria automaticamente os índices de metadados correspondentes.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Enable the metadata management feature for the bucket. 
bucket.open_bucket_meta_query()

Consultar a biblioteca de índices de metadados de um bucket

O código abaixo exemplifica como consultar a biblioteca de índices de metadados de um bucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Query the metadata index library information of a specified bucket. 
get_result = bucket.get_bucket_meta_query_status()

# Display the state. 
print(get_result.state)

Consultar objetos que atendem a condições específicas

O exemplo de código a seguir ilustra como consultar objetos que satisfazem determinadas condições e listar suas informações com base em campos e métodos de ordenação específicos:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import MetaQuery, AggregationsRequest
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Query objects that meet specific conditions and list the object information based on specific fields and sorting methods. 
# Query objects that are smaller than 1 MB, return up to 10 objects at a time, and sort the objects in ascending order. 
do_meta_query_request = MetaQuery(max_results=10, query='{"Field": "Size","Value": "1048576","Operation": "lt"}', sort='Size', order='asc')
result = bucket.do_bucket_meta_query(do_meta_query_request)

# Display the object names. 
print(result.files[0].file_name)
# Display the ETags of the objects. 
print(result.files[0].etag)
# Display the types of the objects. 
print(result.files[0].oss_object_type)
# Display the storage classes of the objects. 
print(result.files[0].oss_storage_class)
# Display the CRC-64 values of the objects. 
print(result.files[0].oss_crc64)
# Display the access control lists (ACLs) of the objects. 
print(result.files[0].object_acl)

Desativar o recurso de gerenciamento de metadados para um bucket

Use o código a seguir para desativar o recurso de gerenciamento de metadados de um bucket específico:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Disable the metadata management feature for the bucket. 
bucket.close_bucket_meta_query()

Referências

  • Para mais informações sobre a operação de API usada para ativar o recurso de gerenciamento de metadados, consulte OpenMetaQuery.

  • Para consultar informações sobre uma biblioteca de índices de metadados via API, consulte GetMetaQueryStatus.

  • A operação de API para consultar objetos sob condições específicas e listar seus dados com ordenação personalizada está documentada em DoMetaQuery.

  • Para desativar o recurso de gerenciamento de metadados programaticamente, consulte a documentação da API CloseMetaQuery.