Todos los productos
Search
Centro de documentos

Object Storage Service:Búsqueda vectorial (SDK de Java V1)

Última actualización: Sep 03, 2026

La búsqueda vectorial de OSS permite encontrar rápidamente archivos de objetos en una gran colección según el contenido semántico, los metadatos de OSS, los metadatos multimedia, los ETags de objetos, las etiquetas y los metadatos personalizados. Esta función mejora la eficiencia de recuperación.

Notas

  • Solo las versiones 3.18.2 y posteriores del kit de desarrollo de software (SDK) de Java admiten la función de búsqueda vectorial.

  • La función de búsqueda vectorial es compatible con buckets en las siguientes regiones: 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) y US (Silicon Valley).

  • En este tema se usa el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.

  • De forma predeterminada, una cuenta de Alibaba Cloud tiene los permisos necesarios para ejecutar operaciones de indexación de datos. Si desea usar un usuario de Resource Access Management (RAM) o STS para ejecutar estas operaciones, debe contar con los siguientes permisos:

    • Para habilitar la función de gestión de metadatos, debe tener el permiso oss:OpenMetaQuery.

    • Para recuperar información sobre un índice de metadatos, debe tener el permiso oss:GetMetaQueryStatus.

    • Para consultar objetos que cumplen condiciones específicas, debe tener el permiso oss:DoMetaQuery.

    • Para deshabilitar la función de gestión de metadatos, debe tener el permiso oss:CloseMetaQuery.

Código de ejemplo

Habilitar la función de búsqueda vectorial

El siguiente código ejemplifica cómo habilitar la función de búsqueda vectorial para un 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();
            }
        }
    }
}

Obtener información sobre el índice de metadatos

El siguiente código ejemplifica cómo recuperar información sobre el índice de metadatos de un 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 cumplen condiciones específicas

El siguiente código ejemplifica cómo usar la función de búsqueda vectorial para consultar objetos que coinciden con contenido semántico especificado.

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();
            }
        }
    }
}

Deshabilitar la función de búsqueda vectorial

El siguiente código ejemplifica cómo deshabilitar la función de búsqueda vectorial para un 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();
            }
        }
    }
}

Referencias

  • Para obtener más información sobre la operación de API para habilitar la función de gestión de metadatos, consulte OpenMetaQuery.

  • Para obtener más información sobre la operación de API para recuperar información sobre un índice de metadatos, consulte GetMetaQueryStatus.

  • Para obtener más información sobre la operación de API para consultar objetos que cumplen condiciones específicas, consulte DoMetaQuery.

  • Para obtener más información sobre la operación de API para deshabilitar la función de gestión de metadatos, consulte CloseMetaQuery.