---
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: "python"
---

# Vector Search using a Static Index

> Client language: Python. Also available for [C#](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-static-index.md), [Node.js](https://docs.ravendb.net/7.2/ai-integration/vector-search/vector-search-using-static-index.nodejs.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.python.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.python.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 Studio](#configure-the-vector-field-in-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.python.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 Studio**:  
>   See [Configure the vector field in Studio](#configure-the-vector-field-in-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.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.python.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.python.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.python.md).  
> `order_by_score()` (`order by score()` in RQL) lists the most similar results (highest scores) first.  
> `order_by_score_descending()` (`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.python.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 `vector_from_text`.  
It indexes embeddings generated from the raw textual data in the `Name` field of all *Product* documents.

#### AbstractIndexCreationTask

```python
class Products_ByVector_Text(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()
        # Call 'CreateVector' to create a VECTOR FIELD
        # Pass the document field containing the text from which the embeddings will be generated
        self.map = "from p in docs.Products select new { vector_from_text = CreateVector(p.Name) }"

        # Customize the vector field using _vector
        self._vector(
            "vector_from_text",
            VectorOptions(
                VectorEmbeddingType.TEXT,
                VectorEmbeddingType.SINGLE,
                number_of_edges=20,
                number_of_candidates_for_indexing=20,
            ),
        )

        self.search_engine_type = SearchEngineType.CORAX
```

#### JS\_index

```python
class Products_ByVector_Text_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            "map('Products', function (p) { return { vector_from_text: createVector(p.Name) }; })"
        }

        self.fields = {
            "vector_from_text" : IndexFieldOptions(
                vector=VectorOptions(VectorEmbeddingType.TEXT, VectorEmbeddingType.SINGLE, number_of_edges=20, number_of_candidates_for_indexing=20)
            )
        }

        self.search_engine_type = SearchEngineType.CORAX
```

#### index\_definition

```python
index_definition = IndexDefinition(
    name="Products/ByVector/Text",
    maps={"from p in docs.Products select new { vector_from_text = CreateVector(p.Name) }"},
    fields={
        "vector_from_text": IndexFieldOptions(
            vector=VectorOptions(
                source_embedding_type=VectorEmbeddingType.TEXT,
                destination_embedding_type=VectorEmbeddingType.SINGLE,
                number_of_edges=20,
                number_of_candidates_for_indexing=20
            )
        )
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"}
)

store.maintenance.send(PutIndexesOperation(index_definition))
```

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

#### raw\_query

```python
similar_products = list(
        session.advanced.raw_query(
            (
                "from index 'Products/ByVector/Text' "
                # Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
                "where exact(vector.search(vector_from_text, $searchTerm, 0.82, 20))"
            ),
            object_type=Product,
        )
        .add_parameter("searchTerm", "italian food")
        .wait_for_non_stale_results()
    )
```

#### RQL

```sql
from index "Products/ByVector/Text"
// Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
where exact(vector.search(vector_from_text, $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 `vector_from_text_embeddings`.  
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.python.md#configuring-an-embeddings-generation-task---from-the-studio).

#### AbstractIndexCreationTask

```python
class Categories_ByPreMadeTextEmbeddings(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()

        # 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
        self.map = 'from c in docs.Categories select new { vector_from_text_embeddings = LoadVector("Name", "id-for-task-open-ai") }'

        self._vector(
            "vector_from_text_embeddings",
            VectorOptions(
                # Vector options can be customized in the same way as the above index example
            ),
        )

        # The index MUST use the Corax search engine
        self.search_engine_type = SearchEngineType.CORAX
```

#### JS\_index

```python
class Categories_ByPreMadeTextEmbeddings_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            'map("Categories", function (c) { return { vector_from_text_embeddings: loadVector("Name", "id-for-task-open-ai") }; })'
        }

        self.fields = {
            "vector_from_text_embeddings": IndexFieldOptions(
                vector=VectorOptions(
                    # Vector options can be customized in the same way as the above index example
                )
            )
        }

        self.search_engine_type = SearchEngineType.CORAX
```

#### IndexDefinition

```python
index_definition = IndexDefinition(
    name="Categories/ByPreMadeTextEmbeddings",
    maps={
        'from c in docs.Categories select new { vector_from_text_embeddings = LoadVector("Name", "id-for-task-open-ai") }'
    },
    fields={
        "vector_from_text_embeddings": IndexFieldOptions(
            vector=VectorOptions(
                # Vector options can be customized in the same way as the above index example
            )
        )
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"},
)
```

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.python.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.python.md#get-embeddings-generation-task-details)
  to learn how to check which tasks are defined and what their identifiers are.

#### raw\_query

```python
similar_categories = list(
        session.advanced.raw_query(
            (
                "from index 'Categories/ByPreMadeTextEmbeddings'"
                # Optionally, wrap the 'vector.search' query with 'exact' to perform an exact search
                "where exact(vector.search(vector_from_text_embeddings, $searchTerm, 0.75, 20))"
            ),
            object_type=Category,
        )
        .add_parameter("searchTerm", "candy")
        .wait_for_non_stale_results()
    )
```

#### RQL

```sql
from index "Categories/ByPreMadeTextEmbeddings"
// Optionally, wrap the 'vector.search' query with 'exact()' to perform an exact search
where exact(vector.search(vector_from_text_embeddings, $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.python.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.python.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.python.md#sample-data).

### Indexing numerical data and querying using numeric input

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

#### AbstractIndexCreationTask

```python
class Movies_ByVector_Single(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()
        # Call 'CreateVector' to create a VECTOR FIELD.
        # Pass the document field containing the array of floats (32-bit floating-point values)
        # from which the embeddings will be generated
        self.map = "from m in docs.Movies select new { vector_from_single = CreateVector(m.tags_embedded_as_single) }"
    
        # Customize the vector field using _vector
        self._vector("vector_from_single", VectorOptions(
            # Define the source embedding type
            source_embedding_type=VectorEmbeddingType.SINGLE,
            
            # Define the quantization for the destination embedding 
            destination_embedding_type=VectorEmbeddingType.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
            number_of_edges=20,
            number_of_candidates_for_indexing=20,
        ))
        
        # The index MUST use the Corax search engine
        self.search_engine_type = SearchEngineType.CORAX
```

#### JS\_index

```python
class Movies_ByVector_Single_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            "map('Movies', function (m) { return { vector_from_single: createVector(m.tags_embedded_as_single) }; })"
        }
        self.fields = {
            "vector_from_single": IndexFieldOptions(
                vector=VectorOptions(
                    source_embedding_type=VectorEmbeddingType.SINGLE,
                    destination_embedding_type=VectorEmbeddingType.SINGLE,
                    dimensions=2,
                    number_of_edges=20,
                    number_of_candidates_for_indexing=20,
                )
            )
        }

        self.search_engine_type = SearchEngineType.CORAX
```

#### IndexDefinition

```python
index_definition = IndexDefinition(
    name="Movies/ByVector/Single",
    maps={"from m in docs.Movies select new { vector_from_single = CreateVector(m.tags_embedded_as_single) }"},
    fields={
        "vector_from_single": IndexFieldOptions(
            vector=VectorOptions(
                source_embedding_type=VectorEmbeddingType.SINGLE,
                destination_embedding_type=VectorEmbeddingType.SINGLE,
                dimensions=2,
                number_of_edges=20,
                number_of_candidates_for_indexing=20,
            )
        )
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"},
)

store.maintenance.send(PutIndexesOperation(index_definition))
```

Execute a vector search using the index:  
(Provide a vector as the `vector.search` search term)

#### raw\_query

```python
similar_movies = list(
        session.advanced.raw_query(
            "from index 'Movies/ByVector/Single' where vector.search(vector_from_single, $queryVector)",
            object_type=Movie,
        )
        .add_parameter("queryVector", [6.599999904632568, 7.699999809265137])
        .wait_for_non_stale_results()
    )
```

#### RQL

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

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

#### AbstractIndexCreationTask

```python
class Movies_ByVector_Int8(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()
        # Call 'CreateVector' to create a VECTOR FIELD.
        # Pass the document field containing the arrays (8-bit signed values)
        # from which the embeddings will be generated
        self.map = "from m in docs.Movies select new { vector_from_int8_arrays = CreateVector(m.tags_embedded_as_int8) }"

        # Customize the vector field using _vector
        self._vector(
            "vector_from_int8_arrays",
            VectorOptions(
                # Define the source embedding type
                source_embedding_type=VectorEmbeddingType.INT8,

                # Define the quantization for the destination embedding
                destination_embedding_type=VectorEmbeddingType.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
                number_of_edges=20,
                number_of_candidates_for_indexing=20,
            ),
        )

        # The index MUST use the Corax search engine
        self.search_engine_type = SearchEngineType.CORAX
```

#### JS\_index

```python
class Movies_ByVector_Int8_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            "map('Movies', function (m) { return { vector_from_int8_arrays: createVector(m.tags_embedded_as_int8) }; })"
        }
        self.fields = {
            "vector_from_int8_arrays": IndexFieldOptions(
                vector=VectorOptions(
                    source_embedding_type=VectorEmbeddingType.INT8,
                    destination_embedding_type=VectorEmbeddingType.INT8,
                    dimensions=2,
                    number_of_edges=20,
                    number_of_candidates_for_indexing=20,
                )
            )
        }

        self.search_engine_type = SearchEngineType.CORAX
```

#### IndexDefinition

```python
index_definition = IndexDefinition(
    name="Movies/ByVector/Int8",
    maps={"from m in docs.Movies select new { vector_from_int8_arrays = CreateVector(m.tags_embedded_as_int8) }"},
    fields={
        "vector_from_int8_arrays": IndexFieldOptions(
            vector=VectorOptions(
                source_embedding_type=VectorEmbeddingType.INT8,
                destination_embedding_type=VectorEmbeddingType.INT8,
                dimensions=2,
                number_of_edges=20,
                number_of_candidates_for_indexing=20,
            )
        )
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"},
)

store.maintenance.send(PutIndexesOperation(index_definition))
```

Execute a vector search using the index:  
(Provide a vector as the `vector.search` search term)

#### raw\_query

```python
similar_movies = list(
        session.advanced.raw_query(
            "from index 'Movies/ByVector/Int8' where vector.search(vector_from_int8_arrays, $queryVector)",
            object_type=Movie,
        )
        .add_parameter("queryVector", VectorQuantizer.to_int8([0.1, 0.2]))
        .wait_for_non_stale_results()
    )
```

#### RQL

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

### Indexing numerical data and querying using text input

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

#### AbstractIndexCreationTask

```python
class Movies_ByVectorFromPhoto(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()
        # Call 'CreateVector' to create a VECTOR FIELD.
        # Pass the document field containing the array from which the embeddings will be generated
        self.map = "from m in docs.Movies select new { vector_from_photo = CreateVector(m.movie_photo_embedding) }"

        # Customize the vector field using _vector
        self._vector(
            "vector_from_photo",
            VectorOptions(
                source_embedding_type=VectorEmbeddingType.SINGLE,
                destination_embedding_type=VectorEmbeddingType.SINGLE,
                # Dimensions should match the embedding size, 6 is only for our simple example...
                dimensions=6,
            ),
        )

        # The index MUST use the Corax search engine
        self.search_engine_type = SearchEngineType.CORAX
```

#### JS\_index

```python
class Movies_ByVectorFromPhoto_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            "map('Movies', function (m) { return { vector_from_photo: createVector(m.movie_photo_embedding) }; })"
        }
        self.fields = {
            "vector_from_photo": IndexFieldOptions(
                vector=VectorOptions(
                    source_embedding_type=VectorEmbeddingType.SINGLE,
                    destination_embedding_type=VectorEmbeddingType.SINGLE,
                    dimensions=6, # using 6 only for this simple example
                )
            )
        }

        self.search_engine_type = SearchEngineType.CORAX
```

#### IndexDefinition

```python
index_definition = IndexDefinition(
    name="Movies/ByVector/FromPhoto",
    maps={"from m in docs.Movies select new { vector_from_photo = CreateVector(m.movie_photo_embedding) }"},
    fields={
        "vector_from_photo": IndexFieldOptions(
            vector=VectorOptions(
                source_embedding_type=VectorEmbeddingType.SINGLE,
                destination_embedding_type=VectorEmbeddingType.SINGLE,
                dimensions=6, # using 6 only for this simple example
            )
        )
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"},
)

store.maintenance.send(PutIndexesOperation(index_definition))
```

Execute a vector search using the index:

- To convert the text into an embedding, pass a textual search term and the task ID to the `embedding.text()` call in the `vector.search` clause.

- 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.python.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.python.md#get-embeddings-generation-task-details)
  to learn how to check which tasks are defined and what their identifiers are.

#### raw\_query

```python
similar_movies = list(
        session.advanced.raw_query(
            "from index 'Movies/ByVectorFromPhoto' where vector.search(vector_from_photo, embedding.text($searchTerm, ai.task($embeddingTaskId)), 0.85, null)", Movie
        )
        .add_parameter("searchTerm", "NASA")
        .add_parameter("embeddingTaskId", "id-for-task-open-ai")
        .wait_for_non_stale_results()
    )
```

#### RQL

```sql
from index 'Movies/ByVectorFromPhoto'
where vector.search(vector_from_photo, 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.python.md).  
This allows you to query across all fields using various predicates.

### AbstractIndexCreationTask

```python
class Products_ByMultipleFields(AbstractIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.map = (
            "from product in docs.Products "
            "select new "
            "{"
            "   price_per_unit = product.PricePerUnit,"
            "   name = product.Name,"
            "   vector_from_text = CreateVector(product.Name)"
            "}"
        )

        # Configure the index-field 'Name' for FTS:
        self._index("name", FieldIndexing.SEARCH)

        # Note:
        # Default values will be used for the VECTOR FIELD if not customized here.

        # The index MUST use the Corax search engine
        self.search_engine_type = SearchEngineType.CORAX
```

### JS\_index

```python
class Products_ByMultipleFields_JS(AbstractJavaScriptIndexCreationTask):
    def __init__(self):
        super().__init__()
        self.maps = {
            "map('Products', function (p) {"
            "   return {"
            "       price_per_unit: p.PricePerUnit, "
            "       name: p.Name, "
            "       vector_from_text: createVector(p.Name) "
            "   };"
            "})"
        }
        
        self.fields = {
            "name": IndexFieldOptions(indexing=FieldIndexing.SEARCH),
        }
        
        self.search_engine_type = SearchEngineType.CORAX
```

### IndexDefinition

```python
index_definition = IndexDefinition(
    name="Products/ByMultipleFields",
    maps={
        "from product in docs.Products "
        "select new "
        "{"
        "   price_per_unit = product.PricePerUnit,"
        "   name = product.Name,"
        "   vector_from_text = CreateVector(product.Name)"
        "}"
    },
    fields={
        "name": IndexFieldOptions(indexing=FieldIndexing.SEARCH),
    },
    configuration={"Indexing.Static.SearchEngineType": "Corax"},
)

store.maintenance.send(PutIndexesOperation(index_definition))
```

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

### raw\_query

```python
results = list(
        session.advanced.raw_query(
            "from index 'Products/ByMultipleFields' where price_per_unit > $minPrice or search(name, $searchTerm1) or vector.search(vector_from_text, $searchTerm2, 0.8)",
            object_type=Product,
        )
        .add_parameter("minPrice", 200)
        .add_parameter("searchTerm1", "Alice")
        .add_parameter("searchTerm2", "italian")
        .wait_for_non_stale_results()
    )
```

### RQL

```sql
from index "Products/ByMultipleFields"
where price_per_unit > $minPrice
or search(name, $searchTerm1)
or vector.search(vector_from_text, $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.python.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.python.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.python.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 `forDoc` 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.

### raw\_query

```python
results = list(
        session.advanced.raw_query(
            # Pass a document ID to the 'forDoc' method to find similar documents
            "from index 'Products/ByVector/Text' where vector.search(vector_from_text, embedding.forDoc($documentID), 0.82)",
            object_type=Product,
        )
        .add_parameter("documentID", "Products/7-A")
        .wait_for_non_stale_results()
    )
```

### RQL

```sql
from index "Products/ByVector/Text"
// Pass a document ID to the 'forDoc' method to find similar documents
where vector.search(vector_from_text, 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*)

```
{`// 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 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` (e.g., `FieldIndexing.No` in code, 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.python.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.
