Skip to main content

Class: SearchIndex

Defined in: indexes/search-index.ts:137

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:236

Get the index name from the schema.

Returns​

string

Constructors​

Constructor​

new SearchIndex(schema, client, validateOnLoad?): SearchIndex

Defined in: indexes/search-index.ts:168

Create a new SearchIndex instance.

Parameters​

schema​

IndexSchema

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:790

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);

create()​

create(options?): Promise<any>

Defined in: indexes/search-index.ts:303

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


delete()​

delete(options?): Promise<any>

Defined in: indexes/search-index.ts:378

Delete the index from Redis.

Parameters​

options?​

DeleteIndexOptions = {}

Deletion options

Returns​

Promise<any>

The result from Redis FT.DROPINDEX command


exists()​

exists(): Promise<boolean>

Defined in: indexes/search-index.ts:336

Check if the index exists in Redis.

Returns​

Promise<boolean>

True if the index exists, false otherwise


fetch()​

fetch(key): Promise<Record<string, unknown> | null>

Defined in: indexes/search-index.ts:481

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:522](https://github.com/redis-developer/redis-vl-typescript/blob/adeb1305d48b93b3dcc7dbc28021a3fba59613df/src/indexes/search-index.ts#L522)

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)

#### Returns

`Promise`\<(`Record`\<`string`, `unknown`\> \| `null`)[]\>

Array of documents (null for missing keys)

#### Example

```typescript
const docs = await index.fetchMany(['123', '456', '789']);

***

### hybridSearch()

> **hybridSearch**\<`T`\>(`query`): `Promise`\<`HybridSearchResult`\<`T`\>\>

Defined in: [indexes/search-index.ts:726](https://github.com/redis-developer/redis-vl-typescript/blob/adeb1305d48b93b3dcc7dbc28021a3fba59613df/src/indexes/search-index.ts#L726)

**`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:395

Get information about the index.

Returns​

Promise<any>

Index information from Redis


load()​

load(data, options?): Promise<string[]>

Defined in: indexes/search-index.ts:452

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 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() })
}
);

search<T>(query, options?): Promise<SearchResult<T>>

Defined in: indexes/search-index.ts:594

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()​

static fromExisting(name, client, validateOnLoad?): Promise<SearchIndex>

Defined in: indexes/search-index.ts:209

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()​

static listAll(client): Promise<any>

Defined in: indexes/search-index.ts:360

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​

readonly schema: IndexSchema

Defined in: indexes/search-index.ts:141

The index schema defining the structure and fields.