All Products
Search
Document Center

Object Storage Service:Use vector search to quickly find files by semantic content and multimedia features

Last Updated:Feb 28, 2026

OSS vector search locates objects across buckets by semantic content, multimedia properties, metadata, ETags, tags, and custom metadata -- without exact file names or paths.

Supported regions

RegionVector searchAudio search
China (Qingdao)SupportedSupported
China (Beijing)SupportedSupported
China (Zhangjiakou)SupportedSupported
China (Hangzhou)SupportedSupported
China (Shanghai)SupportedSupported
China (Shenzhen)SupportedSupported
China (Guangzhou)SupportedSupported
China (Chengdu)SupportedSupported
China (Hong Kong)SupportedNot supported
SingaporeSupportedNot supported
Indonesia (Jakarta)SupportedNot supported
Germany (Frankfurt)SupportedNot supported

Enable vector search

The bucket must be in a supported region. For SDK access, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

OSS console

  1. Log on to the OSS console.

  2. Click Buckets, then click the name of the target bucket.

  3. In the left-side navigation pane, choose Object Management > Data Indexing.

  4. On the Data Indexing page, if this is your first time using data indexing, follow the instructions to grant permissions to the AliyunMetaQueryDefaultRole role. After granting permissions, click Enable Data Indexing.

  5. In the retrieval method section, select AISearch and click Enable.

Building the metadata index takes time depending on the number of objects in the bucket. Refresh the page to check the status.

Alibaba Cloud SDK

Java

Java SDK 3.18.2 or later is required. For more information, see Vector search (Java SDK).

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the name of the bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Obtain a credential from the 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 of the bucket. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou.
        String region = "cn-hangzhou";

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

        try {
            // Enable AISearch.
            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 instance.
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }
}

Python

For more information, see Vector search.

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 credentials provider.
    cfg.credentials_provider = credentials_provider
    # Set the region based on the 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 OpenMetaQuery request to enable the vector search feature for the bucket.
    result = client.open_meta_query(oss.OpenMetaQueryRequest(
            bucket=args.bucket,
            mode='semantic',# Set to "semantic" to select vector search.
    ))

    # Print the status code and request ID of the result.
    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

For more information, see Vector search (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
)

// 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(&region, "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 the command line parameters.

	// Check whether the bucket name is specified. If the bucket name is not specified, return the default parameters and exit the program.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified. If the region is not specified, return the default parameters and exit the program.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// 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 AISearch for a specific bucket.
	request := &oss.OpenMetaQueryRequest{
		Bucket: oss.Ptr(bucketName),
		Mode: oss.Ptr("semantic"), // Set Mode to semantic, which specifies that AISearch is enabled.
	}
	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) // Display the results of the request.
}

PHP

For more information, see Vector search (PHP SDK V2).

<?php

// Include the autoloader file to ensure that dependency libraries can be loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required).
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional).
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required).
];

// Convert the argument descriptions to the long options 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 command-line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are present.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials 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 configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials 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);

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

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

ossutil

Enable vector search for the bucket named examplebucket:

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

For more information, see open-meta-query.

Search for objects

OSS console

The following example searches for files that contain "glowing buildings", are in JPG format, and have dimensions within 800 x 1200 pixels. The expected result is the "Night view by the river.jpg" image.

A night view of a city by a river
  1. Log on to the OSS console.

  2. Click Buckets, then click the name of the target bucket.

  3. In the left-side navigation pane, choose Object Management > Data Indexing.

  4. Set the Search Criteria. Keep default settings for other parameters.

    • In the Semantic Content section, enter a description of the image, for example, glowing buildings. image

    • For Multimedia Type, select Image. image

      • Set Image Format to JPG/JPEG.

      • Set Image Width to less than 800 px.

      • Set Image Height to less than 1200 px.

  5. Click Query Now. The search results match the expected output. The file is found based on the content description.

    image

For the complete list of search criteria and output settings, see Search criteria reference.

Alibaba Cloud SDK

Java

Java SDK 3.18.2 or later is required. For more information, see Vector search (Java SDK).

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the name of the bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Obtain a credential from the 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 of the bucket. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release 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 mediaTypes = new ArrayList();
            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();
            }
        }
    }
}

Python

For more information, see Vector search.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to handle command-line input.
parser = argparse.ArgumentParser(description="do meta query semantic sample")
# Add required 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 bucket name.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')  # The OSS endpoint, optional.

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

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

    # Load the default SDK configuration.
    cfg = oss.config.load_default()
    # Set the credentials 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 vector search mode.
    result = client.do_meta_query(oss.DoMetaQueryRequest(
            bucket=args.bucket,
            mode='semantic',
            meta_query=oss.MetaQuery(
                max_results=1000,
                query='Overlook the snow-covered forest',
                order='desc',
                media_types=oss.MetaQueryMediaTypes(
                    media_type=['image']
                ),
                simple_query='{"Operation":"gt", "Field": "Size", "Value": "30"}',
            ),
    ))

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

if __name__ == "__main__":
    main()

Go

For more information, see Vector search (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() {
	// Use a command line parameter to specify the region. By default, the parameter is an empty string.
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	// Use a command line parameter to specify the bucket name. By default, the parameter is an empty string.
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	flag.Parse() // Parse the command line parameters.

	// Check whether the bucket name is specified. If the bucket name is not specified, return the default parameters and exit the program.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified. If the region is not specified, return the default parameters and exit the program.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// 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) // Use the client configurations to create a new OSSClient instance.

	// Perform AISearch to query the objects that meet specific semantic conditions.
	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"), // Specify sematic content.
			MediaType: oss.Ptr("image"), // Specify the type of the media to be queried. In this example, the type of the media is set to 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

For more information, see Vector search (PHP SDK V2).

<?php

// Include the autoloader file to ensure that dependency libraries can be loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required).
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional).
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required).
];

// Convert the argument descriptions to the long options 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 command-line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are present.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials 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 configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials 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 a vector search to query 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

Search for objects that meet specified conditions in the bucket named 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

For more information, see do-meta-query.

Search criteria reference

Set one or more search criteria as needed.

OSS metadata

CriterionDescription
Storage ClassSelect which storage classes appear in results. With semantic content criteria selected: only Standard and Infrequent Access (IA) are supported. Without semantic content criteria: Standard, IA, Archive, Cold Archive, and Deep Cold Archive are all supported.
Access Control List (ACL)By default, all four ACL values are selected: Inherit from Bucket, Private, Public Read, and Public Read/Write. Select the values to filter by.
Object NameSupports Fuzzy Match and Equals. For example, to find exampleobject.txt: use Equals with the full name exampleobject.txt, or use Fuzzy Match with a prefix or suffix like example or .txt. Fuzzy match can hit any character in the object name. For example, entering test returns localfolder/test/.example.jpg, localfolder/test.jpg, and similar matches.
Upload TypeBy default, all four object types are selected: Normal (simple upload), Multipart (multipart upload), Appendable (append upload), and Symlink (symbolic link).
Last Modified AtSpecify a Start Date and End Date. Accurate to the second.
Object SizeFilter using: Equals, Greater Than, Greater Than Or Equal To, Less Than, or Less Than Or Equal To. Unit: KB.
Object VersionOnly the current version of an object can be queried.

Object ETag and tags

Filter objects by ETag or tag information.

  • ETag: Exact match only. Enclose the ETag in quotation marks. Example: "5B3C1A2E0563E1B002CC607C6689". Enter multiple ETags, one per line.

  • Object Tags: Specify as key-value pairs. Keys and values are case-sensitive. For more information about tag rules, see Object tagging.

Multimedia metadata

Filter results by properties of Image, Document, Audio, and Video content.

TypeSupported formats and properties
ImageFormats: JPG/JPEG, PNG, APNG, BMP, GIF, WEBP, TIFF, HEIC, HEIC-SEQUENCE, AVIF. Properties: width and height in pixels (px).
DocumentFormats: DOC, DOCX, PPTX, PPT, XLS, XLSX, PDF, RTF, TXT, LOG, XML, HTML.
VideoFormats: AVI, MPEG, MPG, RM, MOV, WMV, 3GP, MP4, FLV, MKV, TS. Properties: resolution (px), duration (s), bitrate (kbps).
AudioFormats: MP3, WMA, OGG, RA, MIDI, AIF/AIFF, M4A, MKA, MP2. Properties: duration (s).

Semantic content

Enter a text description to find related image, document, video, or audio files. The description is limited to 40 characters.

Examples: "photos of the Forbidden City in the snow", "how to use a wireless printer".

Restrictions when using semantic content search:

  • Object Sort Order and Data Aggregation output settings are not available.

  • Exactly one set of multimedia metadata search criteria must be selected.

  • Objects encrypted with Bring Your Own Key (BYOK) in Key Management Service (KMS) cannot be searched.

Custom metadata

Enter key-value pairs of custom metadata to filter results.

  • Specify Object Metadata as key-value pairs. For more information about custom metadata, see Manage file metadata.

  • Both key and value are required. A maximum of 20 custom pairs are supported.

Result output settings

When semantic content search criteria are set, sorting and data aggregation are not available.
  • Object Sort Order: Sort results by last modified time, object name, or object size in ascending or descending order.

  • Data Aggregation: Perform calculations on results, including count distinct values, group by, maximum, minimum, average, and sum.

Disable vector search

Disabling vector search does not affect data already stored in OSS. Re-enabling the feature rescans existing files and rebuilds the index. The rebuild time depends on the number of files.

Billing stops in the hour after the feature is disabled. Bill generation may be delayed, so monitor your bill.

OSS console

Log on to the OSS console. On the Data Indexing page, click Disable and confirm the action as prompted.

image

Alibaba Cloud SDK

Java

Java SDK 3.18.2 or later is required. For more information, see Vector search (Java SDK).

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the name of the bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Obtain a credential from the 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 of the bucket. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou.
        String region = "cn-hangzhou";

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

        try {
            // Disable AISearch 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

For more information, see Vector search.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to handle 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 credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration of the SDK.
    cfg = oss.config.load_default()
    # Set the credentials provider to the credentials obtained from environment variables.
    cfg.credentials_provider = credentials_provider
    # Set the region 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 search 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

For more information, see Vector search (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() {
	// Use a command line parameter to specify the region.
	flag.StringVar(&region, "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 the command line parameters.

	// Check whether the bucket name is specified. If the bucket name is not specified, return the default parameters and exit the program.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required") // Record the error and exit the program.
	}

	// Check whether the region is specified. If the region is not specified, return the default parameters and exit the program.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// 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 a specific bucket.
	request := &oss.CloseMetaQueryRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
	}
	result, err := client.CloseMetaQuery(context.TODO(), request) // Execute the request to disable the metadata management feature for the bucket.
	if err != nil {
		log.Fatalf("failed to close meta query %v", err)
	}

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

PHP

For more information, see Vector search (PHP SDK V2).

<?php

// Include the autoloader file to ensure that dependency libraries can be loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required).
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional).
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required).
];

// Convert the argument descriptions to the long options 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 command-line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are present.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials 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 configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials 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 search feature for the bucket.
$request = new \AlibabaCloud\Oss\V2\Models\CloseMetaQueryRequest(
    bucket: $bucket
);

// Execute the operation to disable the search feature.
$result = $client->closeMetaQuery($request);

// Print the result of disabling the search feature.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, used for debugging or tracking requests.
);

ossutil

Disable the metadata management feature for the bucket examplebucket:

ossutil api close-meta-query --bucket examplebucket

For more information, see close-meta-query.

Limits and performance

Bucket limits

LimitValue
Maximum files per bucket5 billion. Performance may degrade beyond this limit. To process more data, contact Technical Support for an evaluation.
Multipart upload objectsOnly complete objects assembled through the CompleteMultipartUpload operation appear in search results. Parts from incomplete or aborted uploads do not.

Internal bandwidth and QPS

OSS provides internal bandwidth and QPS for vector search at no cost to the bucket's Quality of Service (QoS) quota.

RegionInternal bandwidthDefault QPS
China (Beijing), China (Hangzhou), China (Shanghai), China (Shenzhen)10 Gbps1,250
Other regions1 Gbps1,250

Index generation time

During index building, API request fees are incurred for List, Head, and Get calls. Video, audio, and document files take longer to index than image files. Estimate the number of files before enabling.

Structured data and image files

Files in bucketEstimated time
10 million2 to 3 hours
100 million1 day
1 billionAbout 10 days

Video, document, and audio files

Files in bucketEstimated time
10 millionAbout 2 to 3 days
100 millionAbout 7 to 9 days

Incremental index updates

When the QPS for new, modified, or deleted files stays below the default value of 1,250, the latency between a file change and searchability is typically a few minutes to a few hours. If QPS exceeds 1,250, contact Technical Support for assistance.

Search response time

Search results are returned in seconds. The default timeout is 30 seconds.

Billing

Vector search fees consist of two parts:

Vector search feature fees

The vector search feature is currently in public preview and free of charge. This includes object metadata management fees. Billing will start after the public preview ends on August 25, 2025. After public preview, charges are based on OSS data indexing pricing. For more information, see Data indexing fees.

API request fees

API request fees are incurred during index building for existing files and index updates for incremental files. Charges are based on the number of API calls.

BehaviorAPI
Build indexes for files in the bucketHeadObject and GetObject
The bucket contains files with tagsGetObjectTag
The bucket contains files with custom metadataGetObjectMeta
The bucket contains symbolic link filesGetSymlink
Scan files in the bucketListObjects

For more information about OSS API request fees, see Request fees.

To stop incurring these charges, disable vector search.

FAQ

Why is a file not found immediately after upload?

After a file is uploaded, index generation takes some time. There is a delay before the file appears in search results. Wait a few moments, then search again.

API reference

OperationAPI
Enable data indexing or vector searchOpenMetaQuery
Search for objectsDoMetaQuery
Disable data indexingCloseMetaQuery