OSS vector search lets you quickly find object files from a massive number of objects based on criteria such as semantic content, OSS metadata, multimedia metadata, object ETags and tags, and custom metadata. This feature optimizes search efficiency.
Scenarios
Personal and enterprise office scenarios
Vector search lets you search for office files directly by specific semantic content. For example, you can search for keywords such as "ERP system usage," "IT repair process," or "2024 business performance analysis." This simplifies file searching and improves office efficiency.
Multimedia social media scenarios
In multimedia social media scenarios, you can use the search feature to offer your users search functions for specific content and multimedia data. For example, in a social media application where users upload a large amount of image data, semantic search allows users to search for images directly based on their content. For example, they can search for photos with content such as "spring outing in the suburbs," "Spring Festival reunion," or "the seas I have seen." This adds practicality and fun to the application.
Cloud drive scenarios
Most cloud drives currently offer file search based on scalar retrieval, which allows searching by file name, creation time, or file extension. In personal or enterprise cloud drive scenarios, you can use the vector search feature to search for specific content, such as related documents or photos in an album.
Video surveillance scenarios
For video surveillance data, enterprises can use the vector search feature to search for specific files among the monitoring data. For example, you can enter keywords such as "outdoor surveillance on a snowy day" or "orchard on a sunny day" to retrieve the corresponding files.
Limits
Region limits
The vector search feature is available for buckets in the China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hangzhou), China (Shanghai), China (Shenzhen), China (Guangzhou), China (Chengdu), China (Hong Kong), Singapore, Indonesia (Jakarta), and Germany (Frankfurt) regions.
NoteAudio search is not currently supported in the China (Hong Kong), Singapore, Indonesia (Jakarta), and Germany (Frankfurt) regions.
Bucket limits
A bucket with vector search enabled can contain a maximum of 5 billion files. If the number of files in a bucket exceeds 5 billion, search performance may degrade. To process a larger amount of data, contact Technical Support for an evaluation.
Multipart upload
For objects created using multipart upload, the search results show only complete objects that have been assembled from parts using the CompleteMultipartUpload operation. The results do not show parts from uploads that have been initiated but not completed or aborted.
Performance reference
The following performance metrics for the OSS vector search mode are for reference only.
Internal bandwidth and QPS provided by OSS
The internal bandwidth and queries per second (QPS) can process 1,250 file requests per second. This capacity is provided in addition to the vector search mode and does not consume your bucket's Quality of Service (QoS).
Region
Internal bandwidth
Default QPS
China (Beijing), China (Hangzhou), China (Shanghai), and China (Shenzhen)
10 Gbps
1250
Other regions
1 Gbps
1250
Reference for existing file index generation time
During index building for the vector search mode, request fees are incurred for API calls such as List, Head, and Get. Additionally, index generation for video, audio, and document files takes longer than for image files. You should estimate the number of files before using this feature.
If the bucket contains mainly structured data and image files:
10 million files in a single bucket: 2 to 3 hours
100 million files in a single bucket: 1 day
1 billion files in a single bucket: about 10 days
If the bucket contains mainly video, document, and audio files:
10 million files in a single bucket: about 2 to 3 days
100 million files in a single bucket: about 7 to 9 days
Reference for incremental file index update time
When the QPS for new, modified, or deleted files in the bucket is lower than the default value of 1,250, the latency between file upload or modification and when the file becomes searchable is typically a few minutes to a few hours. If the QPS exceeds the default value of 1,250, you can contact Technical Support. We will evaluate the situation and provide technical support.
File search response performance
Search results are returned in seconds. The default timeout is 30 seconds.
Enable vector search
Use the OSS console
Log on to the OSS console.
Click Buckets and then click the name of the target bucket.
In the navigation pane on the left, choose .
On the Data Indexing page, if you are using the data indexing feature for the first time, follow the instructions to grant permissions to the AliyunMetaQueryDefaultRole role. This allows the OSS service to manage data in the bucket. After you grant the permissions, click Enable Data Indexing.
Select Vector Search and click Enable.
NoteBuilding the metadata index takes some time. The duration depends on the number of objects in the bucket. If the process takes too long, you can refresh the page to check the enabling status.
Use an Alibaba Cloud SDK
Java
Only Java SDK 3.18.2 and later versions support the vector search feature. 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(®ion, "region", "", "The region in which the bucket is located.")
// Use a command line parameter to specify the bucket name.
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
flag.Parse() // Parse 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
);Use ossutil
The following example shows how to enable the vector search feature for the bucket named examplebucket. The command is as follows:
ossutil api open-meta-query --bucket examplebucket --meta-query-mode semanticFor more information about this command, see open-meta-query.
Initiate a vector search
Use the OSS console
This section provides an example of how to search for files that contain "glowing buildings", are in JPG format, and have a width and height within 800 × 1200 pixels. The expected search result is the "Night view by the river.jpg" image shown in the following figure.

Log on to the OSS console.
Click Buckets and then click the name of the target bucket.
In the navigation pane on the left, choose .
Set the Search Criteria. Keep the default settings for other parameters.
In the Semantic Content section, enter a description of the image, for example, glowing buildings.

For Multimedia Type, select Image.
Set Image Format to JPG/JPEG.
Set Image Width to less than 800 px.
Set Image Height to less than 1200 px.

Click Search Now. The search results are as expected. The file is successfully found based on the feature description.

For more information about the complete search criteria and output settings, see Search criteria and output settings.
Use an Alibaba Cloud SDK
Java
Only Java SDK 3.18.2 and later versions support the vector search feature. 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(®ion, "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)
);Use ossutil
The following example shows how to query files 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 semanticFor more information about this command, see do-meta-query.
Disable vector search
Disabling this feature does not affect the data already stored in OSS. If you re-enable the feature later, the system rescans existing files and rebuilds the index. This process takes some time, depending on the number of files.
Billing stops in the hour after the feature is disabled. However, there may be a delay in bill generation. For this reason, you should monitor your bill.
Use the OSS console
Log on to the OSS console. On the Data Indexing page, click Disable in the Vector Search section and confirm the action as prompted.

Use an Alibaba Cloud SDK
Java
Only Java SDK 3.18.2 and later versions support the vector search feature. 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(®ion, "region", "", "The region in which the bucket is located.")
// Use a command line parameter to specify the bucket name.
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
flag.Parse() // Parse 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.
);
Use ossutil
The following example shows the command to disable the metadata management feature for the bucket examplebucket:
ossutil api close-meta-query --bucket examplebucketFor more information about this command, see close-meta-query.
Search criteria and output settings
Search criteria settings
The following are the complete search criteria. You can set one or more search criteria as needed.
Result output settings
After you set the "Semantic content search criteria", you cannot specify a sorting method or data aggregation.
You can sort and perform simple statistics on the output results.
Object Sorting Method: You can sort results by last modified time, file name, or file size in ascending or descending order. You can sort the search results as needed to quickly find the required files.
Data Aggregation: You can perform calculations on the search results, such as counting distinct values, counting by group, and calculating the maximum, minimum, average, and sum. This allows for efficient data analysis and management.
Related API operations
The preceding operations are based on API operations. If your program has highly customized requirements, you can directly call REST APIs. To directly call REST APIs, you must manually write code to calculate signatures.
For more information about how to enable the metadata management feature, see OpenMetaQuery.
For more information about how to query files that meet specified conditions, see DoMetaQuery.
For more information about how to disable the metadata management feature, see CloseMetaQuery.
Billing
Vector search fees consist of the following two parts:
Vector search feature fees (free during public preview)
This includes object metadata management fees. This feature is currently in public preview and is free of charge. Billing will officially start after the public preview ends on August 25, 2025. After the public preview ends, you will be charged based on the 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. You are charged based on the number of API calls. The API requests involved are as follows:
Behavior
API
Build indexes for files in the bucket
HeadObject and GetObject
The bucket contains files with tags
GetObjectTag
The bucket contains files with custom metadata
GetObjectMeta
The bucket contains symbolic link files
GetSymlink
Scan files in the bucket
ListObjects
For more information about OSS API request fees, see Request fees.
If you want to stop incurring these charges, you must disable vector search.
FAQ
Why can't I find a file immediately after it is uploaded?
After a file is uploaded, it takes some time to generate the index for the file. Therefore, there is a delay before the file appears in search results. You may not be able to retrieve the file immediately. Wait for a few moments and try again.