---
title: "Vector Search using a Static Index"
description: "Run vector similarity search against a pre-defined static index in RavenDB for optimized and repeatable semantic queries."
url: "https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-static-index"
version: "7.2"
language: "nodejs"
---

# Vector Search using a Static Index

> Client language: Node.js. Also available for [C#](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-static-index.md), [Python](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-static-index.python.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - This article explains how to perform a **vector search** using a **static index**.  
>   **Prior to this article**, it is recommended to get familiar with the [Vector search using a dynamic query](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md) article.
>
> - A static index allows you to define a **vector index-field**,  
>   enabling you to execute vector searches while leveraging the advantages of RavenDB's [indexes](https://docs.ravendb.net/7.2/indexes/what-are-indexes.nodejs.md).
>
> - The vector search feature is only supported by indexes that use the [Corax search engine](https://docs.ravendb.net/7.2/indexes/search-engine/corax.md).
>
> - Vector fields are **not** supported in Map-Reduce indexes.  
>   See [Combining vector search with Map-Reduce indexes](#combining-vector-search-with-map-reduce-indexes)
>   for a workaround that uses two separate indexes.
>
> - In this article:
>   - [Indexing a vector field - Overview](#indexing-a-vector-field---overview)
>     - [Defining a vector field in a static index](#defining-a-vector-field-in-a-static-index)
>     - [Parameters defined in the index definition](#parameters-defined-in-the-index-definition)
>     - [Behavior during indexing](#behavior-during-indexing)
>     - [Parameters used at query time](#parameters-used-at-query-time)
>     - [Behavior when documents are deleted](#vector-behavior-when-documents-are-deleted)
>   - [Indexing vector data - TEXT](#indexing-vector-data---text)
>     - [Indexing raw text](#indexing-raw-text)
>     - [Indexing pre-made text-embeddings generated by tasks](#indexing-pre-made-text-embeddings-generated-by-tasks)
>   - [Indexing vector data - NUMERICAL](#indexing-vector-data---numerical)
>     - [Indexing numerical data and querying using numeric input](#indexing-numerical-data-and-querying-using-numeric-input)
>     - [Indexing numerical data and querying using text input](#indexing-numerical-data-and-querying-using-text-input)
>   - [Indexing multiple field types](#indexing-multiple-field-types)
>   - [Querying the static index for similar documents](#querying-the-static-index-for-similar-documents)
>   - [Configure the vector field in the Studio](#configure-the-vector-field-in-the-studio)
>   - [Combining vector search with Map-Reduce indexes](#combining-vector-search-with-map-reduce-indexes)

## Indexing a vector field - Overview

> **Note**
>
> #### Defining a vector field in a static index
>
> To define a vector index-field in your static-index definition:
>
> - **From the Client API**:
>
>   **`loadVector()`**:  
>   When indexing **pre-made text-embeddings** generated by RavenDB's [Embeddings generation tasks](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md),  
>   use the `loadVector()` method in your index definition.  
>   An example is available in [Indexing pre-made text-embeddings](#indexing-pre-made-text-embeddings-generated-by-tasks).
>
>   **`createVector()`**:  
>   When indexing **your own data** (textual or numerical) that was not generated by these tasks,  
>   use the `createVector()` method in your index definition.  
>   An example is available in [Indexing raw text](#indexing-raw-text).
>
> - **From the Studio**:  
>   See [Configure the vector field in the Studio](#configure-the-vector-field-in-the-studio).
>
> The **source data types** that can be used for vector search are detailed in [Data types for vector search](https://docs.ravendb.net/7.2/ai-integration/vector-search/data-types-for-vector-search.nodejs.md).

> **Note**
>
> #### Parameters defined in the index definition
>
> The following params can be defined for the vector index-field in the index definition:
>
> **Source embedding type** -  
> RavenDB supports performing vector search on TEXTUAL values or NUMERICAL arrays.  
> This param specifies the embedding format of the source data to be indexed.  
> Options include `Text`, `Single`, `Int8`, or `Binary`.
>
> **Destination embedding type** -  
> Specify the quantization format for the embeddings that will be generated.  
> Read more about quantization in [Quantization options](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md#quantization-options).
>
> **Dimensions** -  
> For numerical input only - define the size of the array from your source document.
>
> - If this param is Not provided -  
>   the size will be determined by the first document indexed and will apply to all subsequent documents.
>
> - Ensure the dimensionality of these numerical arrays (i.e., their length) is consistent across all source documents for the indexed field.
>   An index error will occur if a source document has a different dimension for the indexed field.
>
> **Number of edges** -  
> Specify the number of edges that will be created for a vector during indexing.  
> If not specified, the default value is taken from the following configuration key: [Indexing.Corax.VectorSearch.DefaultNumberOfEdges](https://docs.ravendb.net/7.2/server/configuration/indexing-configuration.md#indexingcoraxvectorsearchdefaultnumberofedges).
>
> **Number of candidates for indexing time** -  
> The  number of candidates (potential neighboring vectors) that RavenDB evaluates during vector indexing.  
> If not specified, the default value is taken from the following configuration key: [Indexing.Corax.VectorSearch.DefaultNumberOfCandidatesForIndexing](https://docs.ravendb.net/7.2/server/configuration/indexing-configuration.md#indexingcoraxvectorsearchdefaultnumberofcandidatesforindexing).  
> (Note, this param differs from the number of candidates for query time).

> **Note**
>
> #### Behavior during indexing
>
> - **Raw textual input**:  
>   When indexing raw textual input from your documents, RavenDB generates embedding vectors using the built-in  
>   [bge-micro-v2](https://huggingface.co/TaylorAI/bge-micro-v2) sentence-transformer model, which are then indexed.
>
> - **Pre-made text-embeddings input**:  
>   When indexing embeddings that are pre-generated from your documents' raw text by RavenDB's  
>   [Embeddings generation tasks](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md),
>   RavenDB indexes them without additional transformation, unless quantization is applied.
>
> - **Raw numerical input**:  
>   When indexing pre-made numerical arrays that are already in vector format but were Not generated by these tasks,  
>   such as numerical arrays you created externally, RavenDB indexes them without additional transformation,  
>   unless quantization is applied.
>
> The embeddings are indexed on the server using the [HNSW algorithm](https://en.wikipedia.org/wiki/Hierarchical_navigable_small_world).  
> This algorithm organizes embeddings into a high-dimensional graph structure,  
> enabling efficient retrieval of Approximate Nearest Neighbors (ANN) during queries.
>
> Learn how parallel HNSW graph construction can affect result repeatability in
> [What affects vector search results](https://docs.ravendb.net/7.2/ai-integration/vector-search/what-affects-vector-search-results.md#the-approximate-nature-of-hnsw).

> **Note**
>
> #### Parameters used at query time
>
> **Minimum similarity** -  
> You can specify the minimum similarity to use when searching for related vectors. Can be a value between `0.0` and `1.0`.  
> A value closer to `1.0` requires higher similarity between vectors, while a value closer to `0.0` allows for less similarity.  
> If not specified, the default value is taken from the following configuration key: [Indexing.Corax.VectorSearch.DefaultMinimumSimilarity](https://docs.ravendb.net/7.2/server/configuration/indexing-configuration.md#indexingcoraxvectorsearchdefaultminimumsimilarity).
>
> **Number of candidates at query time** -  
> You can specify the maximum number of vectors that RavenDB will return from a graph search.  
> The number of the resulting documents that correspond to these vectors may be:
>
> - lower than the number of candidates - when multiple vectors originated from the same document.
>
> - higher than the number of candidates - when the same vector is shared between multiple documents.
>
> If not specified, the default value is taken from the following configuration key: [Indexing.Corax.VectorSearch.DefaultNumberOfCandidatesForQuerying](https://docs.ravendb.net/7.2/server/configuration/indexing-configuration.md#indexingcoraxvectorsearchdefaultnumberofcandidatesforquerying).
>
> **Search method** -  
> You can specify the search method at query time:
>
> - *Approximate Nearest-Neighbor search* (Default):  
>   Search for related vectors in an approximate manner, providing faster results.
>
> - *Exact search*:  
>   Perform a thorough scan of the vectors to find the actual closest vectors,  
>   offering better accuracy but at a higher computational cost.
>
> **To ensure consistent comparisons** -  
> the search term is transformed into an embedding vector using the same method as the vector index-field.
>
> **Search results** -  
> The server will search for the most similar vectors in the indexed vector space, taking into account all the parameters described.
> The documents that correspond to the resulting vectors are then returned to the client.
>
> By default, the resulting documents will be ordered by their score, with the highest scores (best matches) first.  
> You can modify this behavior using the [Indexing.Corax.VectorSearch.OrderByScoreAutomatically](https://docs.ravendb.net/7.2/server/configuration/indexing-configuration.md#indexingcoraxvectorsearchorderbyscoreautomatically) configuration key.
>
> In addition, you can apply any of the 'order by' methods to your query, as explained in [Sort query results](https://docs.ravendb.net/7.2/querying/sorting-query-results/sort-query-results.nodejs.md).  
> `orderByScore()` (`order by score()` in RQL) lists the most similar results (highest scores) first.  
> `orderByScoreDescending()` (`order by score() desc` in RQL) lists the least similar results (lowest scores) first.
>
> Changing the sort direction only reorders the matches selected by vector search using its minimum similarity and number of candidates.
> Learn more in [Order by score](https://docs.ravendb.net/7.2/querying/sorting-query-results/sort-query-results.nodejs.md#order-by-score).

> **Note**
>
> #### Vector behavior when documents are deleted
>
> - RavenDB's implementation of the HNSW graph is append-only.
>
> - When all documents associated with a specific vector are deleted, the vector itself is Not physically removed but is soft-deleted.
>   This means the vector is marked as deleted and will no longer appear in query results.  
>   Currently, compaction is not supported.

---

## Indexing vector data - TEXT

### Indexing raw text

The index in this example indexes data from raw text.  
For an index that indexes pre-made text-embeddings see [this example below](#indexing-pre-made-text-embeddings-generated-by-tasks).

The following index defines a **vector field** named `vectorfromText`.  
It indexes embeddings generated from the raw textual data in the `Name` field of all *Product* documents.

#### Index (C# LINQ)

```javascript
class Products_ByVector_Text extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();

        // Index-field 'vectorFromText' will hold the embeddings that will be generated
        // from the TEXT in the documents
        this.map = `docs.Products.Select(product => new {
            // Call 'createVector' to create a VECTOR FIELD.
            // Pass the document field containing the text
            // from which the embeddings will be generated.
            vectorFromText = this.CreateVector(product.Name)
        })`
    
        // You can customize the vector field
        this.vectorField("vectorFromText", {
    
            // Define the source embedding type
            sourceEmbeddingType: "Text",
    
            // Define the quantization for the destination embedding
            destinationEmbeddingType: "Single",
    
            // Optionally, set the number of edges 
            numberOfEdges: 20,
    
            // Optionally, set the number of candidates
            numberOfCandidatesForIndexing: 20
        })

        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

#### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();

indexDefinition.name = "Products/ByVector/Text";

indexDefinition.maps = new Set([`
    from product in docs.Products
    select new 
    {
        vectorFromText = CreateVector(product.Name)
    };`
]);

indexDefinition.fields = {
    "vectorFromText": {
        vector: {
            sourceEmbeddingType: "Text",
            destinationEmbeddingType: "Single",
            numberOfEdges: 20,
            numberOfCandidatesForIndexing: 20
        }
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a vector search using the index:  
Results will include *Product* documents where the `Name` field is similar to the search term `"italian food"`.

#### Query

```javascript
const similarProducts = await session.query({ index: Products_ByVector_Text })
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'withField'
             // Specify the index-field in which to search for similar values
            .withField("vectorFromText"),
        searchTerm => searchTerm
             // Call 'byText'   
             // Provide the term for the similarity comparison
            .byText("italian food"),
        {
            // Optionally, specify the minimum similarity value
            similarity: 0.82,
            // Optionally, specify the number candidates for querying
            numberOfCandidates: 20,
            // Optionally, specify whether the vector search should use the 'exact search method'
            isExact: true
        }
    )
     // Waiting for not-stale results is not mandatory
     // but will assure results are not stale
    .waitForNonStaleResults()
    .all();
```

#### RawQuery

```javascript
const similarProducts = await session.advanced
    .rawQuery(`
        from index "Products/ByVector/Text"
        // Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
        where exact(vector.search(vectorFromText, $searchTerm, 0.82, 20))`)
    .addParameter("searchTerm", "italian food")
    .waitForNonStaleResults()
    .all();
```

#### RQL

```sql
from index "Products/ByVector/Text"
// Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
where exact(vector.search(vectorFromText, $searchTerm, 0.82, 20))
{ "searchTerm" : "italian food" }
```

### Indexing pre-made text-embeddings generated by tasks

The index in this example defines a **vector field** named `vectorFromTextEmbeddings`.  
It indexes pre-made text-embeddings that were generated by this
[Embedding generation task](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/embeddings-generation-task.nodejs.md#configuring-an-embeddings-generation-task---from-the-studio).

#### Index (C# LINQ)

```javascript
class Categories_ByPreMadeTextEmbeddings extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();
    
        // Index-field 'vectorFromTextEmbeddings' will hold the text embeddings
        // that were pre-made by the Embeddings Generation Task
        this.map = `docs.Categories.Select(category => new {
            // Call 'LoadVector' to create a VECTOR FIELD. Pass:
            // * The document field name to be indexed (as a string) 
            // * The identifier of the task that generated the embeddings
            //   for the 'Name' field
            vectorFromTextEmbeddings = this.LoadVector("Name", "id-for-task-open-ai")
        })`

        // You can customize the vector field
        this.vectorField("vectorFromTextEmbeddings", {
            sourceEmbeddingType: "Single",
            destinationEmbeddingType: "Single"
        });
    
        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

#### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();

indexDefinition.name = "Categories/ByPreMadeTextEmbeddings";

indexDefinition.maps = new Set([`
    from category in docs.Categories
    select new 
    {
        vectorFromTextEmbeddings = LoadVector("Name", "id-for-task-open-ai")
    };`
]);

indexDefinition.fields = {
    "vectorFromTextEmbeddings": {
        vector: {
            sourceEmbeddingType: "Single",
            destinationEmbeddingType: "Single"
        }
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a vector search using the index:

- Results will include *Category* documents where the `Name` field is similar to the search term `"candy"`.

- The referenced [Embeddings generation task](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/embeddings-generation-task.nodejs.md)
  must exist and be **enabled** when querying the index by text.  
  The task generates the embedding for the query text at query time.

- If the referenced task is not found or is disabled, RavenDB throws an `InvalidQueryException`.
  To avoid this error, you can verify the task before issuing the query.
  See [Get embeddings generation task details](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md#get-embeddings-generation-task-details)
  to learn how to check which tasks are defined and what their identifiers are.

#### Query

```javascript
const similarProducts = await session.query({ index: Categories_ByPreMadeTextEmbeddings })
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'withField'
             // Specify the index-field in which to search for similar values
            .withField("vectorFromTextEmbeddings"),
        searchTerm => searchTerm
             // Call 'byText'
             // Provide the search term for the similarity comparison
            .byText("candy"),
        {
            // Optionally, specify the minimum similarity value
            similarity: 0.75,
            // Optionally, specify the number of candidates for querying
            numberOfCandidates: 30,
            // Optionally, specify whether the vector search should use the 'exact search method'
            isExact: true
        }
    )
    .waitForNonStaleResults()
    .all();
```

#### RawQuery

```javascript
const similarProducts = await session.advanced
    .rawQuery(`
        from index "Categories/ByPreMadeTextEmbeddings"
        // Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
        where exact(vector.search(vectorFromTextEmbeddings, $searchTerm, 0.75, 20))`)
    .addParameter("searchTerm", "candy")
    .waitForNonStaleResults()
    .all();
```

#### RQL

```sql
from index "Categories/ByPreMadeTextEmbeddings"
// Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
where exact(vector.search(vectorFromTextEmbeddings, $p0, 0.75, 20))
{ "p0": "candy" }
```

---

## Indexing vector data - NUMERICAL

> **Note**
>
> - RavenDB’s [Embedding generation tasks](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md) are typically used to generate vector embeddings from TEXTUAL data stored in your documents.
>   These embeddings are then stored in [dedicated collections](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/embedding-collections.md).
>
> - However, you are not limited to using these built-in tasks.
>   You can generate your own NUMERICAL embeddings - from any source (e.g., text, image, audio, etc.) - using a suitable multimodal model, and store them:
>   - as numerical arrays in your documents’ properties, or
>   - as attachments associated with your documents.
>
> - This numerical data can be indexed in a vector field in a static-index.  
>   Once indexed, you can query the vector field using either of the following:
>
>   - **Query using a numerical embedding (direct vector)**:  
>     You provide a numerical array as the search term, and RavenDB compares it directly against the indexed embeddings.
>     See [Indexing numerical data and querying using numeric input](#indexing-numerical-data-and-querying-using-numeric-input).
>
>   - **Query using a text input**:  
>     You provide a text string as the search term and specify an existing [Embedding generation task](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md) that will convert this text into a vector embedding.
>     This will work only if:
>
>     - the vector field you're querying contains numerical embeddings that were created using the **same model** as the one configured in the specified task, and
>     - that task exists in your database (i.e., its identifier is still available).
>
>     In this case, RavenDB uses the task to transform the search term into an embedding, then compares it to the vector data that you had previously indexed yourself.
>     To improve performance, the generated embedding is cached, so repeated queries with the same search term don’t require re-computation.
>
>     This hybrid approach allows you to index custom embeddings (e.g., externally generated image vectors)
>     while still benefiting from RavenDB’s ability to perform semantic text search, as long as the same model was used for both.  
>     See [Indexing numerical data and querying using text input](#indexing-numerical-data-and-querying-using-text-input).
>
> - > **Info**
>   >
>   > The examples in this section use the [sample data provided in the dynamic query article](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md#sample-data).

### Indexing numerical data and querying using numeric input

The following index defines a vector field named `vectorFromSingle`.  
It indexes embeddings generated from the numerical data in the `tagsEmbeddedAsSingle` field of all *Movie* documents.  
The raw numerical data in the source documents is in **32-bit floating-point format**.

#### Index (C# LINQ)

```javascript
class Movies_ByVector_Single extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();
    
        // Index-field 'vectorFromSingle' will hold the embeddings that will be generated
        // from the NUMERICAL content in the documents.
        this.map = `docs.Movies.Select(movie => new {
            // Call 'CreateVector' to create a VECTOR FIELD.
            // Pass the document field containing the array (32-bit floating-point values)
            // from which the embeddings will be generated.
            vectorFromSingle = this.CreateVector(movie.tagsEmbeddedAsSingle)
        })`;

        // You can customize the vector field
        this.vectorField("vectorFromSingle", {
    
            // Define the source embedding type
            sourceEmbeddingType: "Single", 
    
            // Define the quantization for the destination embedding
            destinationEmbeddingType: "Single",
    
            // It is recommended to configure the number of dimensions
            // which is the size of the arrays that will be indexed.
            dimensions: 2,
    
            // Optionally, set the number of edges and candidates
            numberOfEdges: 20,
            numberOfCandidatesForIndexing: 20,
        });
    
        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

#### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();

indexDefinition.name = "Movies/ByVector/Single";

indexDefinition.maps = new Set([`
    from movie in docs.Movies
    select new 
    {
        vectorFromSingle = CreateVector(movie.tagsEmbeddedAsSingle)
    };
`]);
    
indexDefinition.searchEngineType = "Corax";

indexDefinition.fields = {
    "vectorFromSingle": {
        vector: {
            sourceEmbeddingType: "Single", 
            destinationEmbeddingType: "Single",
            dimensions: 2,
            numberOfEdges: 20,
            numberOfCandidatesForIndexing: 20,
        }
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a vector search using the index:  
(Provide a vector as the search term to the `byEmbedding` method)

#### Query

```javascript
const similarMovies = await session.query({ index: Movies_ByVector_Single })
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'xithField'
             // Specify the index-field in which to search for similar values
            .withField("vectorFromSingle"),
        queryVector => queryVector
             // Call 'byEmbedding'   
             // Provide the vector for the similarity comparison
            .byEmbedding(RavenVector([6.599999904632568, 7.699999809265137])
    )
    .waitForNonStaleResults()
    .all();
```

#### RawQuery

```javascript
const similarMovies = await session.advanced
    .rawQuery(`
        from index "Movies/ByVector/Single"
        where vector.search(vectorFromSingle, $queryVector)`)
    .addParameter("queryVector", RavenVector([6.599999904632568, 7.699999809265137])
    .waitForNonStaleResults()
    .all();
```

#### RQL

```sql
from index "Movies/ByVector/Single"
where vector.search(vectorFromSingle, $queryVector)
{ "queryVector" : { "@vector" : [6.599999904632568, 7.699999809265137] }}
```

---

The following index defines a vector field named `vectorFromInt8Arrays`.  
It indexes embeddings generated from the numerical arrays in the `tagsEmbeddedAsInt8` field of all *Movie* documents.  
The raw numerical data in the source documents is in **Int8 (8-bit integers) format**.

#### Index (C# LINQ)

```javascript
class Movies_ByVector_Int8 extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();
    
        // Index-field 'vectorFromInt8Arrays' will hold the embeddings that will be generated
        // from the NUMERICAL content in the documents.
        this.map = `docs.Movies.Select(movie => new {
            // Call 'CreateVector' to create a VECTOR FIELD.
            // Pass the document field containing the arrays (8-bit integer values)
            // from which the embeddings will be generated.
            vectorFromInt8Arrays = this.CreateVector(movie.tagsEmbeddedAsInt8)
        })`

        // You can customize the vector field
        this.vectorField("vectorFromInt8Arrays", {    
    
            // Define the source embedding type
            sourceEmbeddingType: "Int8",
    
            // Define the quantization for the destination embedding
            destinationEmbeddingType: "Int8",
    
            // It is recommended to configure the number of dimensions
            // which is the size of the arrays that will be indexed.
            dimensions: 2,
    
            // Optionally, set the number of edges and candidates
            numberOfCandidatesForIndexing: 20,
            numberOfEdges: 20,
        })
    
        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

#### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();
    
indexDefinition.name = "Movies/ByVector/Int8";
    
indexDefinition.searchEngineType = Movies_ByVector_Int8.searchEngineType;

indexDefinition.maps = new Set([`
    from movie in docs.Movies
    select new 
    {
        vectorFromInt8Arrays = CreateVector(movie.TagsEmbeddedAsInt8)
    }
`]);

indexDefinition.fields = {
    "vectorFromInt8Arrays": {
        vector: {
            sourceEmbeddingType: "Int8",
            destinationEmbeddingType: "Int8",
            dimensions: 2,
            numberOfCandidatesForIndexing: 20,
            numberOfEdges: 20,
        }
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a vector search using the index:  
(Provide a vector as the search term to the `ByEmbedding` method)

#### Query

```javascript
const similarMovies = await session.query({ index: Movies_ByVector_Int8 })
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'withField'
             // Specify the index-field in which to search for similar values
            .withField("vectorFromInt8Arrays"),
        queryVector => queryVector
             // Call 'byEmbedding'   
             // Provide the vector for the similarity comparison
             // (Note: provide a single vector)
            .byEmbedding(
                 // The provided vector MUST be in the same format as was stored in your document
                 // Call 'VectorQuantizer.toInt8' to transform the rawData to the Int8 format 
                 VectorQuantizer.toInt8([0.1, 0.2]))
    )
    .waitForNonStaleResults()
    .all();
```

#### RawQuery

```javascript
const similarProducts = await session.advanced
    .rawQuery(`
        from index "Movies/ByVector/Int8"
        where vector.search(vectorFromInt8Arrays, $queryVector)`)
    .addParameter("$queryVector", VectorQuantizer.toInt8([0.1, 0.2]))
    .waitForNonStaleResults()
    .all();
```

#### RQL

```sql
from index "Movies/ByVector/Int8"
where vector.search(VectorFromInt8Arrays, $queryVector)
{ "queryVector" : [64, 127, -51, -52, 76, 62] }
```

### Indexing numerical data and querying using text input

The following index defines a vector field named `vectorFromPhoto`.  
It indexes embeddings generated from the numerical data in the `moviePhotoEmbedding` field of all *Movie* documents.

#### Index (C# LINQ)

```javascript
class Movies_ByVectorFromPhoto extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();

        // Index-field 'vectorFromPhoto' will hold the embeddings that will be generated
        // from the NUMERICAL content in the documents.
        this.map = `docs.Movies.Select(movie => new {
            // Call 'CreateVector' to create a VECTOR FIELD.
            // Pass the document field containing the array 
            // from which the embeddings will be generated.
            vectorFromPhoto = this.CreateVector(movie.moviePhotoEmbedding)
        })`

        this.vectorField("vectorFromPhoto", {
            sourceEmbeddingType: "Single", 
            destinationEmbeddingType: "Single",
            // Dimensions should match the embedding size, 6 is only for this simple example...
            dimensions: 6
        })

        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

#### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();

indexDefinition.name = "Movies/ByVectorFromPhoto";

indexDefinition.maps = [`
    from movie in docs.Movies
    select new
    {
        vectorFromPhoto = CreateVector(movie.MoviePhotoEmbedding)
    }
`];

indexDefinition.fields = {
    "vectorFromPhoto": {
        vector: {
            sourceEmbeddingType: "Single",
            destinationEmbeddingType: "Single",
            dimensions: 6 // using 6 only for this simple example
        }
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a vector search using the index:

- Pass a textual search term to the `byText` method,  
  along with the ID of the embedding generation task that will convert the text into an embedding.

- The query is only meaningful if the vector field being searched contains numerical embeddings  
  generated using the same model as the one configured in the specified task.

- The specified task ID must reference an existing and **enabled** [Embeddings generation task](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/embeddings-generation-task.nodejs.md).  
  If the task is not found or is disabled, RavenDB throws an `InvalidQueryException`.
  To avoid this error, you can verify the task before issuing the query.  
  See [Get embeddings generation task details](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/overview.nodejs.md#get-embeddings-generation-task-details)
  to learn how to check which tasks are defined and what their identifiers are.

#### Query

```javascript
// Query for movies with images related to 'NASA'
const similarMovies = await session.query({ index: Movies_ByVectorFromPhoto} )
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'withField'
             // Specify the index field that stores the image embeddings
            .withField("vectorFromPhoto"),
        queryVector => queryVector
             // Call 'byText'
             // Provide a textual description to be embedded by the same multimodal model
             // used for the moviePhotoEmbedding field
            .byText("NASA", "id-of-embedding-generation-task"),
        {
            // As with any other vector search query, you can optionally specify
            // 'similarity', 'numberOfCandidates', and 'isExact'
            similarity: 0.82
        }
    )
    .waitForNonStaleResults()
    .all();
```

#### RawQuery

```javascript
const similarMovies = await session.advanced
    .rawQuery(`
        from index "Movies/ByVectorFromPhoto"
        where vector.search(vectorFromPhoto, 
            embedding.text($searchTerm, ai.task($embeddingTaskId)), 0.85, null)`)
    .addParameter("searchTerm", "NASA")
    .addParameter("$embeddingTaskId", "id-of-embedding-generation-task")
    .waitForNonStaleResults()
    .all();
```

#### RQL

```sql
from index "Movies/ByVectorFromPhoto"
where vector.search(vectorFromPhoto, 
    embedding.text($searchTerm, ai.task($embeddingTaskId)), 0.85, null)
{ "searchTerm" : "NASA", "embeddingTaskId" : "id-of-embedding-generation-task" }
```

---

## Indexing multiple field types

An index can define multiple types of index-fields. In this example, the index includes:  
A *'regular'* field, a *'vector'* field, and a field configured for [full-text search](https://docs.ravendb.net/7.2/indexes/querying/searching.nodejs.md).  
This allows you to query across all fields using various predicates.

### Index (C# LINQ)

```javascript
class Products_ByMultipleFields extends AbstractCsharpIndexCreationTask {
    constructor() {
        super();

        this.map = `docs.Products.Select(product => new {
            // An index-field for 'regular' data
            pricePerUnit = product.PricePerUnit,
    
            // An index-field for 'full-text' search
            name = product.Name,
    
            // An index-field for 'vector' search
            vectorFromText = this.CreateVector(product.Name)
        })`

        // Configure the index-field 'name' for FTS:
        this.index("name", "Search")
    
        // Note:
        // Default values will be used for the VECTOR FIELD if not customized here.

        // The index MUST use the Corax search engine 
        this.searchEngineType = "Corax";
    }
}
```

### IndexDefinition

```javascript
const indexDefinition = new IndexDefinition();

indexDefinition.name = "Products/ByMultipleFields";

indexDefinition.maps = [`from product in docs.Products
        select new 
        {
            pricePerUnit = product.PricePerUnit,
            name = product.Name,
            vectorFromText  = CreateVector(product.Name)
        }`];

indexDefinition.fields = {
    "name": {
        indexing: "Search"
    }
}

indexDefinition.configuration = {
    "Indexing.Static.SearchEngineType": "Corax"
}

await documentStore.maintenance.send(new PutIndexesOperation(indexDefinition));
```

Execute a query that combines predicates across all index-field types:

### DocumentQuery

```javascript
const results = await session.query({ index: Products_ByMultipleFields })
     // Perform a regular search
    .whereGreaterThan("pricePerUnit", 200)
    .orElse()
     // Perform a full-text search
    .search("name", "Alice")
    .orElse()
     // Perform a vector search
    .vectorSearch(
        field => field.withField("vectorFromText"),
        searchTerm => searchTerm.byText("italian food"),
        {similarity: 0.8}
    )
    .waitForNonStaleResults()
    .all();
```

### RawQuery

```javascript
const results = await session.advanced.rawQuery(`
    from index "Products/ByMultipleFields" 
    where pricePerUnit > $minPrice 
    or search(name, $searchTerm1)  
    or vector.search(vectorFromText, $searchTerm2, 0.8)`)
        .addParameter("minPrice", 200)
        .addParameter("searchTerm1", "Alice")
        .addParameter("searchTerm2", "italian food")
        .waitForNonStaleResults()
        .all();
```

### RQL

```sql
from index "Products/ByMultipleFields"
where pricePerUnit > $minPrice
or search(name, $searchTerm1)
or vector.search(vectorFromText, $searchTerm2, 0.8)
{ "minPrice" : 200, "searchTerm1" : "Alice", "searchTerm2": "italian food" }
```

> **Note**
>
> - **Multiple vector searches**:  
>   You can combine multiple vector search statements in a single query using logical operators.  
>   An example is available in:
>   [Combining multiple vector searches in the same query](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md#combining-multiple-vector-searches-in-the-same-query).
>
> - **Vector search with filtering**:  
>   You can also combine vector search with filtering conditions on regular (non-vector) fields in the same query.  
>   Learn more in [Querying vector fields and regular data in the same query](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md#querying-vector-fields-and-regular-data-in-the-same-query).

---

## Querying the static index for similar documents

- Similar to [querying for similar documents using a dynamic query](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-dynamic-query.nodejs.md#dynamic-vector-search---querying-for-similar-documents),  
  you can **query a static-index for similar documents** by specifying a document ID in the vector search.

- The following example queries the static-index defined in [this example](#indexing-vector-data---text) above.
  The document for which we want to find similar documents is specified by the document ID passed to the `ForDocument` method.

- RavenDB retrieves the embedding that was indexed for the queried field in the specified document and uses it as the query vector for the similarity comparison.

- The results will include documents whose indexed embeddings are most similar to the one stored in the referenced document’s index-entry.

### Query

```javascript
const similarProducts = await session.query({ index: Products_ByVector_Text })
     // Perform a vector search
     // Call the 'vectorSearch' method
    .vectorSearch(
        field => field
             // Call 'withField'
             // Specify the index-field in which to search for similar values
            .withField("vectorFromText"),
        embedding => embedding
             // Call 'forDocument'
             // Provide the document ID for which you want to find similar documents.
             // The embedding stored in the index for the specified document
             // will be used as the "query vector".
            .forDocument("Products/7-A"),{
                similarity: 0.82
        }
    )
    .waitForNonStaleResults()
    .all();
```

### RawQuery

```javascript
const similarProducts = await session.advanced.rawQuery(`
    from index 'Products/ByVector/Text'
    // Pass a document ID to the 'forDoc' method to find similar documents
    where vector.search(vectorFromText, embedding.forDoc($documentID), 0.82)`)
        .addParameter("$documentID", "Products/7-A")
        .waitForNonStaleResults()
        .all();
```

### RQL

```sql
from index "Products/ByVector/Text"
// Pass a document ID to the 'forDoc' method to find similar documents
where vector.search(vectorFromText, embedding.forDoc($documentID), 0.82)
{"documentID" : "Products/7-A"}
```

Running the above example on RavenDB’s sample data returns the following documents that have similar content in their *Name* field:
(Note: the results include the referenced document itself, *Products/7-A*)

```javascript
// ID: products/7-A  ... Name: "Uncle Bob's Organic Dried Pears"
// ID: products/51-A ... Name: "Manjimup Dried Apples"
// ID: products/6-A  ... Name: "Grandma's Boysenberry Spread"
```

---

## Configure the vector field in the Studio

![Add vector field](https://docs.ravendb.net/assets/images/add-vector-field-1-6d53d2979ec7c185a7b1fd37563755ed.png)

![Customize vector field](https://docs.ravendb.net/assets/images/add-vector-field-2-4160b2d3a3f2fcc71419edcec3285375.png)

1. **Vector field name**  
   Enter the name of the vector field to customize.
2. **Configure Vector Field**  
   Click this button to customize the field.
3. **Dimensions**  
   For numerical input only - define the size of the array from your source document.
4. **Edges**  
   The number of edges that will be created for a vector during indexing.
5. **Source embedding type**  
   The format of the source embeddings (Text, Single, Int8, or Binary).
6. **Candidates for indexing**  
   The number of candidates (potential neighboring vectors) that RavenDB evaluates during vector indexing.
7. **Destination embedding type**  
   The quantization format for the embeddings that will be generated (Text, Single, Int8, or Binary).

---

## Combining vector search with Map-Reduce indexes

Vectorized fields are currently **not** supported by Map-Reduce indexes.

If you need to perform vector searches on aggregated data, you can use a **two-index workaround**.  
This involves generating artificial documents with a Map-Reduce index, and then applying a standard Map index to those documents to perform the vector search.

### 1. Create a Map-Reduce index (without vector fields)

This Map-Reduce index acts solely as a document generator.  
Enable the [Output reduce results to collection](https://docs.ravendb.net/7.2/studio/database/indexes/create-map-reduce-index.md#saving-map-reduce-results-in-a-collection-artificial-documents) feature
so the reduce output is saved as artificial documents in your database.

- **Do not include pre-made embeddings in the Map phase:**  
  Vector embeddings are massive arrays of data.
  Because of how RavenDB processes and groups data during the reduction phase, carrying these large arrays through the Map-Reduce pipeline will severely inflate your index storage size.

- **Propagate lightweight data instead:**  
  Include only the minimal data needed to create the vectorized field later  
  (for example, the document IDs required for `LoadVector`).

- **Disable field indexing:**  
  Since this Map-Reduce index acts only as a document generator and will not be queried directly,  
  set the indexing behavior for all fields to `No` (or **No** in the Studio field options).  
  This prevents unnecessary background work, saving significant disk space and CPU resources.  
  See [Disabling indexing for index-field](https://docs.ravendb.net/7.2/indexes/using-analyzers.nodejs.md#disabling-indexing-for-index-field).

### 2. Create a Map index on the artificial collection

Create a standard Map index on the artificial collection produced by the first index.  
Because these are now regular documents, you can freely define vector fields and use all vector search APIs on this index to fulfill your query needs.
