Skip to main content

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 guide.

To learn how to create and store embeddings, see the Upsert Embeddings guide.

Setup​

Environment Setup​

Make sure to set up your environment variables:

.env
OPENAI_API_KEY=your_openai_api_key_here
POSTGRES_CONNECTION_STRING=your_connection_string_here

Dependencies​

Import the necessary dependencies:

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:

src/index.ts
const pgVector = new PgVector({
connectionString: process.env.POSTGRES_CONNECTION_STRING!,
});

Example Usage​

Filter by Metadata Value​

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);





View source on GitHub