> ## Documentation Index
> Fetch the complete documentation index at: https://www.paradedb.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Vector Search Quickstart

> Store, index, query, verify, and tune a nearest-neighbor search in ParadeDB

> [!NOTE]
>
> We strongly recommend **`0.27.0`** or later for substantial vector search
> improvements.

This guide runs a nearest-neighbor search from start to finish: store vectors, index them, query, verify that the index is used, and tune recall. It uses the `mock_items` table from [Configure Your Environment](https://www.paradedb.com/docs/start/configure-your-environment.md), which has an eight-dimensional `embedding` column. For the mental model, see [How Vector Search Works](https://www.paradedb.com/docs/concepts/vector/overview.md).

## 1. Store Vectors

Vectors are stored in a `pdb.vector(N)` column, where `N` is the number of dimensions. `mock_items` already has one, declared as `pdb.vector(8)`.

On your own table, declare the column with the dimension of your embedding model. The dimension is required to index the column:

```sql theme={null}
CREATE TABLE documents (
  id bigint PRIMARY KEY,
  body text,
  embedding pdb.vector(1536)
);
```

A vector is written as a bracketed list of numbers, such as `'[0.1, 0.2, 0.3]'`. Pass it from your application as a parameter:

```sql theme={null}
INSERT INTO documents (id, body, embedding)
VALUES ($1, $2, $3);
```

> [!NOTE]
>
> `pdb.vector` requires `0.27.2` or later. To use an existing pgvector column
> instead, see [Compatibility with pgvector
> Types](https://www.paradedb.com/docs/reference/indexing/field-types/vector.md#compatibility-with-pgvector-types).

## 2. Create the Index

Add the vector column to a ParadeDB index together with every column you will filter or sort on. The operator class after the column sets the distance metric:

```sql SQL theme={null}
CREATE INDEX search_idx ON mock_items
USING paradedb (id, description, category, embedding pdb.vector_cosine_ops);
```

```ts Drizzle theme={null}
import { indexing } from "@paradedb/drizzle-paradedb";

// In the pgTable definition:
(table) => [
  indexing
    .paradedbIndex("search_idx")
    .on(
      table.id,
      table.description,
      table.category,
      indexing.vectorField(table.embedding, "cosine"),
    ),
];
```

```python Django theme={null}
from django.db import connection
from paradedb.indexes import ParadeDBIndex

with connection.schema_editor() as schema_editor:
    schema_editor.add_index(
        MockItem,
        ParadeDBIndex(
            fields={
                "id": {},
                "description": {},
                "category": {},
                "embedding": {"metric": "cosine"},
            },
            name="search_idx",
        ),
    )
```

```python SQLAlchemy theme={null}
from sqlalchemy import Index
from paradedb.sqlalchemy import indexing

idx = Index(
    "search_idx",
    indexing.ParadeDBField(MockItem.id),
    indexing.ParadeDBField(MockItem.description),
    indexing.ParadeDBField(MockItem.category),
    indexing.VectorField(MockItem.embedding, metric="cosine"),
    postgresql_using="paradedb",
)

with engine.begin() as conn:
    idx.create(conn)
```

```ruby Rails theme={null}
ActiveRecord::Base.connection.add_paradedb_index(
  :mock_items,
  fields: {
    id: {},
    description: {},
    category: {},
    embedding: { metric: :cosine }
  },
  name: :search_idx
)
```

```cs EF Core theme={null}
modelBuilder.Entity<MockItem>()
    .HasParadeDbIndex("search_idx", e => e.Id)
    .HasField(e => e.Description)
    .HasField(e => e.Category)
    .HasField(e => e.Embedding, VectorMetric.Cosine);
```

> [!NOTE]
>
> If you created `search_idx` in [Create Your First
> Index](https://www.paradedb.com/docs/start/create-your-first-index.md), skip this step. That index already
> includes `embedding`, and a table can have only one ParadeDB index.

| Operator class | Distance | Query operator |
| - | - | - |
| `pdb.vector_l2_ops` | Euclidean | `<->` |
| `pdb.vector_cosine_ops` | Cosine | `<=>` |
| `pdb.vector_ip_ops` | Inner product | `<#>` |

Pick the metric your embedding model was trained for. For a large table, load the data first, then create the index.

## 3. Query

A vector search is an `ORDER BY` on the distance with a `LIMIT`. To use the ParadeDB index it also needs a ParadeDB search operator in the `WHERE` clause. With no filter, use `pdb.all()`.

In an application, the query vector comes from your embedding model and is passed in as a parameter. This guide uses the embedding stored for one row, `Sleek running shoes`, as the query vector. Read it first:

```sql theme={null}
SELECT embedding FROM mock_items WHERE id = 3;
```

```ini Expected Response theme={null}
                                 embedding
---------------------------------------------------------------------------
 [-0.01708,0.467566,-0.757486,0.134082,0.33933,0.04403,0.185394,-0.194613]
(1 row)
```

`mock_items` stores 8-dimension vectors, so the value is short enough to paste. Order the rows by their distance to it:

```sql SQL theme={null}
SELECT id, description
FROM mock_items
WHERE id @@@ pdb.all()
ORDER BY embedding <=> '[-0.01708,0.467566,-0.757486,0.134082,0.33933,0.04403,0.185394,-0.194613]'
LIMIT 5;
```

```ts Drizzle theme={null}
import { eq } from "drizzle-orm";
import { search } from "@paradedb/drizzle-paradedb";

const [source] = await db
  .select({ embedding: mockItems.embedding })
  .from(mockItems)
  .where(eq(mockItems.id, 3));
const queryEmbedding = source.embedding;

await db
  .select({ id: mockItems.id, description: mockItems.description })
  .from(mockItems)
  .where(search.all(mockItems.id))
  .orderBy(search.cosineDistance(mockItems.embedding, queryEmbedding))
  .limit(5);
```

```python Django theme={null}
from paradedb import All, ParadeDB
from paradedb.vector import CosineDistance

query_embedding = MockItem.objects.get(id=3).embedding

MockItem.objects.filter(
    id=ParadeDB(All())
).order_by(
    CosineDistance('embedding', query_embedding)
).values('id', 'description')[:5]
```

```python SQLAlchemy theme={null}
from sqlalchemy import select
from sqlalchemy.orm import Session
from paradedb.sqlalchemy import search, vector

with Session(engine) as session:
    query_embedding = session.scalar(
        select(MockItem.embedding).where(MockItem.id == 3)
    )

    stmt = (
        select(MockItem.id, MockItem.description)
        .where(search.all(MockItem.id))
        .order_by(vector.cosine_distance(MockItem.embedding, query_embedding))
        .limit(5)
    )

    session.execute(stmt).all()
```

```ruby Rails theme={null}
query_embedding = MockItem.find(3).embedding

MockItem.nearest(:embedding, query_embedding, metric: :cosine)
        .select(:id, :description)
        .limit(5)
```

```cs EF Core theme={null}
var queryEmbedding = await dbContext
    .MockItems.Where(item => item.Id == 3)
    .Select(item => item.Embedding!)
    .SingleAsync();

await dbContext
    .MockItems.Where(item => EF.Functions.All(item.Id))
    .OrderBy(item => EF.Functions.CosineDistance(item.Embedding, queryEmbedding))
    .Select(item => new { item.Id, item.Description })
    .Take(5)
    .ToListAsync();
```

```ini Expected Response theme={null}
 id |       description
----+--------------------------
  3 | Sleek running shoes
 20 | Interactive board game
 15 | Refreshing face wash
  4 | White jogging shoes
 22 | Fast charging power bank
(5 rows)
```

The row itself comes first, at distance `0`. `mock_items` holds small sample embeddings, so the other neighbors are not related by meaning.

To search within a subset, filter on indexed columns. The result is the nearest rows among those that match:

```sql SQL theme={null}
SELECT id, description
FROM mock_items
WHERE category === 'footwear'
ORDER BY embedding <=> '[-0.01708,0.467566,-0.757486,0.134082,0.33933,0.04403,0.185394,-0.194613]'
LIMIT 5;
```

```ts Drizzle theme={null}
import { eq } from "drizzle-orm";
import { search } from "@paradedb/drizzle-paradedb";

const [source] = await db
  .select({ embedding: mockItems.embedding })
  .from(mockItems)
  .where(eq(mockItems.id, 3));
const queryEmbedding = source.embedding;

await db
  .select({ id: mockItems.id, description: mockItems.description })
  .from(mockItems)
  .where(search.term(mockItems.category, "footwear"))
  .orderBy(search.cosineDistance(mockItems.embedding, queryEmbedding))
  .limit(5);
```

```python Django theme={null}
from paradedb import ParadeDB, Term
from paradedb.vector import CosineDistance

query_embedding = MockItem.objects.get(id=3).embedding

MockItem.objects.filter(
    category=ParadeDB(Term('footwear'))
).order_by(
    CosineDistance('embedding', query_embedding)
).values('id', 'description')[:5]
```

```python SQLAlchemy theme={null}
from sqlalchemy import select
from sqlalchemy.orm import Session
from paradedb.sqlalchemy import search, vector

with Session(engine) as session:
    query_embedding = session.scalar(
        select(MockItem.embedding).where(MockItem.id == 3)
    )

    stmt = (
        select(MockItem.id, MockItem.description)
        .where(search.term(MockItem.category, "footwear"))
        .order_by(vector.cosine_distance(MockItem.embedding, query_embedding))
        .limit(5)
    )

    session.execute(stmt).all()
```

```ruby Rails theme={null}
query_embedding = MockItem.find(3).embedding

MockItem.search(:category)
        .term("footwear")
        .nearest(:embedding, query_embedding, metric: :cosine)
        .select(:id, :description)
        .limit(5)
```

```cs EF Core theme={null}
var queryEmbedding = await dbContext
    .MockItems.Where(item => item.Id == 3)
    .Select(item => item.Embedding!)
    .SingleAsync();

await dbContext
    .MockItems.Where(item => EF.Functions.Term(item.Category, "footwear"))
    .OrderBy(item => EF.Functions.CosineDistance(item.Embedding, queryEmbedding))
    .Select(item => new { item.Id, item.Description })
    .Take(5)
    .ToListAsync();
```

```ini Expected Response theme={null}
 id |     description
----+----------------------
  3 | Sleek running shoes
  4 | White jogging shoes
  5 | Generic shoes
 23 | Comfortable slippers
 13 | Sturdy hiking boots
(5 rows)
```

> [!WARNING]
>
> Without a search operator in `WHERE`, the query returns correct results but
> does not use the index, and no warning is raised.

## 4. Verify

`EXPLAIN` shows whether the index is doing the work. Look for `TopKScanExecState`:

```sql theme={null}
EXPLAIN (COSTS OFF)
SELECT id, description
FROM mock_items
WHERE category === 'footwear'
ORDER BY embedding <=> '[-0.01708,0.467566,-0.757486,0.134082,0.33933,0.04403,0.185394,-0.194613]'
LIMIT 5;
```

```csv Expected Response theme={null}
 Limit
   ->  Custom Scan (ParadeDB Base Scan) on mock_items
         Table: mock_items
         Index: search_idx
         Vector Search:
           Filtering: Pre (postings)
         Exec Method: TopKScanExecState
         Scores: false
            TopK Order By: embedding <=> vector asc
            TopK Limit: 5
         Tantivy Query: {"with_index":{"query":{"term":{"field":"category","value":"footwear"}}}}
```

A `Sort` node above the scan means the query did not use the vector index. See [Troubleshooting](https://www.paradedb.com/docs/reference/vector/troubleshooting.md#a-query-does-not-use-the-vector-index).

## 5. Tune

Vector search over a large index is approximate. One setting trades accuracy for speed:

```sql theme={null}
SET paradedb.vector_cluster_max_probe = 200;
```

Higher values find more of the true nearest neighbors and take longer. The default is `100`. Before going to production, [measure recall](https://www.paradedb.com/docs/reference/vector/tuning.md#measuring-recall) on a sample of real queries and choose the lowest value that meets your target. Small tables are searched exactly and need no tuning.

## Next Steps

> [card] [Indexing Vectors](https://www.paradedb.com/docs/reference/indexing/field-types/vector.md)
>
> Add `pdb.vector` or pgvector `vector` columns to a ParadeDB index.

> [card] [Querying Vectors](https://www.paradedb.com/docs/reference/vector/querying.md)
>
> Run nearest-neighbor queries with filters, joins, and deterministic
> ordering.

> [card] [Tuning Recall and Latency](https://www.paradedb.com/docs/reference/vector/tuning.md)
>
> Trade recall against latency and read `EXPLAIN ANALYZE` for a vector query.

> [card] [Vector Indexes](https://www.paradedb.com/docs/operate/performance-tuning/vector-indexes.md)
>
> Build large vector indexes and keep them fast under writes.

> [card] [Troubleshooting](https://www.paradedb.com/docs/reference/vector/troubleshooting.md)
>
> Diagnose slow queries, low recall, warnings, and errors.

> [card] [Hybrid Search](https://www.paradedb.com/docs/reference/hybrid/overview.md)
>
> Combine vector and full-text rankings.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.