Implementation:24kchengYe MemoMind insert facts batch
| Knowledge Sources | |
|---|---|
| Domains | Database, Data_Storage |
| Last Updated | 2026-10-28 00:00 GMT |
Overview
Concrete tool for batch-inserting processed facts into the PostgreSQL memory_units table using unnest-based array insertion with search vector population.
Description
The insert_facts_batch function inserts multiple ProcessedFact objects into the memory_units table in a single SQL query. It uses PostgreSQL's `unnest` to pass all column values as arrays, then `INSERT ... SELECT FROM unnest(...) RETURNING id` to insert atomically and retrieve the generated UUIDs.
Key features:
- Text sanitization: cleans fact text and context before insertion
- Temporal field mapping: event_date falls back to occurred_start or mentioned_at
- Confidence scoring: opinion facts get confidence_score=1.0; others get None
- Tag handling: tags passed as JSON strings, converted to varchar[] via jsonb_array_elements_text
- Text signals: builds entity names + date tokens for enriched BM25 indexing
- Search vector: populated via tokenize() for VectorChord, or GENERATED ALWAYS for native PostgreSQL
Usage
Import this function when you need to persist extracted, embedded, and entity-resolved facts into the database. It is called by the retain orchestrator as the storage stage.
Code Reference
Source Location
- Repository: MemoMind
- File: engine/hindsight_api/engine/retain/fact_storage.py
- Lines: L20-175
Signature
async def insert_facts_batch(
conn,
bank_id: str,
facts: list[ProcessedFact],
document_id: str | None = None,
) -> list[str]:
Import
from hindsight_api.engine.retain.fact_storage import insert_facts_batch
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| conn | asyncpg.Connection | Yes | Database connection |
| bank_id | str | Yes | Bank identifier |
| facts | list[ProcessedFact] | Yes | Facts with text, embedding, temporal fields, entities, metadata, tags |
| document_id | str | No | Optional document association |
Outputs
| Name | Type | Description |
|---|---|---|
| unit_ids | list[str] | UUID strings for inserted memory_units rows |
Usage Examples
Batch Inserting Facts
import asyncio
from hindsight_api.engine.retain.fact_storage import insert_facts_batch
async def main():
# processed_facts: list[ProcessedFact] with all fields populated
unit_ids = await insert_facts_batch(
conn=conn,
bank_id="default",
facts=processed_facts,
document_id="doc-123",
)
print(f"Inserted {len(unit_ids)} facts: {unit_ids[:3]}...")
asyncio.run(main())