[Python] How to properly initialize and query a PGVectorStore with metadata columns in...

Discussão em 'Python' iniciado por Stack, Junho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use PGVectorStore in LangChain with metadata columns, following the example in pypi page, but I'm encountering issues when attempting to add and query documents with metadata. The basic example without metadata works fine, but when I try to add metadata columns, I get an error.

    Here's the working code without metadata:

    from langchain_core.documents import Document
    from langchain_core.embeddings import DeterministicFakeEmbedding
    from langchain_postgres import PGEngine, PGVectorStore

    # Replace the connection string with your own Postgres connection string
    CONNECTION_STRING = "postgresql+psycopg3://langchain:langchain@localhost:6024/langchain"
    engine = PGEngine.from_connection_string(url=CONNECTION_STRING)

    # Replace the vector size with your own vector size
    VECTOR_SIZE = 768
    embedding = DeterministicFakeEmbedding(size=VECTOR_SIZE)

    TABLE_NAME = "my_doc_collection"

    engine.init_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=VECTOR_SIZE,
    )

    store = PGVectorStore.create_sync(
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
    )

    docs = [
    Document(page_content="Apples and oranges"),
    Document(page_content="Cars and airplanes"),
    Document(page_content="Train")
    ]

    store.add_documents(docs)

    query = "I'd like a fruit."
    docs = store.similarity_search(query)
    print(docs)


    This works perfectly. However, when I try to add metadata columns like this:

    store = PGVectorStore.create_sync(
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
    metadata_columns=[
    "country",
    "city",
    "address",
    ]
    )


    I get the following error:

    ValueError: Metadata column, country, does not exist.

    Questions:

    • How do I properly initialize a PGVectorStore with metadata columns?
    • Do I need to modify the table creation step to include these metadata columns?
    • How should I structure my Document objects to include metadata when adding them to the store?
    • Once set up, how can I query documents filtering by metadata values?

    I've tried looking at the documentation, but I couldn't find a clear example of how to set up and use metadata with PGVectorStore. Any help or guidance would be greatly appreciated!

    Additional Information:

    • LangChain version:
      • langchain==0.3.24
      • langchain-community==0.3.23
      • langchain-core==0.3.56
      • langchain-openai==0.3.15
      • langchain-postgres==0.0.14
    • Python version: 3.12

    Continue reading...

Compartilhe esta Página