# vectorSearch

Performs an approximate nearest neighbor (ANN) vector search. This command is an extension of the `$vectorSearch` MongoDB® aggregation pipeline operator. To create a vector index on a collection, use the [createIndexes](https://docs.singlestore.com/cloud/reference/singlestore-kai/singlestore-extension-commands/createindexes.md) command.

## Syntax

```
{
  "$vectorSearch": {
    "index": "<index-name>",
    "path": "<field-to-search>",
    "queryVector": [<array-of-numbers>],
    "numCandidates": <number-of-candidates>, // this values is ignored
    "limit": <number-of-results>,
    "filter": {<filter-specification>},
    "kaiSearchOptions": "<json-object>" // additional search parameters
} }
```

## Arguments

| Field              | Type             | Requirement | Description                                                         |
| ------------------ | ---------------- | ----------- | ------------------------------------------------------------------- |
| `index`            | String           | Required    | The name of the vector index to use.                                |
| `path`             | String           | Required    | The field to search.                                                |
| `queryVector`      | Array of numbers | Required    | An array of numbers that represents the query vector to search.     |
| `numCandidates`    | Number           | Optional    | SingleStoreignores this field.                                      |
| `limit`            | Number           | Optional    | The number of documents to return in the result.                    |
| `filter`           | Document         | Optional    | An expression to filter the indexed fields.                         |
| `kaiSearchOptions` | JSON object      | Optional    | Specifies search parameters based on the type of vector index used. |

## Remarks

* You can specify supported [search options](https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/#section-idm457710817120003408966071884.md) in the `kaiSearchOptions` parameter for each index type.
* For a list of vector indexes supported by SingleStore, refer to [Index Type and Parameters](https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/#section-idm4561847861673634089753109443.md). For information on recommended practices and using vector indexes, refer to [Tuning Vector Indexes and Queries](https://docs.singlestore.com/cloud/developer-resources/functional-extensions/tuning-vector-indexes-and-queries.md).

## Examples

The following examples create a vector index, add vectors to a collection, and then search for a specified vector in the collection using `vectorSearch`.

## Example 1

The following example creates a IVF\_PQFS type vector index with `EUCLIDEAN_DISTANCE` `metric_type`.

## 1. Create a Vector Index

Use the `createIndexes` command to create a IVF\_PQFS type vector index named `searchVector_EUC`.

```MongoDB
col = db.exampleCollection

res = db.runCommand({
  createIndexes: "exampleCollection",
  indexes: [
    { key: { "sampleVectors": "vector" },
      name: "searchVector_EUC",
      kaiIndexOptions: {
        index_type: "IVF_PQFS",
        m: 4,
        nprobe: 20,
        nlist: 128,
        metric_type: "EUCLIDEAN_DISTANCE",
        dimensions: 4
      }
    }]})
```

## 2. Add Vectors

Run the following command to add vectors to a collection named `exampleCollection`. This example uses fictional vectors for simplicity.

```MongoDB
col.insertMany([
    {name: "John Doe", occupation: "Software Engineer", sampleVectors: [0.8, 0.2, 0.5, 0.1]},
    {name: "Jane Smith", occupation: "Data Scientist", sampleVectors: [0.6, 0.9, 0.3, 0.7]},
    {name: "Alice Johnson", occupation: "Marketing Manager", sampleVectors: [0.3, 0.7, 0.4, 0.2]},
    {name: "Bob Brown", occupation: "Project Manager", sampleVectors: [0.5, 0.6, 0.8, 0.3]},
    {name: "Emily Davis", occupation: "Graphic Designer", sampleVectors: [0.2, 0.4, 0.6, 0.9]}
])

```

```output

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('666944f2b98d7f1d23ee870e'),
    '1': ObjectId('666944f2b98d7f1d23ee870f'),
    '2': ObjectId('666944f2b98d7f1d23ee8710'),
    '3': ObjectId('666944f2b98d7f1d23ee8711'),
    '4': ObjectId('666944f2b98d7f1d23ee8712')
  }
}

```

## 3. Perform a Vector Search

Use the `$vectorSearch` command to perform a vector search on your vector data using the `searchVector_EUC` vector index created earlier.

```MongoDB
res = col.aggregate([
    { $vectorSearch: {
        index: "searchVector_EUC",
        path: "sampleVectors",
        queryVector: [0.6, 0.8, 0.9, 0.1],
        k: 20,
        numCandidates: 5,
        limit: 2
      }
   }]).toArray()

```

```output

[
  {
    _id: ObjectId('666944f2b98d7f1d23ee8711'),
    name: 'Bob Brown',
    occupation: 'Project Manager',
    sampleVectors: [ 0.5, 0.6, 0.8, 0.3 ]
  },
  {
    _id: ObjectId('666944f2b98d7f1d23ee8710'),
    name: 'Alice Johnson',
    occupation: 'Marketing Manager',
    sampleVectors: [ 0.3, 0.7, 0.4, 0.2 ]
  }
]

```

## Example 2

The following example creates a HNSW\_FLAT type vector index with `DOT_PRODUCT` `metric_type`.

1. Create a vector index named `searchVector_HNSW_DOT`:
   ```MongoDB
   col = db.exampleCollection2

   res = db.runCommand({
     createIndexes: "exampleCollection2",
     indexes: [
       { key: { "sampleVectors": "vector" },
         name: "searchVector_HNSW_DOT",
         kaiIndexOptions: {
           index_type: "HNSW_FLAT",
           M: 12,
           efConstruction: 120,
   	 dimensions: 4
         }
       }]})
   ```

2. Add vectors to the collection. This example uses fictional vectors for simplicity.
   ```MongoDB
   col.insertMany([
       {name: "John Doe", occupation: "Software Engineer", sampleVectors: [0.8, 0.2, 0.5, 0.1]},
       {name: "Jane Smith", occupation: "Data Scientist", sampleVectors: [0.6, 0.9, 0.3, 0.7]},
       {name: "Alice Johnson", occupation: "Marketing Manager", sampleVectors: [0.3, 0.7, 0.4, 0.2]},
       {name: "Bob Brown", occupation: "Project Manager", sampleVectors: [0.5, 0.6, 0.8, 0.3]},
       {name: "Emily Davis", occupation: "Graphic Designer", sampleVectors: [0.2, 0.4, 0.6, 0.9]}
   ])

   ```
   ```output

   {
     acknowledged: true,
     insertedIds: {
       '0': ObjectId('66694706b98d7f1d23ee8718'),
       '1': ObjectId('66694706b98d7f1d23ee8719'),
       '2': ObjectId('66694706b98d7f1d23ee871a'),
       '3': ObjectId('66694706b98d7f1d23ee871b'),
       '4': ObjectId('66694706b98d7f1d23ee871c')
     }
   }
   ```

3. Perform a vector search using the `searchVector_HNSW_DOT` vector index created earlier.
   ```MongoDB
   res = col.aggregate([
       { $vectorSearch: {
           index: "searchVector_HNSW_DOT",
           path: "sampleVectors",
           queryVector: [0.1, 0.6, 0.3, 0.8],
           numCandidates: 5,
           limit: 2
         }
      }]).toArray()

   ```
   ```output

   [
     {
       _id: ObjectId('66694706b98d7f1d23ee8719'),
       name: 'Jane Smith',
       occupation: 'Data Scientist',
       sampleVectors: [ 0.6, 0.9, 0.3, 0.7 ]
     },
     {
       _id: ObjectId('66694706b98d7f1d23ee871c'),
       name: 'Emily Davis',
       occupation: 'Graphic Designer',
       sampleVectors: [ 0.2, 0.4, 0.6, 0.9 ]
     }
   ]

   ```

## References

* [Tuning Vector Indexes and Queries](https://docs.singlestore.com/cloud/developer-resources/functional-extensions/tuning-vector-indexes-and-queries.md)
* [Vector Indexing](https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing.md)
* [Working with Vector Data](https://docs.singlestore.com/cloud/developer-resources/functional-extensions/working-with-vector-data.md)

***

Modified at: June 12, 2024

Source: [/cloud/reference/singlestore-kai/singlestore-extension-commands/vectorsearch/](https://docs.singlestore.com/cloud/reference/singlestore-kai/singlestore-extension-commands/vectorsearch/)

(An index of the documentation is available at /llms.txt)
