Todos os produtos
Search
Central de documentação

Object Storage Service:Pesquisa vetorial

Última atualização: Jun 23, 2026

Com a pesquisa vetorial do OSS, você pode localizar arquivos em conjuntos de dados massivos por conteúdo semântico, metadados, propriedades multimídia, ETags, tags e metadados personalizados.

Casos de uso

Cenários de escritório pessoal e corporativo

Pesquise arquivos de escritório por conteúdo semântico — por exemplo, "como usar o sistema ERP", "processo de reparo de TI" ou "análise de desempenho empresarial de 2024" — em vez de navegar manualmente pelas pastas.

Cenários de mídia social multimídia

Em aplicativos de mídia social com imagens enviadas por usuários, a pesquisa semântica permite que os usuários encontrem fotos pelo conteúdo — por exemplo, "passeio de primavera nos subúrbios" ou "reunião do Festival de Primavera" — sem marcação manual.

Cenários de armazenamento em nuvem

A pesquisa vetorial aprimora drives em nuvem pessoais ou corporativos ao permitir pesquisas baseadas em conteúdo para arquivos, como documentos específicos ou fotos em um álbum.

Cenários de videovigilância

Encontre gravações de vigilância específicas inserindo palavras-chave descritivas, como "vigilância externa em um dia de neve" ou "pomar em um dia ensolarado".

Limitações

  • Disponibilidade por região

    O recurso de pesquisa vetorial está disponível para buckets nas regiões China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hangzhou), China (Shanghai), China (Shenzhen), China (Guangzhou), China (Chengdu), China (Hong Kong), Singapura, Indonésia (Jakarta) e Alemanha (Frankfurt).

    null

    A pesquisa de áudio não é suportada nas regiões China (Hong Kong), Singapura, Indonésia (Jakarta) e Alemanha (Frankfurt).

  • Limitações de bucket

    Um bucket com a pesquisa vetorial ativada pode conter no máximo 5 bilhões de arquivos. Se o número de arquivos em um bucket exceder esse limite, o desempenho da pesquisa poderá ser degradado. Para processar um volume maior de dados, entre em contato com o Technical Support para uma avaliação.

  • Upload multipart

    Ao usar upload multipart, os resultados da pesquisa incluem apenas objetos totalmente montados com a operação CompleteMultipartUpload. Os resultados não incluem partes de uploads que foram iniciados, mas não concluídos ou cancelados.

Referência de desempenho

As métricas de desempenho a seguir se aplicam à pesquisa vetorial do OSS.

  • Largura de banda interna e QPS fornecidos pelo OSS

    O OSS fornece largura de banda interna dedicada e QPS para pesquisa vetorial. Essa capacidade suporta até 1.250 solicitações por segundo e não consome a cota de QoS do seu bucket.

    Região

    Largura de banda interna

    QPS padrão

    China (Beijing), China (Hangzhou), China (Shanghai) e China (Shenzhen)

    10 Gbps

    1250

    Outras regiões

    1 Gbps

    1250

  • Tempo estimado para indexar arquivos existentes

    A construção de índices gera taxas de solicitação de API para operações List, Head e Get (Taxas de solicitação de API). Arquivos de vídeo, áudio e documento levam mais tempo para indexar do que imagens. Estime a quantidade de arquivos antes de ativar esse recurso.

    • Se o bucket contiver principalmente dados estruturados e arquivos de imagem:

      • 10 milhões de arquivos em um único bucket: 2 a 3 horas

      • 100 milhões de arquivos em um único bucket: 1 dia

      • 1 bilhão de arquivos em um único bucket: cerca de 10 dias

    • Se o bucket contiver principalmente arquivos de vídeo, documento e áudio:

      • 10 milhões de arquivos em um único bucket: cerca de 2 a 3 dias

      • 100 milhões de arquivos em um único bucket: cerca de 7 a 9 dias

  • Tempo estimado para atualizar índices de arquivos incrementais

    Quando o QPS de alteração de arquivos estiver abaixo do padrão de 1.250, os arquivos ficam pesquisáveis em minutos a horas. Se o QPS exceder esse limite, entre em contato com o Technical Support para obter assistência.

  • Desempenho de resposta da pesquisa de arquivos

    As pesquisas retornam resultados em segundos. O tempo limite padrão é de 30 segundos.

Ativar a pesquisa vetorial

Console do OSS

  1. Faça logon no console do OSS.

  2. Clique em Buckets e, em seguida, clique no nome do bucket de destino.

  3. No painel de navegação à esquerda, escolha Files > Data Indexing.

  4. Na página Data Indexing, se estiver usando o recurso de indexação de dados pela primeira vez, siga as instruções na tela para conceder permissões à função AliyunMetaQueryDefaultRole. Isso permite que o OSS gerencie dados no bucket. Após conceder as permissões, clique em Enable Data Indexing.

  5. Selecione Vector Search e clique em Enable.

    null

    A construção do índice de metadados leva algum tempo, dependendo do número de objetos. Atualize a página para verificar o status.

Alibaba Cloud SDK

Java

Apenas o Java SDK 3.18.2 e versões posteriores oferecem suporte à pesquisa vetorial. Para mais informações, consulte Pesquisa vetorial (Java SDK V1).

Python

Para mais informações, consulte Pesquisa vetorial.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and add a description.
parser = argparse.ArgumentParser(description="open meta query sample")
# Add the required command-line argument --region to specify the region where the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the required command-line argument --bucket to specify the name of the bucket to operate on.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the optional command-line argument --endpoint to specify the domain name used to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load authentication information from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations provided by the SDK.
    cfg = oss.config.load_default()
    # Set the authentication information provider.
    cfg.credentials_provider = credentials_provider
    # Set the region based on command-line arguments.
    cfg.region = args.region
    # If an endpoint is provided, update the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Build an OpenMetaQueryRequest to enable the AISearch feature for the bucket.
    result = client.open_meta_query(oss.OpenMetaQueryRequest(
            bucket=args.bucket,
            mode='semantic',# Set to "semantic" to select AISearch.
    ))

    # Print the status code and request ID of the request.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# Call the main function when running as the main program.
if __name__ == "__main__":
    main()

Go

Para mais informações, consulte Pesquisa vetorial (Go SDK 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
	bucketName string
)

func init() {
	// Set a command-line flag to specify the region.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set a command-line flag to specify the bucket name.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Create a client configuration and use credentials from environment variables.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create an OSS client.

	// Create a request to enable AISearch for the specified bucket.
	request := &oss.OpenMetaQueryRequest{
		Bucket: oss.Ptr(bucketName),
		Mode:   oss.Ptr("semantic"), // Set mode to "semantic" to enable semantic search capabilities.
	}
	result, err := client.OpenMetaQuery(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to open meta query %v", err)
	}

	log.Printf("open meta query result:%#v\n", result)
}

PHP

Para mais informações, consulte Pesquisa vetorial (PHP SDK V2).

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region in which the bucket resides.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket resides.
$bucket = $options["bucket"]; // The name of the bucket.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket resides.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Enable the AISearch feature.
$request = new Oss\Models\OpenMetaQueryRequest($bucket,'semantic');
$result = $client->openMetaQuery($request);

printf(
   'status code:' . $result->statusCode . PHP_EOL .
   'request id:' . $result->requestId
);

ossutil

O comando a seguir fornece um exemplo de como ativar a pesquisa vetorial para um bucket chamado examplebucket:

ossutil api open-meta-query --bucket examplebucket --meta-query-mode semantic

Para mais informações sobre como usar o ossutil para pesquisa vetorial, consulte open-meta-query.

Iniciar uma pesquisa vetorial

Console do OSS

Esta seção fornece um exemplo de como pesquisar arquivos que contenham "edifícios iluminados", estejam no formato JPG e tenham dimensões de até 800 × 1.200 pixels. O resultado esperado da pesquisa é a imagem "Night view by the river.jpg" mostrada na figura a seguir.

Night view by the river

  1. Faça logon no console do OSS.

  2. Clique em Buckets e, em seguida, clique no nome do bucket de destino.

  3. No painel de navegação à esquerda, escolha Files > Data Indexing.

  4. Defina os Search Criteria. Mantenha as configurações padrão para os demais parâmetros.

    • Na seção Semantic Content, insira uma descrição da imagem, por exemplo, edifícios iluminados.image

    • Em Multimedia Type, selecione Image.

      • Defina Image Format como JPG/JPEG.

      • Defina Image Width como menor que 800 px.

      • Defina Image Height como menor que 1.200 px.

      image

  5. Clique em Search Now. Os resultados da pesquisa são os esperados. O arquivo foi encontrado com base na descrição do recurso.

    image

    Para informações sobre todos os critérios de pesquisa e configurações de saída, consulte Critérios de pesquisa e configurações de saída.

Alibaba Cloud SDK

Java

Apenas o Java SDK 3.18.2 e versões posteriores oferecem suporte à pesquisa vetorial. Para mais informações, consulte Pesquisa vetorial (Java SDK V1).

Python

Para mais informações, consulte Pesquisa vetorial.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to process command-line input.
parser = argparse.ArgumentParser(description="do meta query semantic sample")
# Add the necessary command-line arguments.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)  # The region where the bucket is located.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)  # The name of the bucket.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')  # The OSS domain name, which is optional.

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load access credentials from environment variables.
    # Before running, you need to set the environment variables: OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Set the region.
    cfg.region = args.region
    # If an endpoint is provided, update the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client instance.
    client = oss.Client(cfg)

    # Initiate a metadata query request in AISearch mode.
    result = client.do_meta_query(oss.DoMetaQueryRequest(
            bucket=args.bucket,
            mode='semantic',
            meta_query=oss.MetaQuery(
                max_results=1000,
                query='An aerial view of a snow-covered forest',
                order='desc',
                media_types=oss.MetaQueryMediaTypes(
                    media_type=['image']
                ),
                simple_query='{"Operation":"gt", "Field": "Size", "Value": "30"}',
            ),
    ))

    # Print the retrieval results.
    print(vars(result))

if __name__ == "__main__":
    main()

Go

Para mais informações, consulte Pesquisa vetorial (Go SDK 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
	bucketName string
)

func init() {
	// Set a command-line flag to specify the region.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set a command-line flag to specify the bucket name.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Create a client configuration and use credentials from environment variables and the specified region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create an OSS client.

	// Perform an AISearch operation.
	request := &oss.DoMetaQueryRequest{
		Bucket: oss.Ptr(bucketName),
		Mode:   oss.Ptr("semantic"),
		MetaQuery: &oss.MetaQuery{
			MaxResults: oss.Ptr(int64(99)),
			Query:      oss.Ptr("Overlook the snow-covered forest"), // Provide the semantic query string. This is an example.
			MediaTypes: &oss.MetaQueryMediaTypes{
				MediaTypes: []string{"image"}, // Specify the media types to search. In this example, "image".
			},
			SimpleQuery: oss.Ptr(`{"Operation":"gt", "Field": "Size", "Value": "30"}`),
		},
	}
	result, err := client.DoMetaQuery(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to do meta query %v", err)
	}

	log.Printf("do meta query result:%#v\n", result)
}

PHP

Para mais informações, consulte Pesquisa vetorial (PHP SDK V2).

<?php

// Import the autoloader file to ensure that dependency libraries are 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 where 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 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 where 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 where 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);

// Perform an AISearch query for objects that meet the specified conditions.
$request = new Oss\Models\DoMetaQueryRequest($bucket, new Oss\Models\MetaQuery(
    maxResults: 99,
    query: "Overlook the snow-covered forest",
    mediaTypes: new Oss\Models\MetaQueryMediaTypes('image'),
    simpleQuery: '{"Operation":"gt", "Field": "Size", "Value": "30"}',
), 'semantic');

$result = $client->doMetaQuery($request);
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'result:' . var_export($result, true)
);

ossutil

O comando a seguir fornece um exemplo de como consultar arquivos que atendam às condições especificadas em um bucket chamado examplebucket.

ossutil api do-meta-query --bucket examplebucket --meta-query "{\"Query\":\"Overlooking the snow covered forest\",\"MediaTypes\":{\"MediaType\":\"image\"},\"SimpleQuery\":\"{\\\"Operation\\\":\\\"gt\\\", \\\"Field\\\": \\\"Size\\\", \\\"Value\\\": \\\"1\\\"}\"}" --meta-query-mode semantic

Para mais informações sobre este comando, consulte do-meta-query.

Desativar a pesquisa vetorial

  • Desativar a pesquisa vetorial não afeta os dados armazenados. Reativá-la aciona uma nova varredura completa e reconstrução de índice, cujo tempo depende da quantidade de arquivos.

  • O faturamento é interrompido em até uma hora após a desativação do recurso. A geração da fatura pode sofrer atraso.

Console do OSS

Faça logon no console do OSS. Na página Data Indexing, clique em Disable ao lado de Vector Search e confirme a ação conforme solicitado.

image

Alibaba Cloud SDK

Java

Apenas o Java SDK 3.18.2 e versões posteriores oferecem suporte à pesquisa vetorial. Para mais informações, consulte Pesquisa vetorial (Java SDK V1).

Python

Para mais informações, consulte Pesquisa vetorial.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to process 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 command-line arguments.
    args = parser.parse_args()

    # Load credential information from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider to the credentials obtained from environment variables.
    cfg.credentials_provider = credentials_provider
    # Set the region information in the configuration.
    cfg.region = args.region
    # If an endpoint is provided, set the endpoint in the configuration.
    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 retrieval feature for the bucket.
    result = client.close_meta_query(oss.CloseMetaQueryRequest(
            bucket=args.bucket,
    ))

    # Print the status code and request ID of the response.
    print(f'status code: {result.status_code}, request id: {result.request_id}')

# Execute the main function when this script is run directly.
if __name__ == "__main__":
    main()

Go

Para mais informações, consulte Pesquisa vetorial (Go SDK 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
	bucketName string
)

func init() {
	// Set a command-line flag to specify the region.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Set a command-line flag to specify the bucket name.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}


func main() {
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Create a client configuration and use credentials from environment variables and the specified region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg) // Create an OSS client.

	// Create a request to disable AISearch for the specified bucket.
	request := &oss.CloseMetaQueryRequest{
		Bucket: oss.Ptr(bucketName), // Specify the target bucket.
	}
	result, err := client.CloseMetaQuery(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to close meta query %v", err)
	}

	log.Printf("close meta query result:%#v\n", result)
}

PHP

Para mais informações, consulte Pesquisa vetorial (PHP SDK V2).

<?php

// Import the autoloader file to ensure that dependency libraries are 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 where 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 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 where 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 where 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 for debugging or request tracking.
);

ossutil

O comando a seguir fornece um exemplo de como desativar o recurso de pesquisa vetorial para um bucket chamado examplebucket:

ossutil api close-meta-query --bucket examplebucket

Para mais informações sobre este comando, consulte close-meta-query.

Critérios de pesquisa e configurações de saída

Critérios de pesquisa

Defina um ou mais dos critérios de pesquisa a seguir.

Critérios de pesquisa de metadados do OSS

Critério

Descrição

Storage Class

Selecione as classes de armazenamento dos objetos a serem incluídos nos resultados da consulta.

  • Se você definir conteúdo semântico como critério de pesquisa, apenas as classes de armazenamento Standard e Infrequent Access (IA) são suportadas.

  • Se você não definir conteúdo semântico como critério de pesquisa, as classes de armazenamento Standard, IA, Archive, Cold Archive e Deep Cold Archive são suportadas por padrão.

Access Control List (ACL)

Por padrão, todas as quatro ACLs do OSS são selecionadas: Inherit from Bucket, Private, Public Read e Public Read/Write. Selecione as ACLs dos objetos a serem incluídos nos resultados da consulta.

File Name

Fuzzy Match e Equals são suportadas. Para encontrar um arquivo específico como exampleobject.txt, faça a correspondência de uma das seguintes maneiras:

  • Selecione Equals e insira o nome completo do arquivo exampleobject.txt.

  • Selecione Fuzzy Match e insira um prefixo ou sufixo de arquivo, como example ou .txt.

    null

    Uma correspondência aproximada pode corresponder a qualquer substring do nome do objeto. Por exemplo, se você inserir test, os resultados da consulta incluirão objetos como localfolder/test/.example.jpg e localfolder/test.jpg.

Upload Type

Consulte por tipo de objeto. O OSS suporta os seguintes tipos, todos selecionados por padrão:

  • Normal: um objeto criado por upload simples.

  • Multipart: um objeto criado por upload multipart.

  • Appendable: um objeto criado por upload de anexação.

  • Symbolic link: um link simbólico que fornece acesso rápido a um objeto.

Last Modified Time

Especifique a Start Date e a End Date da última modificação do objeto. A precisão é de segundos.

File Size

Cinco condições de filtro são suportadas: Equals, Greater Than, Greater Than Or Equal To, Less Than e Less Than Or Equal To. O tamanho do arquivo é medido em KB.

Object Version

É possível consultar apenas a versão atual de um objeto.

Critérios de pesquisa por ETag e tag de objetos

Para filtrar objetos por ETag e tag, insira as informações de ETag ou tag dos objetos que deseja recuperar.

  • ETag suporta apenas correspondência exata. O ETag deve estar entre aspas. Exemplo: "5B3C1A2E0563E1B002CC607C6689". É possível inserir vários ETags, um por linha.

  • Especifique Object Tags como pares chave-valor. As chaves e os valores das tags de objetos diferenciam maiúsculas de minúsculas. Para mais informações sobre regras de tags, consulte Marcação de objetos.

Critérios de pesquisa de metadados multimídia

Filtre os resultados com base em propriedades específicas de arquivos de Image, Document, Audio e Video.

Critério

Descrição

Imagem

  • Formatos suportados: JPG/JPEG, PNG, APNG, BMP, GIF, WEBP, TIFF, HEIC, HEIC-SEQUENCE e AVIF.

  • Largura e altura da imagem: defina um intervalo para a largura e a altura em pixels (px).

Documento

  • Formatos suportados: DOC, DOCX, PPTX, PPT, XLS, XLSX, PDF, RTF, TXT, LOG, XML e HTML.

Vídeo

  • Formatos suportados: AVI, MPEG, MPG, RM, MOV, WMV, 3GP, MP4, FLV, MKV e TS.

  • Resolução do vídeo: defina um intervalo para a resolução do vídeo em pixels (px).

  • Duração do vídeo: defina um intervalo de duração em segundos (s).

  • Taxa de bits do vídeo: defina um intervalo de taxa de bits em kilobits por segundo (kbps).

Áudio

  • Formatos suportados: MP3, WMA, OGG, RA, MIDI, AIF/AIFF, M4A, MKA e MP2.

  • Duração do áudio: defina um intervalo de duração em segundos (s).

Critérios de pesquisa por conteúdo semântico

Insira conteúdo semântico para recuperar rapidamente recursos de imagem, documento, vídeo ou áudio relacionados.

  • Pesquise arquivos com conteúdo específico. A consulta de pesquisa é limitada a 40 caracteres. Por exemplo, pesquise "fotos da Cidade Proibida na neve" ou "como usar uma impressora sem fio".

  • Limitações da pesquisa por conteúdo semântico:

    • Não é possível definir os métodos de saída Object Sorting Method ou Data Aggregation.

    • É necessário selecionar exatamente um conjunto de Multimedia Metadata Search Criteria.

    • Não é suportada a pesquisa de objetos criptografados com o recurso Bring Your Own Key (BYOK) do Key Management Service (KMS).

Critérios de pesquisa de metadados personalizados

Insira pares chave-valor de metadados personalizados para recuperar resultados com precisão.

  • Especifique Object Metadata como pares chave-valor. Para mais informações sobre metadados personalizados, consulte Gerenciar metadados de objetos.

  • É possível adicionar vários pares chave-valor. Tanto a chave quanto o valor são obrigatórios. São suportados no máximo 20 pares personalizados.

Configurações de saída de resultados

Ao pesquisar por conteúdo semântico, não é possível especificar um método de classificação nem usar agregação de dados.

Classifique os resultados e execute agregações básicas.

  • Object Sorting Method: classifique os resultados por hora da última modificação, nome do arquivo ou tamanho do arquivo em ordem crescente ou decrescente.

  • Data Aggregation: realize cálculos nos resultados da pesquisa, como contagem de valores distintos, contagem por grupo e cálculo de máximo, mínimo, média e soma.

Referência de API

Essas operações usam APIs REST. Para chamar as APIs diretamente, é necessário escrever código para calcular assinaturas.

Ativar pesquisa vetorial: OpenMetaQuery.

Consultar arquivos: DoMetaQuery.

Desativar pesquisa vetorial: CloseMetaQuery.

Faturamento

  • As taxas de pesquisa vetorial consistem em duas partes principais:

    • Taxas do recurso de pesquisa vetorial

      Isso abrange o gerenciamento de metadados de objetos, cobrado conforme as taxas de indexação de dados do OSS. Taxas de indexação de dados.

    • Taxas de solicitação de API

      As taxas de solicitação de API são geradas durante a construção de índices e atualizações incrementais. A cobrança é feita pelo número de chamadas de API:

      Ações

      API

      Construir índices para arquivos no bucket.

      HeadObject e GetObject

      O bucket contém arquivos que possuem tags.

      GetObjectTag

      O bucket contém arquivos que possuem metadados personalizados.

      GetObjectMeta

      O bucket contém arquivos de link simbólico.

      GetSymlink

      Varrer arquivos no bucket.

      ListObjects

      Taxas de solicitação.

  • Para interromper as cobranças relacionadas, desative a pesquisa vetorial em tempo hábil.

Perguntas frequentes

Por que não consigo encontrar um arquivo imediatamente após o upload?

A geração de índice leva algum tempo após o upload. Se um arquivo não aparecer nos resultados imediatamente, aguarde alguns instantes e pesquise novamente.