You need to enable JavaScript to run this app.
Torch Object Storage

Torch Object Storage

Copy page
Download PDF
Vector
QueryVectors(TOS Vectors Node.js SDK)
Copy page
Download PDF
QueryVectors(TOS Vectors Node.js SDK)
The queryVectors interface retrieves the TopK vectors closest in distance. This article explains how to perform this operation using the queryVectors interface in the TOS Vectors Node.js SDK.​
Notes​
  • To prevent key leakage, this example code reads Access Key ID and Secret Access Key from environment variables. Therefore, before using the SDK, you need to configure long-term access credentials. For details, see Configure Long-term Access Credentials.​
  • The TOS Vectors Node.js SDK supports using temporary access credentials. It also supports timeout settings, retry policies, and other mechanisms. You can configure these flexibly based on your business needs to enhance application security. For details, see Common Configuration Scenarios.​
Permissions required​
The primary account has all permissions by default, but IAM users have no permissions by default. If you want to use a sub-account to perform queryVectors operations, the primary account must grant the sub-account the following permissions through IAM policies and bucket policies:​
tosvectors:QueryVectors​
Code example​
Query the nearest TopK vectors​
​
// Query the nearest TopK vectors​
​
import {​
TosVectorsClient,​
TosClientError,​
TosServerError,​
} from "@volcengine/tos-sdk";​
​
// Retrieve authentication information and configuration from environment variables​
const client = new TosVectorsClient({​
accessKeyId: process.env["TOS_ACCESS_KEY"], // TOS_ACCESS_KEY: your Access Key ID​
accessKeySecret: process.env["TOS_SECRET_KEY"], // TOS_SECRET_KEY: your Secret Key​
region: 'Provide your region',​
endpoint: 'Provide your vector endpoint',​
});​
​
const vectorBucketName = 'Provide your vector bucket name';​
const accountId = process.env["TOS_ACCOUNT_ID"];​
const indexName = "test";​
​
/**​
* Handle errors that may occur during SDK calls.​
*@paramerror The captured error object​
*/​
function handleError(error: Error) {​
if (error instanceof TosClientError) {​
// Client-side exceptions, usually due to parameter errors or network issues​
console.log("Client Error:");​
console.log(" Message:", error.message);​
if (error.stack) {​
console.log(" Stack:", error.stack);​
}​
} else if (error instanceof TosServerError) {​
// Server-side exceptions, indicating the request was received but failed to process​
console.log("Server Error:");​
console.log(" Request ID:", error.requestId);​
console.log(" Status Code:", error.statusCode);​
console.log(" Code:", error.code);​
console.log(" Message:", error.message);​
console.log(" Headers:", error.headers);​
} else {​
// Other unknown exceptions​
console.log("Unexpected Error:");​
console.log(" Message:", error.message);​
}​
}​
​
async function main() {​
// Ensure the following dimensions match the dimension used when creating the index​
const dimension = 128;​
const topK = 5;​
​
try {​
console.log(​
`Querying top ${topK} nearest vectors from index: ${indexName} in vector bucket: ${vectorBucketName}...`,​
);​
​
// 1. Construct the query vector consistent with the index dimension致​
const queryVectorData = Array.from({ length: dimension }, () =>​
Math.random(),​
);​
​
// 2. Assemble the QueryVectors input parameter数​
​
// 3. Call the queryVectors method to find nearest neighbors量​
const result = await client.queryVectors({​
vectorBucketName,​
accountID: accountId,​
indexName,​
returnDistance: true,​
returnMetadata: true,​
topK,​
queryVector: {​
float32: queryVectorData,​
},​
// To filter by business metadata, set the filter here, for example:​
// filter: { category: "book" },​
});​
​
// 4. Print general response information息​
console.log("QueryVectors Request Succeeded:");​
console.log(" Request ID:", result.requestId);​
console.log(" Status Code:", result.statusCode);​
console.log(" Headers:", result.headers);​
​
// 5. Print core business data fields: returned vector key, distance, and metadataa​
const vectors = result.data?.vectors;​
​
if (!vectors || vectors.length === 0) {​
console.log(" No vectors returned for this query.");​
return;​
}​
​
console.log(" Matched Vectors:");​
vectors.forEach((vector, index) => {​
console.log(` [${index}] Key: ${vector.key}`);​
console.log(` Distance: ${vector.distance}`);​
console.log(" Metadata:", vector.metadata);​
});​
} catch (error: any) {​
handleError(error);​
}​
}​
​
main();​
​
​
Related documentation​
For the API documentation of QueryVectors, see QueryVectors.​
Last updated: 2026.02.06 18:01:45