1. How to use pgvector in PostgreSQL for vector similarity search with HNSW indexes?
❓ Context: Explain the vector data type, HNSW index tuning, and distance operators (<->, <=>, <#>) in Postgres 16+.
pgvector is an open-source extension for PostgreSQL that allows storing and indexing high-dimensional vector embeddings directly inside relational tables alongside relational data.
Distance Operators:
HNSW Indexing:
Provides fast approximate nearest neighbor (ANN) search without building IVF clusters.
-- Enable vector extension
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE document_chunks (
id BIGSERIAL PRIMARY KEY,
content TEXT NOT NULL,
embedding vector(1536) NOT NULL
);
-- Create HNSW index for fast Cosine Distance lookup
CREATE INDEX idx_chunks_embedding_hnsw
ON document_chunks
USING hnsw (embedding vector_cosine_ops);pgvector eliminates the need for separate standalone vector databases by keeping embeddings transactional within PostgreSQL.