# Hybrid Vector Search
[EN] Source: https://mastra.ai/examples/rag/query/hybrid-vector-search

When you combine vector similarity search with metadata filters, you can create a hybrid search that is more precise and efficient.
This approach combines:

- Vector similarity search to find the most relevant documents
- Metadata filters to refine the search results based on additional criteria

This example demonstrates how to use hybrid vector search with Mastra and PGVector.

## Overview

The system implements filtered vector search using Mastra and PGVector. Here's what it does:

1. Queries existing embeddings in PGVector with metadata filters
2. Shows how to filter by different metadata fields
3. Demonstrates combining vector similarity with metadata filtering

> **Note**: For examples of how to extract metadata from your documents, see the [Metadata Extraction](../embedding/metadata-extraction) guide.
>
> To learn how to create and store embeddings, see the [Upsert Embeddings](/examples/rag/upsert/upsert-embeddings) guide.

## Setup

### Environment Setup

Make sure to set up your environment variables:

```bash title=".env"
OPENAI_API_KEY=your_openai_api_key_here
POSTGRES_CONNECTION_STRING=your_connection_string_here
```

### Dependencies

Import the necessary dependencies:

```typescript copy showLineNumbers title="src/index.ts"
import { embed } from "ai";
import { PgVector } from "@mastra/pg";
import { openai } from "@ai-sdk/openai";
```

## Vector Store Initialization

Initialize PgVector with your connection string:

```typescript copy showLineNumbers{4} title="src/index.ts"
const pgVector = new PgVector({
  connectionString: process.env.POSTGRES_CONNECTION_STRING!,
});
```

## Example Usage

### Filter by Metadata Value

```typescript copy showLineNumbers{6} title="src/index.ts"
// Create embedding for the query
const { embedding } = await embed({
  model: openai.embedding("text-embedding-3-small"),
  value: "[Insert query based on document here]",
});

// Query with metadata filter
const result = await pgVector.query({
  indexName: "embeddings",
  queryVector: embedding,
  topK: 3,
  filter: {
    "path.to.metadata": {
      $eq: "value",
    },
  },
});

console.log("Results:", result);
```

<br />
<br />
<hr className="dark:border-[#404040] border-gray-300" />
<br />
<br />
<GithubLink
  link={
    "https://github.com/mastra-ai/mastra/blob/main/examples/basics/rag/hybrid-vector-search"
  }
/>


---
title: "Example: Retrieving Top-K Results | RAG"
description: Example of using Mastra to query a vector database and retrieve semantically similar chunks.
---

import GithubLink from "@site/src/components/GithubLink";