Skip to content

API Reference parrot.stores.postgres

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.stores.postgres

View source

Alias AbstractStore

Re-exported from parrot.stores.abstract.AbstractStore.

Class Base

Alias DistanceStrategy

Re-exported from parrot.stores.models.DistanceStrategy.

Alias Document

Re-exported from parrot.stores.models.Document.

Alias LateChunkingProcessor

Re-exported from parrot.stores.utils.chunking.LateChunkingProcessor.

Class PgVectorStore

A PostgreSQL vector store implementation using pgvector, completely independent of Langchain. This store interacts directly with a specified schema and table for robust data isolation.

Parameter Type Default Description
table str None
schema str 'public'
id_column str 'id'
embedding_column str 'embedding'
document_column str 'document'
text_column str 'text'
embedding_model Union[dict, str] 'sentence-transformers/all-mpnet-base-v2'
embedding Optional[Callable] None
distance_strategy DistanceStrategy DistanceStrategy.COSINE
use_uuid bool False
pool_size int 50
auto_initialize bool True
enable_colbert bool False
**kwargs {}

Method PgVectorStore.get_id_column

Return the ID column definition based on whether to use UUID or not. If use_uuid is True, the ID column will be a PostgreSQL UUID type with server-side generation using uuid_generate_v4(). If use_uuid is False, the ID column will be a String type with a default value generated by Python's uuid.uuid4() function.

get_id_column(use_uuid: bool) -> sqlalchemy.Column

Parameter Type Default Description
use_uuid bool

Returns: sqlalchemy.Column

Method PgVectorStore.define_collection_table

Dynamically define a SQLAlchemy Table for pgvector storage.

define_collection_table(table: str, schema: str, dimension: int = 384, metadata: Optional[MetaData] = None, use_uuid: bool = False, id_column: str = 'id', embedding_column: str = 'embedding') -> sqlalchemy.Table

Parameter Type Default Description
table str
schema str
dimension int 384
metadata Optional[MetaData] None
use_uuid bool False
id_column str 'id'
embedding_column str 'embedding'

Returns: sqlalchemy.Table

Method PgVectorStore.connection

Establishes and returns an async database connection.

connection(dsn: str = None) -> AsyncEngine

Parameter Type Default Description
dsn str None

Returns: AsyncEngine

Method PgVectorStore.get_session

Get a session from the pool. This is the main method for getting connections.

get_session() -> AsyncSession

Returns: AsyncSession

Method PgVectorStore.session

Context manager for handling database sessions with proper cleanup. This is the recommended way to handle database operations.

session()

Method PgVectorStore.initialize_database

Initialize pgvector extension and detect index tuning.

Index-dependent settings (hnsw., ivfflat.) are only applied when a vector index actually exists on the table. Settings are registered via a connection-pool event so every session gets them.

enable_seqscan is intentionally left at the PostgreSQL default (on) so queries work on tables without a vector index.

initialize_database()

Method PgVectorStore.disconnect

Completely dispose of the engine and close all connections. Call this when you're completely done with the store.

disconnect() -> None

Method PgVectorStore.add_documents

Embeds and adds documents to the specified table.

When metadata_filters is provided, existing rows matching ALL filter conditions are deleted before the new rows are inserted (upsert via delete-and-insert). Filter semantics are identical to similarity_search: scalar → equality, list → IN. All filter values are parameter-bound to prevent SQL injection.

add_documents(documents: List[Document], table: str = None, schema: str = None, embedding_column: str = 'embedding', content_column: str = 'document', metadata_column: str = 'cmetadata', metadata_filters: Optional[Dict[str, Any]] = None, **kwargs) -> None

Parameter Type Default Description
documents List[Document] A list of Document objects to add.
table str None The name of the table.
schema str None The database schema where the table resides.
embedding_column str 'embedding' The name of the column to store embeddings.
content_column str 'document' The name of the column to store the main text content.
metadata_column str 'cmetadata' The name of the JSONB column for metadata.
metadata_filters Optional[Dict[str, Any]] None Optional dict of JSONB metadata filters used to scope the upsert delete-and-insert. When provided, matching rows are deleted before the new documents are inserted.
**kwargs {}

Method PgVectorStore.get_distance_strategy

Return the appropriate distance expression based on the metric or configured strategy.

get_distance_strategy(embedding_column_obj, query_embedding, metric: str = None) -> Any

Parameter Type Default Description
embedding_column_obj The SQLAlchemy column object for embeddings
query_embedding The query embedding vector
metric str None Optional metric string ('COSINE', 'L2', 'IP', 'DOT') - if None, uses self.distance_strategy

Returns: Any

Method PgVectorStore.similarity_search

Perform similarity search with optional threshold filtering.

By default, parent rows (is_full_document=True or document_type='parent'/'parent_chunk') are excluded from the candidate set (FEAT-128). Pass include_parents=True to restore the legacy behaviour where all rows are returned.

Returns: List of SearchResult objects with content, metadata, score, collection_id, and record_id

similarity_search(query: str, table: str = None, schema: str = None, k: Optional[int] = None, limit: int = None, metadata_filters: Optional[Dict[str, Any]] = None, score_threshold: Optional[float] = None, metric: str = None, embedding_column: str = 'embedding', content_column: str = 'document', metadata_column: str = 'cmetadata', id_column: str = 'id', additional_columns: Optional[List[str]] = None, include_parents: bool = False) -> List[SearchResult]

Parameter Type Default Description
query str The search query text
table str None Table name (optional, uses default if not provided)
schema str None Schema name (optional, uses default if not provided)
k Optional[int] None
limit int None Maximum number of results to return
metadata_filters Optional[Dict[str, Any]] None Dictionary of metadata filters to apply
score_threshold Optional[float] None Maximum distance threshold results with distance > threshold will be filtered out)
metric str None Distance metric to use ('COSINE', 'L2', 'IP')
embedding_column str 'embedding' Name of the embedding column
content_column str 'document' Name of the content column
metadata_column str 'cmetadata' Name of the metadata column
id_column str 'id' Name of the ID column
additional_columns Optional[List[str]] None List of additional columns to include in results.
include_parents bool False

Returns: List[SearchResult]

Method PgVectorStore.get_vector

get_vector(metric_type: str = None, **kwargs)

Parameter Type Default Description
metric_type str None
**kwargs {}

Method PgVectorStore.drop_collection

Drops the specified table in the given schema.

drop_collection(table: str, schema: str = 'public') -> None

Parameter Type Default Description
table str The name of the table to drop.
schema str 'public' The database schema where the table resides.

Method PgVectorStore.prepare_embedding_table

Prepare a Postgres Table as an embedding table in PostgreSQL with advanced features. This method prepares a table with the following columns:

  • id: unique identifier (String)
  • embedding: the vector column (Vector(dimension) or JSONB)
  • document: text column containing the document
  • collection_id: UUID column for collection identification.
  • metadata: JSONB column for metadata
  • Additional columns based on the provided columns list
  • Enhanced indexing strategies for efficient querying
  • Support for multiple distance strategies (COSINE, L2, IP, etc.) Args:
  • tablename (str): Name of the table to create.
  • embedding_column (str): Name of the column for storing embeddings.
  • document_column (str): Name of the column for storing document text.
  • metadata_column (str): Name of the column for storing metadata.
  • dimension (int): Dimension of the embedding vector.
  • id_column (str): Name of the column for storing unique identifiers.
  • use_jsonb (bool): Whether to use JSONB for metadata storage.
  • drop_columns (bool): Whether to drop existing columns.
  • create_all_indexes (bool): Whether to create all distance strategies.

prepare_embedding_table(table: str, schema: str = 'public', conn: AsyncEngine = None, id_column: str = 'id', embedding_column: str = 'embedding', document_column: str = 'document', metadata_column: str = 'cmetadata', dimension: int = 768, colbert_dimension: int = 128, use_jsonb: bool = True, drop_columns: bool = False, create_all_indexes: bool = True, **kwargs)

Parameter Type Default Description
table str
schema str 'public'
conn AsyncEngine None
id_column str 'id'
embedding_column str 'embedding'
document_column str 'document'
metadata_column str 'cmetadata'
dimension int 768
colbert_dimension int 128
use_jsonb bool True
drop_columns bool False
create_all_indexes bool True
**kwargs {}

Method PgVectorStore.create_embedding_table

Create an embedding table in PostgreSQL with advanced features. This method creates a table with the following columns:

  • id: unique identifier (String)
  • embedding: the vector column (Vector(dimension) or JSONB)
  • document: text column containing the document
  • cmetadata: JSONB column for metadata
  • Additional columns based on the provided columns list
  • Enhanced indexing strategies for efficient querying
  • Support for multiple distance strategies (COSINE, L2, IP, etc.) Args:
  • table (str): Name of the table to create.
  • columns (List[str]): List of column names to include in the table.
  • schema (str): Database schema where the table will be created.
  • embedding_column (str): Name of the column for storing embeddings.
  • document_column (str): Name of the column for storing document text.
  • metadata_column (str): Name of the column for storing metadata.
  • dimension (int): Dimension of the embedding vector.
  • id_column (str): Name of the column for storing unique identifiers.
  • use_jsonb (bool): Whether to use JSONB for metadata storage.
  • drop_columns (bool): Whether to drop existing columns.
  • create_all_indexes (bool): Whether to create all distance strategies.

Enhanced embedding table creation with JSONB strategy for better semantic search.

This approach creates multiple document representations:

  1. Primary search content (emphasizing store ID)
  2. Location-based content
  3. Structured metadata for filtering
  4. Multiple embedding variations

create_embedding_table(table: str, columns: List[str], schema: str = 'public', embedding_column: str = 'embedding', document_column: str = 'document', metadata_column: str = 'cmetadata', dimension: int = None, id_column: str = 'id', use_jsonb: bool = False, drop_columns: bool = True, create_all_indexes: bool = True, **kwargs)

Parameter Type Default Description
table str
columns List[str]
schema str 'public'
embedding_column str 'embedding'
document_column str 'document'
metadata_column str 'cmetadata'
dimension int None
id_column str 'id'
use_jsonb bool False
drop_columns bool True
create_all_indexes bool True
**kwargs {}

Method PgVectorStore.add_colbert_document

Add a document with ColBERT token embeddings to the specified table.

add_colbert_document(document_id: str, content: str, token_embeddings: np.ndarray, table: str, schema: str = 'public', metadata: Optional[Dict[str, Any]] = None, document_column: str = 'document', metadata_column: str = 'cmetadata', id_column: str = 'id', **kwargs) -> None

Parameter Type Default Description
document_id str Unique identifier for the document
content str The document text content
token_embeddings np.ndarray NumPy array of token embeddings (shape: [num_tokens, embedding_dim])
table str The name of the table
schema str 'public' The database schema where the table resides
metadata Optional[Dict[str, Any]] None Optional metadata dictionary
document_column str 'document' Name of the document content column
metadata_column str 'cmetadata' Name of the metadata column
id_column str 'id' Name of the ID column
**kwargs {}

Method PgVectorStore.colbert_search

Perform ColBERT search with late interaction using MaxSim scoring.

colbert_search(query_tokens: np.ndarray, table: str, schema: str = 'public', top_k: int = 10, metadata_filters: Optional[Dict[str, Any]] = None, min_tokens: Optional[int] = None, max_tokens: Optional[int] = None, id_column: str = 'id', document_column: str = 'document', metadata_column: str = 'cmetadata', additional_columns: Optional[List[str]] = None) -> List[SearchResult]

Parameter Type Default Description
query_tokens np.ndarray NumPy array of query token embeddings (shape: [num_query_tokens, embedding_dim])
table str Table name
schema str 'public' Schema name
top_k int 10 Number of results to return
metadata_filters Optional[Dict[str, Any]] None Optional metadata filters
min_tokens Optional[int] None Minimum number of tokens in documents to consider
max_tokens Optional[int] None Maximum number of tokens in documents to consider
id_column str 'id' Name of the ID column
document_column str 'document' Name of the document content column
metadata_column str 'cmetadata' Name of the metadata column
additional_columns Optional[List[str]] None Additional columns to include in results

Returns: List[SearchResult] — List of SearchResult objects ordered by ColBERT score (descending)

Method PgVectorStore.hybrid_search

Perform hybrid search combining dense embeddings and ColBERT token matching.

hybrid_search(query: str, query_tokens: Optional[np.ndarray] = None, table: str = None, schema: str = None, top_k: int = 10, dense_weight: float = 0.7, colbert_weight: float = 0.3, metadata_filters: Optional[Dict[str, Any]] = None, **kwargs) -> List[SearchResult]

Parameter Type Default Description
query str Text query
query_tokens Optional[np.ndarray] None Optional pre-computed query token embeddings
table str None Table name
schema str None Schema name
top_k int 10 Number of final results
dense_weight float 0.7 Weight for dense similarity scores (0-1)
colbert_weight float 0.3 Weight for ColBERT scores (0-1)
metadata_filters Optional[Dict[str, Any]] None Metadata filters to apply
**kwargs {}

Returns: List[SearchResult] — List of SearchResult objects with combined scores

Method PgVectorStore.mmr_search

Perform Maximal Marginal Relevance (MMR) search to balance relevance and diversity.

MMR helps avoid redundant results by selecting documents that are relevant to the query but diverse from each other.

By default, parent rows are excluded from the candidate set (FEAT-128). Pass include_parents=True to restore legacy behaviour.

mmr_search(query: str, table: str = None, schema: str = None, k: int = 10, fetch_k: int = None, lambda_mult: float = 0.5, metadata_filters: Optional[Dict[str, Any]] = None, score_threshold: Optional[float] = None, metric: str = None, embedding_column: str = 'embedding', content_column: str = 'document', metadata_column: str = 'cmetadata', id_column: str = 'id', additional_columns: Optional[List[str]] = None, include_parents: bool = False) -> List[SearchResult]

Parameter Type Default Description
query str The search query text
table str None Table name (optional, uses default if not provided)
schema str None Schema name (optional, uses default if not provided)
k int 10 Number of final results to return
fetch_k int None Number of candidate documents to fetch (default: k * 3)
lambda_mult float 0.5 MMR diversity parameter (0-1): - 1.0 = pure relevance (no diversity) - 0.0 = pure diversity (no relevance) - 0.5 = balanced (default)
metadata_filters Optional[Dict[str, Any]] None Dictionary of metadata filters to apply
score_threshold Optional[float] None Maximum distance threshold for initial candidates
metric str None Distance metric to use ('COSINE', 'L2', 'IP')
embedding_column str 'embedding' Name of the embedding column
content_column str 'document' Name of the content column
metadata_column str 'cmetadata' Name of the metadata column
id_column str 'id' Name of the ID column
additional_columns Optional[List[str]] None Additional columns to include in results
include_parents bool False When True, include parent rows in the candidate set (bypasses FEAT-128 default filter).

Returns: List[SearchResult] — List of SearchResult objects selected via MMR algorithm

Method PgVectorStore.delete_documents

Delete documents from the vector store based on metadata field values.

delete_documents(documents: Optional[List[Document]] = None, pk: str = 'source_type', values: Optional[Union[str, List[str]]] = None, table: Optional[str] = None, schema: Optional[str] = None, metadata_column: Optional[str] = None, **kwargs) -> int

Parameter Type Default Description
documents Optional[List[Document]] None List of documents whose metadata values will be used for deletion. If provided, the pk field values will be extracted from these documents.
pk str 'source_type' The metadata field name to use for deletion (default: 'source_type')
values Optional[Union[str, List[str]]] None Specific values to delete. Can be a single string or list of strings. If provided, this takes precedence over extracting from documents.
table Optional[str] None Override table name
schema Optional[str] None Override schema name
metadata_column Optional[str] None Override metadata column name
**kwargs {}

Returns: int — Number of documents deleted

Method PgVectorStore.delete_documents_by_filter

Delete documents based on multiple metadata field conditions.

delete_documents_by_filter(filter_dict: Dict[str, Union[str, List[str]]], table: Optional[str] = None, schema: Optional[str] = None, metadata_column: Optional[str] = None, **kwargs) -> int

Parameter Type Default Description
filter_dict Dict[str, Union[str, List[str]]] Dictionary of field_name: value(s) pairs for deletion criteria
table Optional[str] None Override table name
schema Optional[str] None Override schema name
metadata_column Optional[str] None Override metadata column name
**kwargs {}

Returns: int — Number of documents deleted

Method PgVectorStore.delete_all_documents

Delete ALL documents from the vector store table.

WARNING: This will delete all data in the table!

delete_all_documents(table: Optional[str] = None, schema: Optional[str] = None, confirm: bool = False, **kwargs) -> int

Parameter Type Default Description
table Optional[str] None Override table name
schema Optional[str] None Override schema name
confirm bool False Must be set to True to proceed with deletion
**kwargs {}

Returns: int — Number of documents deleted

Method PgVectorStore.delete_documents_by_ids

Delete documents by their IDs.

delete_documents_by_ids(document_ids: List[str], table: Optional[str] = None, schema: Optional[str] = None, id_column: Optional[str] = None, **kwargs) -> int

Parameter Type Default Description
document_ids List[str] List of document IDs to delete
table Optional[str] None Override table name
schema Optional[str] None Override schema name
id_column Optional[str] None Override ID column name
**kwargs {}

Returns: int — Number of documents deleted

Method PgVectorStore.count_documents_by_filter

Count documents that would be affected by a filter (useful before deletion).

count_documents_by_filter(filter_dict: Dict[str, Union[str, List[str]]], table: Optional[str] = None, schema: Optional[str] = None, metadata_column: Optional[str] = None, **kwargs) -> int

Parameter Type Default Description
filter_dict Dict[str, Union[str, List[str]]] Dictionary of field_name: value(s) pairs for criteria
table Optional[str] None Override table name
schema Optional[str] None Override schema name
metadata_column Optional[str] None Override metadata column name
**kwargs {}

Returns: int — Number of documents matching the filter

Method PgVectorStore.from_documents

Add documents using late chunking strategy.

from_documents(documents: List[Document], table: str = None, schema: str = None, embedding_column: str = 'embedding', content_column: str = 'document', metadata_column: str = 'cmetadata', chunk_size: int = 8192, chunk_overlap: int = 200, store_full_document: bool = True, **kwargs) -> Dict[str, Any]

Parameter Type Default Description
documents List[Document] List of Document objects to process
table str None Table name
schema str None Schema name
embedding_column str 'embedding' Name of embedding column
content_column str 'document' Name of content column
metadata_column str 'cmetadata' Name of metadata column
chunk_size int 8192 Maximum size of each chunk
chunk_overlap int 200 Overlap between chunks
store_full_document bool True Whether to store full document alongside chunks
**kwargs {}

Returns: Dict[str, Any] — Dictionary with processing statistics

Method PgVectorStore.document_search

Search with late chunking context awareness.

document_search(query: str, table: str = None, schema: str = None, limit: int = 10, search_chunks: bool = True, search_full_docs: bool = False, rerank_with_context: bool = True, context_window: int = 2, **kwargs) -> List[SearchResult]

Parameter Type Default Description
query str Search query
table str None Table name
schema str None Schema name
limit int 10 Number of results
search_chunks bool True Whether to search chunk-level embeddings
search_full_docs bool False Whether to search full document embeddings
rerank_with_context bool True Whether to rerank using surrounding chunks
context_window int 2 Number of adjacent chunks to include for context
**kwargs {}

Returns: List[SearchResult] — List of SearchResult objects with enhanced context

Method PgVectorStore.collection_exists

Check if a collection (table) exists in the database.

collection_exists(table: str, schema: str = 'public') -> bool

Parameter Type Default Description
table str Name of the table to check
schema str 'public' Schema name (default: 'public')

Returns: bool — True if the collection exists, False otherwise

Method PgVectorStore.delete_collection

Delete a collection (table) from the database.

delete_collection(table: str, schema: str = 'public') -> None

Parameter Type Default Description
table str Name of the table to delete
schema str 'public' Schema name (default: 'public')

Raises:

  • RuntimeError — If the collection does not exist or deletion fails

Method PgVectorStore.create_collection

Create a new collection (table) in the database.

create_collection(table: str, schema: str = 'public', dimension: int = 768, index_type: str = 'COSINE', metric_type: str = 'L2', id_column: Optional[str] = None, **kwargs) -> None

Parameter Type Default Description
table str Name of the table to create
schema str 'public' Schema name (default: 'public')
dimension int 768 Embedding dimension (default: 768)
index_type str 'COSINE' Type of index to create (default: "COSINE")
metric_type str 'L2' Distance metric type (default: 'L2')
id_column Optional[str] None Name of the ID column (default: 'id')
**kwargs {}

Raises:

  • RuntimeError — If collection creation fails

Alias SearchResult

Re-exported from parrot.stores.models.SearchResult.

Alias default_sqlalchemy_pg

Re-exported from parrot.conf.default_sqlalchemy_pg.

Function vector_distance

vector_distance(embedding_column, vector, op)

Parameter Type Default Description
embedding_column
vector
op

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally