Class: SearchIndex
Defined in: indexes/search-index.ts:153
SearchIndex class for managing Redis vector search indices.
This class provides methods to create, manage, and query Redis search indices. Users create their own Redis client and pass it to the constructor.
Example
import { createClient } from 'redis';
import { SearchIndex, IndexSchema, StorageType } from 'redis-vl';
const client = createClient();
await client.connect();
const schema = new IndexSchema({
index: { name: 'my-index', prefix: 'doc', storageType: StorageType.HASH }
});
schema.addField({ name: 'title', type: 'text' });
const searchIndex = new SearchIndex(schema, client);
await searchIndex.create();
Accessors
name
Get Signature
get name():
string
Defined in: indexes/search-index.ts:252
Get the index name from the schema.
Returns
string
Constructors
Constructor
new SearchIndex(
schema,client,validateOnLoad?):SearchIndex
Defined in: indexes/search-index.ts:184
Create a new SearchIndex instance.
Parameters
schema
The index schema
client
any
Redis client instance (created by user)
validateOnLoad?
boolean = false
Whether to validate documents on load (default: false)
Returns
SearchIndex
Throws
If schema is not a valid IndexSchema instance
Throws
If client is not provided
Methods
aggregate()
aggregate(
query):Promise<{results:Record<string,string|string[]>[];total:number; }>
Defined in: indexes/search-index.ts:1017
Execute an AggregationQuery (FT.AGGREGATE) against this index.
Returns the raw aggregate result: a total row count and a list of
rows, where each row is a Record<string, string | string[]> of field
name to value. GROUPBY/REDUCE/APPLY aliases appear as keys on each row.
Scalar reducers (COUNT, SUM, AVG, …) yield strings — numeric
casting is the caller's job. List reducers (TOLIST) yield
string[], preserving the array structure Redis returns on the wire.
Parameters
query
AggregationQuery
Returns
Promise<{ results: Record<string, string | string[]>[]; total: number; }>
Example
import { AggregationQuery, Reducers } from 'redis-vl';
const q = new AggregationQuery('@category:{electronics}')
.groupBy('@brand', Reducers.sum('price', 'revenue'))
.sortBy([{ field: 'revenue', direction: 'DESC' }])
.limit(0, 5);
const { total, results } = await index.aggregate(q);
for (const row of results) console.log(row.brand, row.revenue);
clear()
clear():
Promise<number>
Defined in: indexes/search-index.ts:684
Delete every document in the index, keeping the index itself in place.
Asks the index for its documents, deletes them in batches with UNLINK (see
dropKeys()), and repeats until the index is empty. Only documents the
index can see are deleted. A key under the prefix that the index does not
hold, such as a plain string or a document that failed to index, is left alone.
A document still being indexed may need a second clear().
Returns
Promise<number>
How many keys were deleted
Throws
If the index does not exist, or Redis fails to search or delete
Example
const deleted = await index.clear();
console.log(`Deleted ${deleted} documents`);
create()
create(
options?):Promise<any>
Defined in: indexes/search-index.ts:320
Create the index in Redis.
Parameters
options?
CreateIndexOptions = {}
Creation options
Returns
Promise<any>
The result from Redis FT.CREATE command
Throws
If no fields are defined for the index
Throws
If checking whether the index already exists fails
delete()
delete(
options?):Promise<any>
Defined in: indexes/search-index.ts:403
Delete the index from Redis.
Parameters
options?
DeleteIndexOptions = {}
Deletion options
Returns
Promise<any>
The result from Redis FT.DROPINDEX command
dropKeys()
dropKeys(
keys):Promise<number>
Defined in: indexes/search-index.ts:592
Delete documents from Redis by key. The index itself is left in place.
Takes full Redis keys, such as the ones load() returns or the id on
each search result. This differs from fetch() and fetchMany(), which
take ids without the prefix.
Uses UNLINK, so Redis frees the memory in the background and a large
delete does not pause the server. On a cluster the keys are unlinked one
at a time, because keys in different slots cannot share one command.
Parameters
keys
string | string[]
A full Redis key, or an array of them
Returns
Promise<number>
How many keys were deleted. Keys that do not exist are not counted.
Throws
If Redis fails to delete the keys
Example
const keys = await index.load([{ title: 'Doc 1' }, { title: 'Doc 2' }]);
const deleted = await index.dropKeys(keys[0]); // 1
exists()
exists():
Promise<boolean>
Defined in: indexes/search-index.ts:357
Check if the index exists in Redis.
Returns
Promise<boolean>
True if the index exists, false if Redis reports it as missing
Throws
If the check fails for any other reason, such as a connection
failure or insufficient permissions. The original error is available as cause.
expireKeys()
expireKeys(
keys,ttl):Promise<number>
Defined in: indexes/search-index.ts:641
Make documents expire: Redis deletes each key ttl seconds from now.
Takes full Redis keys, like dropKeys().
Parameters
keys
string | string[]
A full Redis key, or an array of them
ttl
number
Seconds until the keys expire. Must be a positive integer, because Redis deletes a key straight away when it is given a TTL of 0 or less.
Returns
Promise<number>
How many keys had the TTL set. Keys that do not exist are not counted.
Throws
If ttl is not a positive integer, or Redis fails to set the expiry
Example
const keys = await index.load([{ title: 'Doc 1' }, { title: 'Doc 2' }]);
const updated = await index.expireKeys(keys, 3600); // 2
fetch()
fetch(
key):Promise<Record<string,unknown> |null>
Defined in: indexes/search-index.ts:507
Fetch a single document by key.
Parameters
key
string
The document key (without prefix)
Returns
Promise<Record<string, unknown> | null>
The document or null if not found
Example
const doc = await index.fetch('123');
***
### fetchMany()
> **fetchMany**(`keys`, `batchSize?`): `Promise`\<(`Record`\<`string`, `unknown`\> \| `null`)[]\>
Defined in: [indexes/search-index.ts:535](https://github.com/redis-developer/redis-vl-typescript/blob/406fdecb3cfeba6ad4796acadc1934b2cda4e0af/src/indexes/search-index.ts#L535)
Fetch multiple documents by keys.
Uses pipelining for efficient batch retrieval.
#### Parameters
##### keys
`string`[]
Array of document keys (without prefix)
##### batchSize?
`number` = `200`
Number of commands per pipeline batch (default: 200). Must be greater than 0.
#### Returns
`Promise`\<(`Record`\<`string`, `unknown`\> \| `null`)[]\>
Array of documents (null for missing keys)
#### Throws
If batchSize is not greater than 0, or reading from Redis fails
#### Example
```typescript
const docs = await index.fetchMany(['123', '456', '789']);
***
### hybridSearch()
> **hybridSearch**\<`T`\>(`query`): `Promise`\<`HybridSearchResult`\<`T`\>\>
Defined in: [indexes/search-index.ts:953](https://github.com/redis-developer/redis-vl-typescript/blob/406fdecb3cfeba6ad4796acadc1934b2cda4e0af/src/indexes/search-index.ts#L953)
**`Experimental`**
Execute a hybrid (text + vector) search via Redis' built-in `FT.HYBRID`
command. Score fusion happens server-side — no client-side fusion.
Requires Redis Open Source 8.4.0+ on the server (FT.HYBRID was
introduced in that release).
Built on `client.ft.hybrid()` which `@redis/search` flags
experimental. The reply shape may shift between minor releases.
#### Type Parameters
##### T
`T` = `Record`\<`string`, `unknown`\>
#### Parameters
##### query
`HybridQuery`
#### Returns
`Promise`\<`HybridSearchResult`\<`T`\>\>
#### Example
```typescript
import { HybridQuery } from 'redis-vl';
const q = new HybridQuery({
text: 'machine learning',
textFieldName: 'description',
vector: embedding,
vectorField: 'embedding',
combine: { type: 'RRF' },
vsimFilter: '@brand:{nike}',
});
const { total, documents, executionTime } = await index.hybridSearch(q);
info()
info():
Promise<any>
Defined in: indexes/search-index.ts:420
Get information about the index.
Returns
Promise<any>
Index information from Redis
key()
key(
id):string
Defined in: indexes/search-index.ts:567
Build the full Redis key for a document ID, from the index prefix and key separator.
This is the key load() writes when you pass the same value with idField.
dropKeys() and expireKeys() take full keys like this one, while fetch()
takes the ID on its own.
Parameters
id
string
The document ID, without the prefix
Returns
string
The full Redis key
Example
const key = index.key('42'); // 'docs:42' for an index with the prefix 'docs'
await index.expireKeys(key, 3600);
load()
load(
data,options?):Promise<string[]>
Defined in: indexes/search-index.ts:478
Load documents into the index.
This method handles:
- Auto-generating keys using ULID if no idField or keys provided
- Extracting IDs from documents using idField
- Using explicit keys if provided
- Preprocessing documents before storage
- Setting TTL on documents
- Supporting both HASH and JSON storage types
- Batching operations using Redis pipelining for performance
- Optional schema validation
Parameters
data
Record<string, unknown>[]
Array of documents to load
options?
LoadOptions = {}
Load options
Returns
Promise<string[]>
Array of keys that were loaded
Throws
If keys length doesn't match data length
Throws
If idField is not found in a document
Throws
If validation fails when validateOnLoad is enabled
Throws
If a vector field holds a Buffer on a JSON index
Throws
If there's an error loading data to Redis
Example
// Auto-generate keys
const keys = await index.load([
{ title: 'Doc 1', score: 100 },
{ title: 'Doc 2', score: 200 }
]);
// Use idField
const keys = await index.load(
[{ id: 'user1', name: 'John' }],
{ idField: 'id' }
);
// Use explicit keys
const keys = await index.load(
[{ name: 'John' }],
{ keys: ['user:1'] }
);
// With preprocessing, TTL, and validation
const keys = await index.load(
[{ name: 'John' }],
{
ttl: 3600,
batchSize: 100,
validateOnLoad: true,
preprocess: (doc) => ({ ...doc, timestamp: Date.now() })
}
);
paginate()
paginate<
T>(query,pageSize?):AsyncGenerator<SearchResult<T>,void,undefined>
Defined in: indexes/search-index.ts:904
Run a query one page at a time, for result sets too large to fetch in one call.
Each loop gives you the next page, and the loop ends when no results are left.
The last page can have fewer than pageSize documents.
Things to know:
- It changes the
offsetandlimitof the query you pass in. Use a new query for any other search afterwards. - Sort the query on a field with unique values, such as
id, so pages don't repeat or skip documents. - A
VectorQueryreturns at mostnumResultsdocuments in total. RaisenumResultsto get more pages. - Redis stops paging past 1,000,000 results by default (the
search-max-search-resultssetting).
Type Parameters
T
T = Record<string, unknown>
Parameters
query
BaseQuery
The query to run. A CountQuery is rejected, as it never returns documents.
pageSize?
number = 30
Number of documents per page (default: 30). Must be a positive integer.
Returns
AsyncGenerator<SearchResult<T>, void, undefined>
Yields
One SearchResult per page, never with an empty documents array
Throws
If pageSize is not a positive integer, the query is a
CountQuery, or Redis fails to run the search. The error is thrown when the
loop starts, not when you call paginate().
Example
const query = new FilterQuery({ filter: Tag('brand').eq('nike') }).sortBy('id');
for await (const page of index.paginate(query, 100)) {
for (const doc of page.documents) {
console.log(doc.id, doc.value);
}
}
search()
search<
T>(query,options?):Promise<SearchResult<T>>
Defined in: indexes/search-index.ts:764
Execute a search query against the index
Type Parameters
T
T = Record<string, unknown>
Parameters
query
BaseQuery
Query object (VectorQuery, FilterQuery, etc.)
options?
QueryOptions
Optional query execution options. If both query-level
query.sortBy(...) and options.sortBy are supplied, options.sortBy
takes precedence.
Returns
Promise<SearchResult<T>>
Search results with documents and scores
Examples
import { VectorQuery } from 'redis-vl';
// Vector similarity search
const query = new VectorQuery({
vector: embedding,
vectorField: 'embedding',
topK: 10,
returnFields: ['title', 'content']
});
const results = await index.search(query);
console.log(`Found ${results.total} results`);
results.documents.forEach((doc) => {
console.log(`${doc.value.title} (score: ${doc.score})`);
});
// Vector search with metadata filtering
const query = new VectorQuery({
vector: embedding,
vectorField: 'embedding',
filter: '@category:{electronics}',
topK: 5
});
const results = await index.search(query);
fromExisting()
staticfromExisting(name,client,validateOnLoad?):Promise<SearchIndex>
Defined in: indexes/search-index.ts:225
Load an existing index from Redis by name.
This method fetches the index metadata using FT.INFO and reconstructs the IndexSchema from the stored information.
Parameters
name
string
Name of the existing index in Redis
client
any
Redis client instance
validateOnLoad?
boolean = false
Whether to validate documents on load (default: false)
Returns
Promise<SearchIndex>
SearchIndex instance with reconstructed schema
Throws
If index doesn't exist or cannot be loaded
Example
// Load an existing index
const index = await SearchIndex.fromExisting('my-index', client);
// Use the loaded index
const docs = await index.fetchMany(['key1', 'key2']);
listAll()
staticlistAll(client):Promise<any>
Defined in: indexes/search-index.ts:385
List the names of all search indices in the Redis database.
Parameters
client
any
Redis client instance
Returns
Promise<any>
Names of every search index in the database
Example
const names = await SearchIndex.listAll(client);
// Next, you can load one of the existing index:
const index = await SearchIndex.fromExisting(names[0], client);
Properties
schema
readonlyschema:IndexSchema
Defined in: indexes/search-index.ts:157
The index schema defining the structure and fields.