Todos os produtos
Search
Central de documentação

Object Storage Service:Pesquisa vetorial (Java SDK V1)

Última atualização: Sep 22, 2026

A pesquisa vetorial do OSS permite encontrar rapidamente objetos em uma grande coleção com base em conteúdo semântico, metadados do OSS, metadados de multimídia, ETags de objeto, tags e metadados personalizados. Esse recurso melhora a eficiência da recuperação.

Observações

  • O recurso de pesquisa vetorial é compatível apenas com as versões 3.18.2 e posteriores do SDK do Java.

  • Esse recurso é compatível com buckets nas seguintes regiões: China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hangzhou), China (Shanghai), China (Shenzhen), China (Guangzhou), China (Chengdu), China (Hong Kong), Singapore, Indonesia (Jakarta), Germany (Frankfurt), US (Virginia) e US (Silicon Valley).

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

  • Neste tópico, você obtém as credenciais de acesso a partir de variáveis de ambiente. Para obter mais informações, consulte 配置访问凭证.

  • O exemplo deste tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte Client configuration.

  • Por padrão, uma conta do Alibaba Cloud tem as permissões necessárias para executar operações de indexação de dados. Para usar um usuário do Resource Access Management (RAM) ou o STS na execução dessas operações, são necessárias as seguintes permissões:

    • Para ativar o recurso de gerenciamento de metadados, é necessária a permissão oss:OpenMetaQuery.

    • Para recuperar informações sobre um índice de metadados, é requerida a permissão oss:GetMetaQueryStatus.

    • Para consultar objetos que atendem a condições específicas, a permissão oss:DoMetaQuery é obrigatória.

    • Para desativar o recurso de gerenciamento de metadados, deve-se ter a permissão oss:CloseMetaQuery.

Código de exemplo

Ativar o recurso de pesquisa vetorial

O código a seguir mostra como ativar o recurso de pesquisa vetorial para um bucket específico.

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 {
        // The endpoint is set to China (Hangzhou) in this example. Replace it with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Enable the vector search feature.
            ossClient.openMetaQuery(bucketName, MetaQueryMode.SEMANTIC);
        } 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.
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }
}

Obter informações sobre o índice de metadados

O código a seguir mostra como recuperar informações sobre o índice de metadados de um bucket específico.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetMetaQueryStatusResult;

public class GetMetaQueryStatus {
    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // The endpoint is set to China (Hangzhou) in this example. Replace it with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Get information about the metadata index of the specified bucket.
            GetMetaQueryStatusResult getResult = ossClient.getMetaQueryStatus(bucketName);
             // Get the current retrieval pattern.
            System.out.println(getResult.getMetaQueryMode().toString());
            // Get the current scan type.
            System.out.println(getResult.getPhase());
            // Get the status of the metadata index.
            System.out.println(getResult.getState());
            // Get the time when the metadata index was created.
            System.out.println(getResult.getCreateTime());
            // Get the time when the metadata index was last updated.
            System.out.println(getResult.getUpdateTime());
        } 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.
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }
}

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

O código a seguir mostra como usar o recurso de pesquisa vetorial para consultar objetos que correspondem a um conteúdo semântico específico.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
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 {
        // The endpoint is set to China (Hangzhou) in this example. Replace it with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            int maxResults = 20;
            List<String> mediaTypes = new ArrayList<String>();
            mediaTypes.add("image");
            String query = "Snow";
            String simpleQuery = "{\"Operation\":\"gt\", \"Field\": \"Size\", \"Value\": \"30\"}";
            String sort = "Size";
            DoMetaQueryRequest doMetaQueryRequest = new DoMetaQueryRequest(bucketName, maxResults, query, sort, MetaQueryMode.SEMANTIC, mediaTypes, simpleQuery);
            DoMetaQueryResult doMetaQueryResult = ossClient.doMetaQuery(doMetaQueryRequest);
        } 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 {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }
}

Desativar o recurso de pesquisa vetorial

O código a seguir mostra como desativar o recurso de pesquisa vetorial para um bucket específico.

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 {
        // The endpoint is set to China (Hangzhou) in this example. Replace it with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Disable the vector search 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.
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }
}

Referências

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

  • Consulte a operação da API GetMetaQueryStatus para obter mais detalhes sobre como recuperar informações de um índice de metadados.

  • Para saber mais sobre a operação da API usada para consultar objetos que atendem a condições específicas, consulte DoMetaQuery.

  • Se precisar de mais informações sobre a operação da API para desativar o recurso de gerenciamento de metadados, consulte CloseMetaQuery.