Docspgvector
pgvector Integration
Native vector similarity search for AI-powered applications, semantic search, and RAG pipelines.
Vector search through REST and GraphQL
Postrust provides native support for pgvector, enabling vector similarity search directly through your REST and GraphQL APIs. Build AI-powered applications with:
- Semantic search using embeddings
- Product recommendations
- RAG (Retrieval Augmented Generation) pipelines
- Image similarity search
- Document clustering
Setup
SQL
-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create table with vector column
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT,
embedding vector(1536) -- OpenAI dimensions
);
-- Create index for fast similarity search
CREATE INDEX ON documents
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);REST API
cURL
# Insert document with embedding
curl -X POST "localhost:3000/documents" \
-H "Content-Type: application/json" \
-d '{
"title": "Introduction to Rust",
"content": "Rust is a systems programming language...",
"embedding": [0.1, 0.2, 0.3, ...]
}'
# Search similar documents via RPC
curl -X POST "localhost:3000/rpc/search_similar" \
-H "Content-Type: application/json" \
-d '{
"query_embedding": [0.1, 0.2, ...],
"match_count": 10
}'Similarity Search Function
Create a PostgreSQL function for semantic search:
SQL
CREATE OR REPLACE FUNCTION search_similar(
query_embedding vector(1536),
match_count int DEFAULT 10,
match_threshold float DEFAULT 0.8
)
RETURNS TABLE (
id int,
title text,
content text,
similarity float
)
LANGUAGE sql STABLE
AS $$
SELECT
documents.id,
documents.title,
documents.content,
1 - (documents.embedding <=> query_embedding) AS similarity
FROM documents
WHERE 1 - (documents.embedding <=> query_embedding) > match_threshold
ORDER BY documents.embedding <=> query_embedding
LIMIT match_count;
$$;GraphQL API
GraphQL
# Query documents with embeddings
query {
documents {
id
title
embedding
}
}
# Similarity search via RPC
query SearchSimilar($embedding: [Float!]!) {
searchSimilar(queryEmbedding: $embedding, matchCount: 10) {
id
title
content
similarity
}
}Distance Operators
| Operator | Description | Use Case |
|---|---|---|
| <-> | L2 distance (Euclidean) | General purpose |
| <#> | Negative inner product | Normalized vectors |
| <=> | Cosine distance | Text embeddings |
Index Types
IVFFlat
Faster build, less memory. Good for most use cases.
USING ivfflat (embedding vector_cosine_ops)HNSW
More accurate, faster queries. Slower to build.
USING hnsw (embedding vector_cosine_ops)