Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 25, 2026

O Object Storage Service (OSS) oferece o recurso de indexação de dados, que permite consultar objetos correspondentes a condições específicas de metadados, como o nome, o ETag, a classe de armazenamento, o tamanho e o horário da última modificação dos objetos. Esse recurso classifica e agrega os resultados da consulta de acordo com os requisitos do seu negócio e aumenta a eficiência na consulta de objetos específicos entre um grande número de objetos.

Observações

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

  • Apenas os buckets localizados na região China (Hangzhou) oferecem suporte ao recurso de indexação de dados. Para mais informações, consulte MetaSearch.

  • Este tópico usa 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 mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, usamos variáveis de ambiente para obter as credenciais de acesso. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization.

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 de um bucket. Ao ativar esse recurso, o OSS cria uma biblioteca de índices de metadados para o bucket e cria índices de metadados para todos os objetos nele contidos. Após criar a biblioteca de índices, o OSS continua a executar varreduras quase em tempo real nos objetos incrementais do bucket e cria índices de metadados para esses objetos incrementais.

# -*- 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 a seguir mostra 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 código de exemplo a seguir mostra como consultar objetos que atendem às condições específicas e listar as informações desses objetos com base em campos e métodos de classificaçã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

O código a seguir mostra como 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 que ativa o recurso de gerenciamento de metadados, consulte OpenMetaQuery.

  • Para obter mais informações sobre a operação de API que consulta as informações de uma biblioteca de índices de metadados, consulte GetMetaQueryStatus.

  • Para mais detalhes sobre a operação de API que consulta objetos que atendem às condições específicas e lista as informações com base em campos e métodos de classificação, consulte DoMetaQuery.

  • Para saber mais sobre a operação de API que desativa o recurso de gerenciamento de metadados, consulte CloseMetaQuery.