import type { ResetCommandOptions } from "@commands/client"; import { DeleteCommand, FetchCommand, InfoCommand, Namespace, QueryCommand, QueryManyCommand, RangeCommand, ResetCommand, UpdateCommand, UpsertCommand, } from "@commands/client"; import { ResumableQuery, type ResumableQueryPayload } from "@commands/client/resumable-query"; import type { Dict } from "@commands/client/types"; import { DeleteNamespaceCommand, ListNamespacesCommand } from "@commands/management"; import type { Requester } from "@http"; export type CommandArgs any> = ConstructorParameters[0]; /** * Serverless vector client for upstash vector db. */ export class Index { protected client: Requester; /** * Create a new vector db client * * @example * ```typescript * const index = new Index({ * url: "", * token: "", * }); * ``` */ constructor(client: Requester) { this.client = client; } namespace = (namespace: string) => new Namespace(this.client, namespace); /** * Deletes items from the index by id, by id prefix, or by filter. * * @example * ```js * // Delete by id * await index.delete("test-id"); * // Delete by ids * await index.delete(["test-id1", "test-id2"]); * // Delete by id prefix * await index.delete({ prefix: "test-" }); * // Delete by filter * await index.delete({ filter: "age >= 23" }); * ``` * * @param args - A single id, an array of ids, a prefix, or a filter to delete items from the index. * @returns Number of deleted vectors in the format `{ deleted: number }`.If no vectors are deleted, returns `{ deleted: 0 }`. * @see node_modules/@upstash/vector/docs/commands/delete.mdx */ delete = (args: CommandArgs, options?: { namespace?: string }) => new DeleteCommand(args, options).exec(this.client); /** * Queries an index with specified parameters. * This method creates and executes a query command on an index based on the provided arguments. * * @example * ```js * await index.query({ * topK: 3, * vector: [ 0.22, 0.66 ], * filter: "age >= 23 and (type = \'turtle\' OR type = \'cat\')" * }); * ``` * * @param {Object} args - The arguments for the query command. * @param {number[]} args.vector - An array of numbers representing the feature vector for the query. * This vector is utilized to find the most relevant items in the index. * @param {number} args.topK - The desired number of top results to be returned, based on relevance or similarity to the query vector. * @param {string} [args.filter] - An optional filter string to be used in the query. The filter string is used to narrow down the query results. * @param {boolean} [args.includeVectors=false] - When set to true, includes the feature vectors of the returned items in the response. * @param {boolean} [args.includeMetadata=false] - When set to true, includes additional metadata of the returned items in the response. * @param {boolean} [args.includeData=false] - When set to true, includes data - string - of the returned items in the response. * * A promise that resolves with an array of query result objects when the request to query the index is completed. * * @see node_modules/@upstash/vector/docs/commands/query.mdx */ query = ( args: CommandArgs, options?: { namespace?: string } ) => new QueryCommand(args, options).exec(this.client); /** * Queries an index with specified parameters. * This method creates and executes a query command on an index based on the provided arguments. * * @example * ```js * await index.queryMany([ * { * topK: 3, * vector: [0.22, 0.66], * filter: "age >= 23 and (type = 'turtle' OR type = 'cat')", * }, * { * topK: 3, * vector: [0.45, 0.52], * filter: "age >= 27 and (type = 'rabbit' OR type = 'dog')", * }, * ]); * * ``` * * @param {Object} args - The arguments for the query command. * @param {number[]} args.vector - An array of numbers representing the feature vector for the query. * This vector is utilized to find the most relevant items in the index. * @param {number} args.topK - The desired number of top results to be returned, based on relevance or similarity to the query vector. * @param {string} [args.filter] - An optional filter string to be used in the query. The filter string is used to narrow down the query results. * @param {boolean} [args.includeVectors=false] - When set to true, includes the feature vectors of the returned items in the response. * @param {boolean} [args.includeMetadata=false] - When set to true, includes additional metadata of the returned items in the response. * @param {boolean} [args.includeData=false] - When set to true, includes data - string - of the returned items in the response. * * A promise that resolves with an array of arrays of query result objects, * where each inner array represents a group of results matching a specific query condition. * * @see node_modules/@upstash/vector/docs/commands/query.mdx */ queryMany = ( args: CommandArgs, options?: { namespace?: string } ) => new QueryManyCommand(args, options).exec(this.client); /** * Initializes a resumable query operation on the vector database. * This method allows for querying large result sets in multiple chunks or implementing pagination. * * @template TMetadata * @param {ResumableQueryPayload} args - The arguments for the resumable query. * @param {number} args.maxIdle - The maximum idle time in seconds before the query session expires. * @param {number} args.topK - The number of top results to return in each fetch operation. * @param {number[]} args.vector - The query vector used for similarity search. * @param {boolean} [args.includeMetadata] - Whether to include metadata in the query results. * @param {boolean} [args.includeVectors] - Whether to include vectors in the query results. * @param {Object} [options] - Additional options for the query. * @param {string} [options.namespace] - The namespace to query within. * @returns {Promise>} A promise that resolves to a ResumableQuery object. * @example * const { result, fetchNext, stop } = await index.resumableQuery({ * maxIdle: 3600, * topK: 50, * vector: [0.1, 0.2, 0.3, ...], * includeMetadata: true, * includeVectors: true * }, { namespace: 'my-namespace' }); * * const firstBatch = await fetchNext(10); * const secondBatch = await fetchNext(10); * await stop(); // End the query session * * @see node_modules/@upstash/vector/docs/commands/resumable-query.mdx */ resumableQuery = async ( args: ResumableQueryPayload, options?: { namespace?: string } ) => { const resumableQuery = new ResumableQuery(args, this.client, options?.namespace); const initialQuery = await resumableQuery.start(); const { fetchNext, stop } = resumableQuery; return { fetchNext, stop, result: initialQuery.scores }; }; /** * Upserts (Updates and Inserts) specific items into the index. * It's used for adding new items to the index or updating existing ones. * * @example * ```js * const upsertArgs = { * id: '123', * vector: [0.42, 0.87, ...], * metadata: { property1: 'value1', property2: 'value2' } * }; * const upsertResult = await index.upsert(upsertArgs); * console.log(upsertResult); // Outputs the result of the upsert operation * ``` * * @param {CommandArgs} args - The arguments for the upsert command. * @param {number|string} args.id - The unique identifier for the item being upserted. * @param {number[]} args.vector - The feature vector associated with the item. * @param {Record} [args.metadata] - Optional metadata to be associated with the item. * * @returns {string} A promise that resolves with the result of the upsert operation after the command is executed. * @see node_modules/@upstash/vector/docs/commands/upsert.mdx */ upsert = ( args: CommandArgs>, options?: { namespace?: string } ) => new UpsertCommand(args, options).exec(this.client); /** * Updates specific items in the index. * It's used for updating existing items in the index. * * @example * ```js * const updateArgs = { * id: '123', * vector: [0.42, 0.87, ...], * metadata: { property1: 'value1', property2: 'value2' } * }; * const updateResult = await index.update(updateArgs); * console.log(updateResult); // Outputs the result of the update operation * ``` * * @param {CommandArgs} args - The arguments for the update command. * @param {number|string} args.id - The unique identifier for the item being updated. * @param {number[]} [args.vector] - The feature vector associated with the item. * @param {Record} [args.metadata] - Optional metadata to be associated with the item. * @param {string} [options.namespace] - The namespace to update the item in. * * @returns {Promise<{updated: number}>} A promise that returns the number of items successfully updated. * @see node_modules/@upstash/vector/docs/commands/upsert.mdx */ update = ( args: CommandArgs>, options?: { namespace?: string } ) => new UpdateCommand(args, options).exec(this.client); /** * Fetches specific items from the index by their IDs or by an id prefix. * * Note: While using id prefix, the paginated `range` command is recommended to prevent timeouts on large result sets. * * @example * ```js * // Using ids * await index.fetch(["test-1", "test-2"], { includeMetadata: true }); * * // Using id prefix * await index.fetch({ prefix: "test-" }); * ``` * * @param {...CommandArgs} args - The arguments for the fetch command. * @param {FetchPayload} args[0] - An array of IDs or the id prefix of the items to be fetched. * @param {FetchCommandOptions} args[1] - Options for the fetch operation. * @param {boolean} [args[1].includeMetadata=false] - Optionally include metadata of the fetched items. * @param {boolean} [args[1].includeVectors=false] - Optionally include feature vectors of the fetched items. * @param {string} [args[1].namespace = ""] - The namespace of the index to fetch items from. * * @returns {Promise[]>} A promise that resolves with an array of fetched items or null if not found, after the command is executed. * @see node_modules/@upstash/vector/docs/commands/fetch.mdx */ fetch = (...args: CommandArgs) => new FetchCommand(args).exec(this.client); /** * It's used for wiping the index. * * By default, resets the default namespace: * * @example * ```js * await index.reset(); * console.log('Default namespace has been reset'); * ``` * * To reset a namespace, call reset like: * * @example * ```js * await index.reset({ namespace: "ns" }); * console.log('Namespace ns has been reset'); * ``` * * If you want to reset all namespaces, call reset like: * * @example * ```js * await index.reset({ all: true }); * console.log('All namespaces have been reset'); * ``` * * @returns {Promise} A promise that resolves with the result of the reset operation after the command is executed. * @see node_modules/@upstash/vector/docs/commands/reset.mdx */ reset = (options?: ResetCommandOptions) => new ResetCommand(options).exec(this.client); /** * Retrieves a paginated range of items from the index. Optionally filter results by an id prefix. * Returns items in batches with a cursor for pagination. * * @example * ```js * const args = { * limit: 10, * includeVectors: true, * includeMetadata: false * }; * await index.range(args); * * // Use the cursor to get the next page of results * const nextPage = await index.range({ * // You have to pass the arguments from the first call * ...args, * cursor: rangeResult.nextCursor, * }); * ``` * * @param {CommandArgs} args - The arguments for the range command. * @param {string} [args.prefix] - The prefix of the items to be fetched. * @param {number|string} args.cursor - The starting point (cursor) for the range query. * @param {number} args.limit - The maximum number of items to return in this range. * @param {boolean} [args.includeVectors=false] - Optionally include the feature vectors of the items in the response. * @param {boolean} [args.includeMetadata=false] - Optionally include additional metadata of the items in the response. * * @returns {Promise>} A promise that resolves with the response containing the next cursor and an array of vectors, after the command is executed. * @see node_modules/@upstash/vector/docs/commands/range.mdx */ range = ( args: CommandArgs, options?: { namespace?: string } ) => new RangeCommand(args, options).exec(this.client); /** * Retrieves info from the index. * * @example * ```js * const infoResults = await index.info(); * console.log(infoResults); // Outputs the result of the info operation * ``` * * @returns {Promise} A promise that resolves with the response containing the vectorCount, pendingVectorCount, indexSize, dimension count and similarity algorithm after the command is executed. * @see node_modules/@upstash/vector/docs/commands/info.mdx */ info = () => new InfoCommand().exec(this.client); /** * List all namespaces in the vector database. * * @example * ```js * const namespaces = await index.listNamespaces(); * console.log(namespaces); // Outputs the list of namespaces * ``` * * @returns {Promise} A promise that resolves with an array of namespaces after the command is executed. */ listNamespaces = () => new ListNamespacesCommand().exec(this.client); /** * Deletes a namespace from the vector database. * * @example * ```js * await index.deleteNamespace('namespace'); * console.log('Namespace has been deleted'); * ``` * * @param {string} namespace - The name of the namespace to be deleted. * @returns {Promise} A promise that resolves with the result of the delete operation after the command is executed. */ deleteNamespace = (namespace: string) => new DeleteNamespaceCommand(namespace).exec(this.client); }