> ## Documentation Index
> Fetch the complete documentation index at: https://docs.neuraltrust.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Postgres

# **PostgresKnowledgeBase**

`PostgresKnowledgeBase` is a PostgreSQL-backed vector knowledge base class that supports fast document retrieval using semantic vector search and traditional text-based queries. It leverages the [`pgvector`](https://github.com/pgvector/pgvector) extension for similarity search and is built to integrate with LLMs and embeddings models.

## Installation

```bash theme={null}
uv add "trusttest[rag-postgres]"
```

## Environment Variables

You can use environment variables for seamless config:

```bash theme={null}
POSTGRES_URL=localhost
POSTGRES_USERNAME=postgres
POSTGRES_PASSWORD=secret
POSTGRES_DATABASE=docs
```

## Example Usage

```python theme={null}
from trusttest.kb import PostgresKnowledgeBase
from trusttest.embeddings import EmbeddingsOpenAi

kb = PostgresKnowledgeBase(
    database="music",
    uri="localhost",
    username="postgres",
    password="password",
    fields_mapping={
        "id": "id",
        "content": "lyrics",
        "embedding": "embedding",
        "table": "Song",
    },
    embeddings_model=EmbeddingsOpenAi(api="openai", model="text-embedding-3-small"),
    seed_topics=["love", "party", "nature", "sadness"]
)

results = kb.search("ocean")
```

## Notes & Tips

* If the `embedding` field is not specified, semantic search will be disabled.
* To enable `pgvector`, make sure your database has the extension installed:

```sql theme={null}
CREATE EXTENSION IF NOT EXISTS vector;
```

* Semantic similarity uses the `<->` operator for efficient ANN search.
