Migrating from the legacy PGVector class to PGVectorStore moves your data from a two-table schema to a single-table-per-collection schema. This improves performance through better metadata handling (columns instead of JSON) and simplifies management.
Recommended Migration Workflow
- Initialize the Engine: Create a
PGEngine using your connection string. - Initialize Destination Table: Use
engine.init_vectorstore_table to create the new table. You can customize metadata_columns and id_column for better filtering and non-UUID identifiers. - Create VectorStore Object: Instantiate
PGVectorStore.create_sync (or the async equivalent) using the engine and your embedding service. If you customized columns in step 2, you must pass the same metadata_columns and id_column here. - Execute Migration: Use
migrate_pgvector_collection to copy data. Setting delete_pg_collection=True will remove the data from the original PGVector tables after a successful copy.
from langchain_postgres import PGEngine, PGVectorStore
from langchain_postgres.utils.pgvector_migrator import migrate_pgvector_collection
from langchain_core.embeddings import FakeEmbeddings
from sqlalchemy import Column
# 1. Setup Engine
engine = PGEngine.from_connection_string(url="postgresql://user:pass@host/db")
# 2. Setup Destination Table
VECTOR_SIZE = 768
metadata_columns = [Column("col_0", "VARCHAR")]
engine.init_vectorstore_table(
table_name="destination_table",
vector_size=VECTOR_SIZE,
metadata_columns=metadata_columns,
id_column=Column("langchain_id", "VARCHAR"),
)
# 3. Create VectorStore
destination_vector_store = PGVectorStore.create_sync(
engine,
embedding_service=FakeEmbeddings(size=VECTOR_SIZE),
table_name="destination_table",
metadata_columns=["col_0"],
id_column="langchain_id",
)
# 4. Migrate
migrate_pgvector_collection(
engine,
collection_name="my_collection",
vector_store=destination_vector_store,
delete_pg_collection=True,
)