An implementation of LangChain vectorstore abstraction usingThe code lives in an integration package called: langchain-postgres.postgresas the backend and utilizing thepgvectorextension.
Status
This code has been ported over fromlangchain-community into a dedicated package called langchain-postgres. The following changes have been made:
langchain-postgresworks only with psycopg3. Please update your connnecion strings frompostgresql+psycopg2://...topostgresql+psycopg://langchain:langchain@...(yes, it’s the driver name ispsycopgnotpsycopg3, but it’ll usepsycopg3.- The schema of the embedding store and collection have been changed to make add_documents work correctly with user specified ids.
- One has to pass an explicit connection object now.
Setup
First donwload the partner package:pgvector extension:
Credentials
There are no credentials needed to run this notebook, just make sure you downloaded thelangchain-postgres package and correctly started the postgres container.
If you want to get best in-class automated tracing of your model calls you can also set your LangSmith API key by uncommenting below:
Instantiation
Manage vector store
Add items to vector store
Note that adding documents by ID will over-write any existing documents that match that ID.Delete items from vector store
Query vector store
Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent.Filtering Support
The vectorstore supports a set of filters that can be applied against the metadata fields of the documents.| Operator | Meaning/Category |
|---|---|
| $eq | Equality (==) |
| $ne | Inequality (!=) |
| $lt | Less than (<) |
| $lte | Less than or equal (<=) |
| $gt | Greater than (>) |
| $gte | Greater than or equal (>=) |
| $in | Special Cased (in) |
| $nin | Special Cased (not in) |
| $between | Special Cased (between) |
| $like | Text (like) |
| $ilike | Text (case-insensitive like) |
| $and | Logical (and) |
| $or | Logical (or) |
Query directly
Performing a simple similarity search can be done as follows:PGVector vector store, please refer to the API reference.
Query by turning into retriever
You can also transform the vector store into a retriever for easier usage in your chains.Usage for retrieval-augmented generation
For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:API reference
For detailed documentation of all __ModuleName__VectorStore features and configurations head to the API reference: python.langchain.com/api_reference/postgres/vectorstores/langchain_postgres.vectorstores.PGVector.htmlConnect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.