{"id":6393,"library":"llama-index-vector-stores-postgres","title":"LlamaIndex Postgres Vector Store","description":"The `llama-index-vector-stores-postgres` library provides an integration for LlamaIndex, allowing users to leverage PostgreSQL with the `pgvector` extension as a robust and scalable vector store. It is currently at version 0.8.1 and follows LlamaIndex's active development and frequent release cadence, especially for integration packages.","status":"active","version":"0.8.1","language":"en","source_language":"en","source_url":"https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/vector_stores/llama-index-vector-stores-postgres","tags":["LlamaIndex","vector store","PostgreSQL","pgvector","LLM","embedding","database"],"install":[{"cmd":"pip install llama-index-vector-stores-postgres llama-index psycopg2-binary","lang":"bash","label":"Install library and core LlamaIndex"}],"dependencies":[{"reason":"The vector store backend. Requires the 'pgvector' extension enabled.","package":"PostgreSQL","optional":false},{"reason":"PostgreSQL extension for vector similarity search. Essential for functionality.","package":"pgvector","optional":false},{"reason":"Core LlamaIndex library, which this package integrates with.","package":"llama-index","optional":false},{"reason":"Python adapter for PostgreSQL, used for database connections.","package":"psycopg2-binary","optional":false},{"reason":"SQL toolkit and ORM, used internally for database interactions.","package":"SQLAlchemy","optional":false}],"imports":[{"symbol":"PGVectorStore","correct":"from llama_index.vector_stores.postgres import PGVectorStore"},{"symbol":"VectorStoreIndex","correct":"from llama_index.core import VectorStoreIndex"},{"symbol":"SimpleDirectoryReader","correct":"from llama_index.core import SimpleDirectoryReader"},{"symbol":"StorageContext","correct":"from llama_index.core import StorageContext"}],"quickstart":{"code":"import os\nimport psycopg2\nfrom sqlalchemy import make_url\nfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext\nfrom llama_index.vector_stores.postgres import PGVectorStore\n\n# --- Database Setup (Example for local PostgreSQL) ---\n# Ensure PostgreSQL is running and 'pgvector' extension is enabled.\n# Example: CREATE EXTENSION IF NOT EXISTS vector; in your database.\n\nDB_HOST = os.environ.get('PG_HOST', 'localhost')\nDB_PORT = os.environ.get('PG_PORT', '5432')\nDB_USER = os.environ.get('PG_USER', 'postgres')\nDB_PASSWORD = os.environ.get('PG_PASSWORD', 'password')\nDB_NAME = os.environ.get('PG_DATABASE', 'llama_db')\nTABLE_NAME = os.environ.get('PG_TABLE_NAME', 'llamaindex_documents')\nEMBED_DIM = int(os.environ.get('EMBED_DIM', '1536')) # e.g., for OpenAI embeddings\n\nconnection_string = f\"postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}\"\n\n# Ensure the database exists and pgvector extension is enabled\ntry:\n    conn = psycopg2.connect(connection_string)\n    conn.autocommit = True\n    with conn.cursor() as c:\n        c.execute(f\"DROP DATABASE IF EXISTS {DB_NAME} WITH (FORCE);\")\n        c.execute(f\"CREATE DATABASE {DB_NAME};\")\n    conn.close()\n    print(f\"Database '{DB_NAME}' created/recreated.\")\nexcept Exception as e:\n    print(f\"Could not connect or create database: {e}\")\n    print(\"Please ensure PostgreSQL is running and connection details are correct.\")\n    exit(1)\n\n# Connect to the specific database for PGVectorStore\ndb_connection_string = f\"{connection_string}/{DB_NAME}\"\n\n# --- LlamaIndex Usage ---\n# 1. Create a dummy document for indexing\nif not os.path.exists(\"data\"): os.makedirs(\"data\")\nwith open(\"data/test_document.txt\", \"w\") as f:\n    f.write(\"The quick brown fox jumps over the lazy dog. This is a test document for LlamaIndex and Postgres.\")\n\ndocuments = SimpleDirectoryReader(\"data\").load_data()\n\n# 2. Initialize the PGVectorStore\nvector_store = PGVectorStore.from_params(\n    database=DB_NAME,\n    host=DB_HOST,\n    password=DB_PASSWORD,\n    port=int(DB_PORT),\n    user=DB_USER,\n    table_name=TABLE_NAME,\n    embed_dim=EMBED_DIM,\n)\n\n# 3. Create StorageContext and VectorStoreIndex\nstorage_context = StorageContext.from_defaults(vector_store=vector_store)\nindex = VectorStoreIndex.from_documents(\n    documents,\n    storage_context=storage_context,\n)\n\n# 4. Query the index\nquery_engine = index.as_query_engine()\nresponse = query_engine.query(\"What did the fox do?\")\nprint(f\"Response: {response}\")\n\n# Clean up\n# Note: To properly drop tables, you often need to connect to a different database (e.g., 'postgres')\n# or ensure no active connections to DB_NAME exist. For simplicity, we skip full table teardown here.\n# A full teardown might involve:\n# conn = psycopg2.connect(connection_string + '/postgres')\n# conn.autocommit = True\n# with conn.cursor() as c:\n#     c.execute(f\"DROP TABLE IF EXISTS {TABLE_NAME} CASCADE;\")\n# conn.close()\n","lang":"python","description":"This quickstart demonstrates how to initialize `PGVectorStore`, integrate it with LlamaIndex's `VectorStoreIndex`, and perform a simple query. It includes basic PostgreSQL setup steps (database creation and `pgvector` extension enablement) and uses environment variables for sensitive connection details. Ensure you have a PostgreSQL server running and the `pgvector` extension installed and enabled in your database."},"warnings":[{"fix":"Migrate your LlamaIndex core configurations to use the `Settings` object (e.g., `Settings.llm = ...`, `Settings.embed_model = ...`) or pass parameters directly to index/query engine constructors. Ensure all required integration packages (`llama-index-llms-openai`, `llama-index-embeddings-openai`, etc.) are installed separately.","message":"LlamaIndex v0.10.0 introduced a significant refactor, splitting the main library into `llama-index-core` and numerous integration packages. While namespace imports are generally preserved (e.g., `from llama_index.vector_stores.postgres import PGVectorStore`), the `ServiceContext` object was deprecated in favor of `Settings` or direct parameter passing for configuring LLMs, embeddings, etc.","severity":"breaking","affected_versions":">=0.10.0"},{"fix":"Before using `PGVectorStore`, ensure your PostgreSQL server has the `pgvector` extension installed and enable it in your target database with `CREATE EXTENSION IF NOT EXISTS vector;`.","message":"The PostgreSQL database must have the `pgvector` extension installed and enabled. Without this, the `PGVectorStore` will not function, and you may encounter SQL errors related to unknown vector types or functions.","severity":"gotcha","affected_versions":"All"},{"fix":"If operating with restricted database permissions, you might need to pre-create the schema manually, or subclass `PGVectorStore` to override and skip the schema creation method (`_create_schema_if_not_exists`). Alternatively, ensure the user has `CREATE` privilege on the database.","message":"`PGVectorStore` may attempt to create a new schema in the database, which can lead to `psycopg2.errors.InsufficientPrivilege` errors if the connected database user lacks schema creation permissions.","severity":"gotcha","affected_versions":"All"},{"fix":"For persistent storage of non-vector indexes, explicitly configure and pass a `PostgresIndexStore` (from `llama_index.storage.index_store.postgres`) to your `StorageContext` in addition to `PGVectorStore`.","message":"When persisting other index types (like `KeywordTableIndex`) alongside vector data in PostgreSQL, simply providing `PGVectorStore` to `StorageContext` is insufficient for their persistence. These other index types require a separate `IndexStore`.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z"}