MetaSearch indexa los metadatos de los objetos en OSS. Esto le permite filtrar y recuperar objetos mediante condiciones personalizadas.
Casos de uso
Auditoría de datos
Localice rápidamente archivos para auditorías de datos o cumplimiento normativo. Por ejemplo, en servicios financieros, filtre por etiquetas personalizadas y permisos de control de acceso para encontrar archivos con niveles específicos de sensibilidad.
Copia de seguridad y archivado de datos empresariales
Recupere archivos por fecha o tipo durante las copias de seguridad y el archivado. Filtre por hora de creación, clase de almacenamiento o etiquetas personalizadas para localizar registros históricos o archivados.
Límites
-
Límite de región
MetaSearch está disponible en a continuación regiones: China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Shenzhen), China (Guangzhou), China (Chengdu), China (Ulanqab), China (Hong Kong), Singapore, Indonesia (Jakarta), Germany (Frankfurt), US (Virginia), US (Silicon Valley) y UK (London).
-
Límite de bucket
Un bucket con MetaSearch habilitado puede contener hasta 50 mil millones de objetos. Superar este límite puede degradar el rendimiento de recuperación. Para procesar volúmenes de datos mayores, comuníquese con Technical Support para solicitar una evaluación.
-
Carga multiparte
Para los objetos creados mediante carga multiparte, los resultados de la consulta muestran únicamente los objetos completos ensamblados con la operación CompleteMultipartUpload. No se incluyen las partes de carga incompletas o canceladas.
Rendimiento
A continuación se presentan métricas solo de referencia.
-
Tiempo de generación del índice de archivos existentes
100 millones de archivos en un solo bucket: 4 horas
Mil millones de archivos en un solo bucket: aproximadamente 10 horas
10 mil millones de archivos en un solo bucket: entre 1 y 3 días aproximadamente
20 mil millones de archivos en un solo bucket: entre 2 y 4 días aproximadamente
30 mil millones de archivos en un solo bucket: entre 3 y 6 días aproximadamente
50 mil millones de archivos en un solo bucket: entre 6 y 10 días aproximadamente
Si su bucket contiene más de mil millones de archivos con etiquetas, la generación del índice tarda más que las estimaciones anteriores.
-
Tiempo de actualización incremental del índice de archivos
De forma predeterminada, OSS asigna 5,000 QPS a MetaSearch para las actualizaciones del índice. Esta cuota es independiente de la QoS de su bucket. Cuando la tasa de adición, modificación o eliminación de archivos se mantiene por debajo de 5,000, las actualizaciones suelen estar disponibles para búsqueda en cuestión de minutos. Si la tasa supera los 5,000 QPS, comuníquese con Technical Support para obtener asistencia.
-
Rendimiento de recuperación de archivos
La recuperación se completa en segundos, con un tiempo de espera predeterminado de 30 segundos.
Habilitar MetaSearch
OSS console
Para buckets en China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Shenzhen), China (Guangzhou), China (Chengdu), China (Hong Kong), Singapore, Indonesia (Jakarta) o Germany (Frankfurt)
Inicie sesión en OSS console.
En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.
En el panel de navegación izquierdo, elija .
En la página Data Indexing, si es la primera vez que accede, siga las indicaciones para otorgar permisos a AliyunMetaQueryDefaultRole. De este modo, OSS podrá gestionar los datos del bucket. A continuación, haga clic en Enable Data Indexing.
-
Seleccione MetaSearch y luego haga clic en Enable.
NotaEl tiempo necesario para habilitar MetaSearch depende de la cantidad de objetos en el bucket.
Para buckets en la región UK (London), China (Ulanqab), US (Virginia) o US (Silicon Valley)
Inicie sesión en OSS console.
En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.
En el panel de navegación izquierdo, elija . Si es la primera vez que accede, siga las indicaciones para otorgar permisos a AliyunMetaQueryDefaultRole. Así, OSS podrá gestionar los datos del bucket.
-
Active Metadata Management.
NotaEl tiempo necesario para habilitar Metadata Management depende de la cantidad de objetos en el bucket.
Alibaba Cloud SDK
Habilite MetaSearch para un bucket antes de ejecutar consultas. Por ejemplo:
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.MetaQueryMode;
public class OpenMetaQuery {
public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
// In this example, the endpoint of the China (Hangzhou) region is used.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
//Call the shutdown method to release associated resources when the OSSClient instance is no longer used.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Enable the MetaSearch feature.
ossClient.openMetaQuery(bucketName);
} catch (OSSException oe) {
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Error Message: " + ce.getMessage());
} finally {
// Shut down the OSSClient instance.
if(ossClient != null){
ossClient.shutdown();
}
}
}
}
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="open meta query sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint for accessing OSS. This parameter is required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# From the environment variables, load the authentication information required to access OSS.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration of the SDK.
cfg = oss.config.load_default()
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Set the region to the one provided from the command line.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client.
client = oss.Client(cfg)
# Initiate a request to enable metadata-based query.
result = client.open_meta_query(oss.OpenMetaQueryRequest(
bucket=args.bucket,
))
# Display the HTTP status code and request ID.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
# Call the main function when the script is directly run.
if __name__ == "__main__":
main()
Go
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string // Specify a variable to store the region information obtained from the command lines.
bucketName string // Specify a variable to store the bucket name obtained from the command lines.
)
// The init function is executed before the main function to initialize the program.
func init() {
// Use a command line parameter to specify the region.
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
// Use a command line parameter to specify the bucket name.
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check if the bucket name is specified. If not, the program outputs default parameters and terminates.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required") // Log the error message and terminate the program.
}
// Check whether the region is specified. If the region is not specified, output the default parameters and exit the program.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required") // Log the error message and terminate the program.
}
// Create and configure a client and use environment variables to pass the credential provider.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := oss.NewClient(cfg) // Use the client configurations to create a new OSSClient instance.
// Create an OpenMetaQuery request to enable the metadata management feature for a specific bucket.
request := &oss.OpenMetaQueryRequest{
Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
}
result, err := client.OpenMetaQuery(context.TODO(), request) // Execute the request to enable the metadata management feature for the bucket.
if err != nil {
log.Fatalf("failed to open meta query %v", err) // If an error occurs, record the error message and terminate the program.
}
log.Printf("open meta query result:%#v\n", result) // Display the result.
}
PHP
<?php // Importe el archivo de autocarga para garantizar que las bibliotecas de dependencias se carguen correctamente. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Defina la descripción de los argumentos de línea de comandos. $optsdesc = [ "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // La región donde se encuentra el bucket. Este parámetro es obligatorio. "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // El endpoint que otros servicios pueden usar para acceder a OSS. Este parámetro es opcional. "bucket" => ['help' => 'The name of the bucket', 'required' => True], // El nombre del bucket. Este parámetro es obligatorio. ]; // Convierta la descripción de los argumentos al formato de opción larga que requiere getopt. // Los dos puntos (:) después de cada argumento indican que este requiere un valor. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Analice sintácticamente los argumentos de línea de comandos. $options = getopt("", $longopts); // Compruebe si se especificaron los argumentos obligatorios. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtenga la información de ayuda del argumento. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // Si no se especifica un argumento obligatorio, salga del programa. } } // Extraiga los valores de los argumentos analizados. $region = $options["region"]; // La región donde se encuentra el bucket. $bucket = $options["bucket"]; // El nombre del bucket. // Cargue la información de credenciales desde las variables de entorno. // Utilice EnvironmentVariableCredentialsProvider para leer el Access Key ID y el Access Key Secret de las variables de entorno. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Utilice las configuraciones predeterminadas del SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Establezca el proveedor de credenciales. $cfg->setRegion($region); // Establezca la región donde se encuentra el bucket. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Si se proporciona un endpoint, establézcalo. } // Cree una instancia de cliente de OSS. $client = new Oss\Client($cfg); // Cree un objeto OpenMetaQueryRequest para habilitar la función de recuperación escalar en el bucket. $request = new Oss\Models\OpenMetaQueryRequest( bucket: $bucket ); // Ejecute la operación para habilitar la función de recuperación escalar. $result = $client->openMetaQuery($request); // Imprima el resultado de habilitar la función de recuperación escalar. printf( 'status code:' . $result->statusCode . PHP_EOL . // El código de estado HTTP. Por ejemplo, 200 indica que la solicitud fue exitosa. 'request id:' . $result->requestId . PHP_EOL // El ID de solicitud, que se usa para depurar o rastrear solicitudes. );
Ossutil
Habilite MetaSearch para un bucket llamado examplebucket:
ossutil api open-meta-query --bucket examplebucket
Ejecutar una consulta de MetaSearch
OSS console
Este ejemplo busca objetos menores a 500 KB, modificados por última vez entre las 00:00 del 11 de septiembre de 2024 y las 00:00 del 12 de septiembre de 2024. Los resultados se ordenan por tamaño de objeto de forma ascendente, con el tamaño máximo como agregación.
Inicie sesión en OSS console.
En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.
En el panel de navegación izquierdo, elija .
-
Configure a continuación parámetros. Deje los demás con sus valores predeterminados.
Establezca Last Modified At en el rango de las 00:00 del 11 de septiembre de 2024 a las 00:00 del 12 de septiembre de 2024.
Establezca Object Size en menos de 500 KB.
-
Expanda More filter conditions.
En Object Sort Order, seleccione Object Size y Ascending.
En Data Aggregation, seleccione Maximum para Object Size.

-
Query conditions and output settings.
Haga clic en Query. Dos objetos coinciden con las condiciones de la consulta. El objeto más grande tiene 434 KB.

Alibaba Cloud SDK
Estos ejemplos consultan objetos que coinciden con condiciones específicas.
Java
Ejemplos adicionales: MetaSearch (Java SDK V1).
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;
public class DoMetaQuery {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient instance is no longer used.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Query objects that meet specific conditions and return objects based on specific fields and in the specified sorting order.
int maxResults = 20;
// Query objects that are smaller than 1,048,576 bytes in size, return up to 20 objects at a time, and sort the objects in ascending order.
String query = "{\"Field\": \"Size\",\"Value\": \"1048576\",\"Operation\": \"lt\"}";
String sort = "Size";
DoMetaQueryRequest doMetaQueryRequest = new DoMetaQueryRequest(bucketName, maxResults, query, sort);
Aggregation aggregationRequest = new Aggregation();
Aggregations aggregations = new Aggregations();
List<Aggregation> aggregationList = new ArrayList<Aggregation>();
// Specify the name of the field that is used in the aggregate operation.
aggregationRequest.setField("Size");
// Specify the operator that is used in the aggregate operation. max indicates the maximum value.
aggregationRequest.setOperation("max");
aggregationList.add(aggregationRequest);
aggregations.setAggregation(aggregationList);
// Specify the aggregate operation.
doMetaQueryRequest.setAggregations(aggregations);
doMetaQueryRequest.setOrder(SortOrder.ASC);
DoMetaQueryResult doMetaQueryResult = ossClient.doMetaQuery(doMetaQueryRequest);
if(doMetaQueryResult.getFiles() != null){
for(ObjectFile file : doMetaQueryResult.getFiles().getFile()){
System.out.println("Filename: " + file.getFilename());
// Query the ETag value that is used to identify the content of the object.
System.out.println("ETag: " + file.getETag());
// Query the access control list (ACL) of the object.
System.out.println("ObjectACL: " + file.getObjectACL());
// Query the type of the object.
System.out.println("OssObjectType: " + file.getOssObjectType());
// Query the storage class of the object.
System.out.println("OssStorageClass: " + file.getOssStorageClass());
// Query the number of tags of the object.
System.out.println("TaggingCount: " + file.getOssTaggingCount());
if(file.getOssTagging() != null){
for(Tagging tag : file.getOssTagging().getTagging()){
System.out.println("Key: " + tag.getKey());
System.out.println("Value: " + tag.getValue());
}
}
if(file.getOssUserMeta() != null){
for(UserMeta meta : file.getOssUserMeta().getUserMeta()){
System.out.println("Key: " + meta.getKey());
System.out.println("Value: " + meta.getValue());
}
}
}
} else if(doMetaQueryResult.getAggregations() != null){
for(Aggregation aggre : doMetaQueryResult.getAggregations().getAggregation()){
// Query the field by which the aggregation is performed.
System.out.println("Field: " + aggre.getField());
// Query the aggregation operator.
System.out.println("Operation: " + aggre.getOperation());
// Query the result of the aggregate operation.
System.out.println("Value: " + aggre.getValue());
if(aggre.getGroups() != null && aggre.getGroups().getGroup().size() > 0){
// Query the value of the aggregation.
System.out.println("Groups value: " + aggre.getGroups().getGroup().get(0).getValue());
// Query the total number of the aggregations.
System.out.println("Groups count: " + aggre.getGroups().getGroup().get(0).getCount());
}
}
} else {
System.out.println("NextToken: " + doMetaQueryResult.getNextToken());
}
} catch (OSSException oe) {
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Error Message: " + ce.getMessage());
} finally {
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
}
Python
Ejemplos adicionales: MetaSearch.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser for parsing arguments from the command line.
parser = argparse.ArgumentParser(description="do meta query sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Obtain access credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration of the SDK.
cfg = oss.config.load_default()
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Set the region to the one provided from the command line.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client.
client = oss.Client(cfg)
# Perform the metadata-based query.
result = client.do_meta_query(oss.DoMetaQueryRequest(
bucket=args.bucket, # The bucket that stores the objects to be queried.
meta_query=oss.MetaQuery( # Specify query settings.
aggregations=oss.MetaQueryAggregations( # Specify aggregatios.
aggregations=[ # The aggregation list.
oss.MetaQueryAggregation( # The first aggregation: the total object size.
field='Size',
operation='sum',
),
oss.MetaQueryAggregation( # The second aggregation: the maximum object size.
field='Size',
operation='max',
)
],
),
next_token='', # The pagination token.
max_results=100, # The maximum number of entries that can be returned. Valid values: 0 to 100.
query='{"Field": "Size","Value": "1048576","Operation": "gt"}', # The query condition.
sort='Size', # The sorting field.
order=oss.MetaQueryOrderType.DESC, # The sorting order.
),
))
# Display the basic response information.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
# You can uncomment the one or more of the following lines to display more details.
# f' files: {result.files},'
# f' file: {result.files.file},'
# f' file modified time: {result.files.file.file_modified_time},'
# f' etag: {result.files.file.etag},'
# f' server side encryption: {result.files.file.server_side_encryption},'
# f' oss tagging count: {result.files.file.oss_tagging_count},'
# f' oss tagging: {result.files.file.oss_tagging},'
# f' key: {result.files.file.oss_tagging.taggings[0].key},'
# f' value: {result.files.file.oss_tagging.taggings[0].value},'
# f' key: {result.files.file.oss_tagging.taggings[1].key},'
# f' value: {result.files.file.oss_tagging.taggings[1].value},'
# f' oss user meta: {result.files.file.oss_user_meta},'
# f' key: {result.files.file.oss_user_meta.user_metas[0].key},'
# f' value: {result.files.file.oss_user_meta.user_metas[0].value},'
# f' key: {result.files.file.oss_user_meta.user_metas[1].key},'
# f' value: {result.files.file.oss_user_meta.user_metas[1].value},'
# f' filename: {result.files.file.filename},'
# f' size: {result.files.file.size},'
# f' oss object type: {result.files.file.oss_object_type},'
# f' oss storage class: {result.files.file.oss_storage_class},'
# f' object acl: {result.files.file.object_acl},'
# f' oss crc64: {result.files.file.oss_crc64},'
# f' server side encryption customer algorithm: {result.files.file.server_side_encryption_customer_algorithm},'
# f' aggregations: {result.aggregations},'
f' field: {result.aggregations.aggregations[0].field},'
f' operation: {result.aggregations.aggregations[0].operation},'
f' field: {result.aggregations.aggregations[1].field},'
f' operation: {result.aggregations.aggregations[1].operation},'
f' next token: {result.next_token},'
)
# If matched objects are found, display tags and user metadata.
if result.files:
if result.files.file.oss_tagging.taggings:
for r in result.files.file.oss_tagging.taggings:
print(f'result: key: {r.key}, value: {r.value}')
if result.files.file.oss_user_meta.user_metas:
for r in result.files.file.oss_user_meta.user_metas:
print(f'result: key: {r.key}, value: {r.value}')
# Display all aggregations.
if result.aggregations.aggregations:
for r in result.aggregations.aggregations:
print(f'result: field: {r.field}, operation: {r.operation}')
if __name__ == "__main__":
main()
Go
Ejemplos adicionales: MetaSearch (Go SDK V2).
package main import ( "context" "flag" "fmt" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) var ( region string // Especifique una variable para almacenar la información de la región obtenida de la línea de comandos. bucketName string // Especifique una variable para almacenar el nombre del bucket obtenido de la línea de comandos. ) // La función init se ejecuta antes de la función main para inicializar el programa. func init() { // Utilice un parámetro de línea de comandos para especificar la región. De forma predeterminada, el parámetro es una cadena vacía. flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") // Utilice un parámetro de línea de comandos para especificar el nombre del bucket. De forma predeterminada, el parámetro es una cadena vacía. flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") } func main() { flag.Parse() // Analice sintácticamente los parámetros de línea de comandos. // Compruebe si se especificó el nombre del bucket. Si no, el programa muestra los parámetros predeterminados y finaliza. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Compruebe si se especificó la región. Si no, el programa muestra los parámetros predeterminados y finaliza. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Cree y configure un cliente. Utilice variables de entorno para pasar el proveedor de credenciales y la región. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) client := oss.NewClient(cfg) // Utilice las configuraciones del cliente para crear una nueva instancia de OSSClient. // Cree una solicitud DoMetaQuery para consultar los objetos que cumplen condiciones específicas. request := &oss.DoMetaQueryRequest{ Bucket: oss.Ptr(bucketName), // Especifique el nombre del bucket. MetaQuery: &oss.MetaQuery{ Query: oss.Ptr({"Field": "Size","Value": "1048576","Operation": "gt"}), // Consulte objetos cuyo tamaño sea mayor a 1 MB. Sort: oss.Ptr("Size"), // Liste los objetos por tamaño. Order: oss.Ptr(oss.MetaQueryOrderAsc), // Ordene los objetos de forma ascendente. }, } result, err := client.DoMetaQuery(context.TODO(), request) // Ejecute la solicitud para consultar los objetos que cumplen las condiciones anteriores. if err != nil { log.Fatalf("failed to do meta query %v", err) } // Muestre el token utilizado para consultar los datos de la siguiente página. fmt.Printf("NextToken:%s\n", result.NextToken) // Recorra los resultados devueltos y muestre los detalles de cada objeto. for _, file := range result.Files { fmt.Printf("File name: %s\n", file.Filename) fmt.Printf("size: %d\n", file.Size) fmt.Printf("File Modified Time:%s\n", file.FileModifiedTime) fmt.Printf("Oss Object Type:%s\n", file.OSSObjectType) fmt.Printf("Oss Storage Class:%s\n", file.OSSStorageClass) fmt.Printf("Object ACL:%s\n", file.ObjectACL) fmt.Printf("ETag:%s\n", file.ETag) fmt.Printf("Oss CRC64:%s\n", file.OSSCRC64) if file.OSSTaggingCount != nil { fmt.Printf("Oss Tagging Count:%d\n", file.OSSTaggingCount) } // Muestre las etiquetas de los objetos. for _, tagging := range file.OSSTagging { fmt.Printf("Oss Tagging Key:%s\n", tagging.Key) fmt.Printf("Oss Tagging Value:%s\n", tagging.Value) } // Muestre los metadatos de usuario. for _, userMeta := range file.OSSUserMeta { fmt.Printf("Oss User Meta Key:%s\n", userMeta.Key) fmt.Printf("Oss User Meta Key Value:%s\n", *userMeta.Value) } } }
PHP
Ejemplos adicionales: MetaSearch (PHP SDK V2).
<?php // Importe el archivo de autocarga para garantizar que las bibliotecas de dependencias se carguen correctamente. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Defina la descripción de los argumentos de línea de comandos. $optsdesc = [ "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // La región donde se encuentra el bucket. Este parámetro es obligatorio. "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // El endpoint que otros servicios pueden usar para acceder a OSS. Este parámetro es opcional. "bucket" => ['help' => 'The name of the bucket', 'required' => True], // El nombre del bucket. Este parámetro es obligatorio. ]; // Convierta la descripción de los argumentos al formato de opción larga que requiere getopt. // Los dos puntos (:) después de cada argumento indican que este requiere un valor. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Analice sintácticamente los argumentos de línea de comandos. $options = getopt("", $longopts); // Compruebe si se especificaron los argumentos obligatorios. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtenga la información de ayuda del argumento. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // Si no se especifica un argumento obligatorio, salga del programa. } } // Extraiga los valores de los argumentos analizados. $region = $options["region"]; // La región donde se encuentra el bucket. $bucket = $options["bucket"]; // El nombre del bucket. // Cargue la información de credenciales desde las variables de entorno. // Utilice EnvironmentVariableCredentialsProvider para leer el Access Key ID y el Access Key Secret de las variables de entorno. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Utilice las configuraciones predeterminadas del SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Establezca el proveedor de credenciales. $cfg->setRegion($region); // Establezca la región donde se encuentra el bucket. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Si se proporciona un endpoint, establézcalo. } // Cree una instancia de cliente de OSS. $client = new Oss\Client($cfg); // Cree un objeto DoMetaQueryRequest para ejecutar una operación de consulta de metadatos. $request = new \AlibabaCloud\Oss\V2\Models\DoMetaQueryRequest( bucket: $bucket, metaQuery: new \AlibabaCloud\Oss\V2\Models\MetaQuery( maxResults: 5, // La cantidad máxima de resultados que se devolverán. query: "{'Field': 'Size','Value': '1048576','Operation': 'gt'}", // Condición de consulta: objetos cuyo tamaño sea mayor a 1 MB. sort: 'Size', // Ordene por tamaño de objeto. order: \AlibabaCloud\Oss\V2\Models\MetaQueryOrderType::ASC, // Ordene de forma ascendente. aggregations: new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregations( // Operación de agregación aggregations: [ new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregation( field: 'Size', // El campo de tamaño de objeto. operation: 'sum' // Operación de agregación: suma. ), new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregation( field: 'Size', // El campo de tamaño de objeto. operation: 'max' // Operación de agregación: valor máximo. ), ] ) ) ); // Ejecute la operación de consulta de metadatos. $result = $client->doMetaQuery($request); // Imprima el resultado de la consulta de metadatos. printf( 'status code:' . $result->statusCode . PHP_EOL . // El código de estado HTTP. Por ejemplo, 200 indica que la solicitud fue exitosa. 'request id:' . $result->requestId . PHP_EOL . // El ID de solicitud, que se usa para depurar o rastrear solicitudes. 'result:' . var_export($result, true) . PHP_EOL // El resultado de la consulta, que contiene los objetos coincidentes y sus datos agregados. );
Usar ossutil
Utilice ossutil para consultar los objetos coincidentes. Para instalar ossutil, consulte Install ossutil.
Consulte los objetos coincidentes en el bucket examplebucket:
ossutil api do-meta-query --bucket examplebucket --meta-query "{\"MaxResults\":\"5\",\"Query\":\"{\\\"Field\\\": \\\"Size\\\",\\\"Value\\\": \\\"1048576\\\",\\\"Operation\\\": \\\"gt\\\"}\",\"Sort\":\"Size\",\"Order\":\"asc\",\"Aggregations\":{\"Aggregation\":[{\"Field\":\"Size\",\"Operation\":\"sum\"},{\"Field\":\"Size\",\"Operation\":\"max\"}]}}"
Deshabilitar MetaSearch
Deshabilitar MetaSearch no afecta los datos almacenados. Si vuelve a habilitar la función, se analizan de nuevo los archivos existentes y se reconstruye el índice. El tiempo necesario depende de la cantidad de archivos en su bucket.
La facturación se detiene una hora después de que deshabilite la función. La generación de facturas puede presentar retrasos; revise sus facturas para comprobar que sean correctas.
OSS console
Inicie sesión en la consola de OSS. En la página Data Indexing, haga clic en Disable junto a Metadata Management y siga las indicaciones.

Alibaba Cloud SDK
Java
Ejemplos adicionales: MetaSearch (OSS SDK for Java V1).
import com.aliyun.oss.; import com.aliyun.oss.common.auth.; import com.aliyun.oss.common.comm.SignVersion; public class CloseMetaQuery { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // 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. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient instance is no longer used. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Disable the MetaSearch feature for the bucket. ossClient.closeMetaQuery(bucketName); } catch (OSSException oe) { System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Error Message: " + ce.getMessage()); } finally { // Shut down the OSSClient instance. if(ossClient != null){ ossClient.shutdown(); } } } }
Python
Ejemplos adicionales: MetaSearch.
import argparse import alibabacloud_oss_v2 as oss # Create an ArgumentParser object for processing command-line arguments. parser = argparse.ArgumentParser(description="close meta query sample") parser.add_argument('--region', help='The region in which the bucket is located.', required=True) parser.add_argument('--bucket', help='The name of the bucket.', required=True) parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS') def main(): # Parse the command-line arguments. args = parser.parse_args() # Obtain access credentials from environment variables. credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Use the default configuration of the SDK. cfg = oss.config.load_default() # Set the credential provider to the credential provider obtained from the environment variables. cfg.credentials_provider = credentials_provider # Set the region in the configuration to the one specified in the command line. cfg.region = args.region # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint. if args.endpoint is not None: cfg.endpoint = args.endpoint # Create an OSS client. client = oss.Client(cfg) # Call the close_meta_query method to disable the metadata query feature for the specified bucket. result = client.close_meta_query(oss.CloseMetaQueryRequest( bucket=args.bucket, )) # Display the HTTP status code and request ID. print(f'status code: {result.status_code}, request id: {result.request_id}') # Call the main function when the script is directly run. if __name__ == "__main__": main()
Go
Ejemplos adicionales: MetaSearch (OSS SDK for Go V2).
package main import ( "context" "flag" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) var ( region string // Specify a variable to store the region information obtained from the command lines. bucketName string // Specify a variable to store the bucket name obtained from the command lines. ) // The init function is executed before the main function to initialize the program. func init() { // Use a command line parameter to specify the region. flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") // Use a command line parameter to specify the bucket name. flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") } func main() { flag.Parse() // Parse command line parameters. // Check if the bucket name is specified. If not, the program outputs default parameters and terminates. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") // Log the error message and terminate the program. } // Check if the region is specified. If not, the program outputs default parameters and terminates. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") // Log the error message and terminate the program. } // Create and configure a client and use environment variables to pass the credential provider and the region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) client := oss.NewClient(cfg) // Create a new OSSClient instance. // Create a CloseMetaQuery request to disable the metadata management feature for the bucket. request := &oss.CloseMetaQueryRequest{ Bucket: oss.Ptr(bucketName), // Specify the name of the bucket. } result, err := client.CloseMetaQuery(context.TODO(), request) // Execute the request. if err != nil { log.Fatalf("failed to close meta query %v", err) // If an error occurs, record the error message and exit the program. } log.Printf("close meta query result:%#v\n", result) }
PHP
Ejemplos adicionales: MetaSearch (OSS SDK for PHP V2).
<?php // Import the autoloader file to ensure that dependency libraries can be correctly loaded. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Define the description of command line arguments. $optsdesc = [ "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region in which the bucket is located. This parameter is required. "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional. "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required. ]; // Convert the argument description to the long option format required by getopt. // A colon (:) after each argument indicates that the argument requires a value. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Parse the command line arguments. $options = getopt("", $longopts); // Check whether the required arguments are specified. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information of the argument. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // If a required argument is not specified, exit the program. } } // Extract values from the parsed arguments. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. // Load the credential information from environment variables. // Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider. $cfg->setRegion($region); // Set the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint. } // Create an OSS client instance. $client = new Oss\Client($cfg); // Create a CloseMetaQueryRequest object to disable the retrieval feature for the bucket. $request = new \AlibabaCloud\Oss\V2\Models\CloseMetaQueryRequest( bucket: $bucket ); // Execute the operation to disable the retrieval feature. $result = $client->closeMetaQuery($request); // Print the result of disabling the retrieval feature. printf( 'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful. 'request id:' . $result->requestId . PHP_EOL // The request ID, which is used to debug or track requests. );
ossutil
En este ejemplo se deshabilita MetaSearch para el bucket examplebucket:
ossutil api close-meta-query --bucket examplebucket
Condiciones de consulta y configuración de salida
Condiciones de consulta
Utilice estas condiciones de forma individual o combinada.
Configuración de salida
Ordene los resultados y agregue estadísticas.
Object Sort Order: ordene por fecha de última modificación, nombre del objeto o tamaño del objeto en orden ascendente, descendente o predeterminado.
Data Aggregation: ejecute cálculos sobre los resultados de la consulta, como contar elementos únicos, agrupar y contar, buscar valores máximos o mínimos, calcular promedios y sumar valores.
API relacionadas
Para mayor personalización, llame directamente a las API REST. Deberá encargarse usted mismo del cálculo de firmas.
Habilite la gestión de metadatos con OpenMetaQuery.
Consulte los archivos coincidentes con DoMetaQuery.
Deshabilite la gestión de metadatos con CloseMetaQuery.
Facturación
-
El precio de MetaSearch consta de los dos componentes siguientes:
-
Cargos por la función MetaSearch
Son cargos de gestión por los metadatos de los objetos. Se facturan a la tarifa estándar de indexación de datos de OSS. Consulte Data indexing fees.
-
Cargos por solicitudes de API
Los cargos por solicitudes de API se generan durante las actualizaciones incrementales del índice de archivos. Se le cobra según la cantidad de llamadas a la API. A continuación se muestran las solicitudes de API que generan estos cargos:
Acciones
API
Recuento
Indexar un objeto en un bucket
HeadObject y GetObject
Una llamada por objeto
Indexar un objeto con etiquetas
GetObjectTag
Una llamada por objeto con etiquetas
Indexar un objeto con metadatos personalizados
GetObjectMeta
Una llamada por objeto con metadatos personalizados
Indexar un vínculo simbólico
GetSymlink
Una llamada por vínculo simbólico
Buscar objetos en un bucket
ListObjects
Una llamada por cada 1,000 objetos analizados
-
Para detener estos cargos, disable MetaSearch.
Preguntas frecuentes
Creación lenta del índice de datos en buckets grandes
La indexación procesa aproximadamente 600 objetos incrementales por segundo. Calcule el tiempo total estimado según la cantidad de objetos de su bucket.
Consultar el tamaño total de objetos por prefijo
Inicie sesión en la consola de OSS.
En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.
En el panel de navegación izquierdo, seleccione .
-
Establezca Object Name en Prefix Match e introduzca el prefijo:
random_files/. Mantenga los demás parámetros con su configuración predeterminada.
-
Configure Search Result Settings.
En Object Sort Order, seleccione Default.
-
En Data Aggregation, seleccione Sum de Object Size.

-
Haga clic en Query Now. Los resultados muestran el tamaño total de todos los objetos con el prefijo
random_files/.
Documentación relacionada
MetaSearch filtra por fecha de última modificación, clase de almacenamiento, ACL y tamaño de archivo. How to filter files in OSS within a specified time range.