Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: correct API mismatches in pipeline, ingest, and vector_store docs

KaifAhmad1689d57b361be
diff --git a/docs/reference/ingest.md b/docs/reference/ingest.md
index b5f984ec..af0c9e52 100644
--- a/docs/reference/ingest.md
+++ b/docs/reference/ingest.md
@@ -22,10 +22,10 @@ icon: "database"
Real-time ingestion from Kafka, RabbitMQ, AWS Kinesis, and Apache Pulsar.
</Card>
<Card title="Cloud Storage" icon="cloud">
- S3Ingestor, GCSIngestor, and GDriveIngestor with authentication options.
+ `CloudStorageIngestor` — unified client for AWS S3, Google Cloud Storage, and Azure Blob Storage.
</Card>
<Card title="Database Ingestors" icon="database">
- DBIngestor, SnowflakeIngestor, MongoIngestor, and DuckDBIngestor.
+ `DBIngestor` (SQL via SQLAlchemy) and `SnowflakeIngestor` for data warehouse queries.
</Card>
</CardGroup>
@@ -61,18 +61,25 @@ icon: "database"
</Step>
<Step title="Feed sources into the pipeline">
```python
- from semantica.pipeline import Pipeline
+ from semantica.pipeline import PipelineBuilder, ExecutionEngine
from semantica.parse import DocumentParser
from semantica.semantic_extract import NERExtractor
from semantica.llms import Groq
- llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))
+ llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))
+ ingestor = FileIngestor()
+ parser = DocumentParser()
+ extractor = NERExtractor(method="llm", llm_provider=llm)
- pipeline = Pipeline()
- pipeline.add_step("ingest", FileIngestor())
- pipeline.add_step("parse", DocumentParser())
- pipeline.add_step("extract", NERExtractor(method="llm", llm_provider=llm))
- result = pipeline.run("data/")
+ builder = PipelineBuilder()
+ builder.add_step("ingest", "file_ingest", handler=ingestor.ingest_file)
+ builder.add_step("parse", "document_parse", handler=parser.parse)
+ builder.add_step("extract", "ner_extract", handler=extractor.extract)
+ builder.connect_steps("ingest", "parse")
+ builder.connect_steps("parse", "extract")
+
+ pipeline = builder.build("my_pipeline")
+ result = ExecutionEngine().execute_pipeline(pipeline, data="data/")
```
</Step>
</Steps>
@@ -213,54 +220,40 @@ icon: "database"
```
</Tab>
<Tab title="Cloud Storage">
- ### S3Ingestor
+ ### CloudStorageIngestor
- Ingest files directly from AWS S3 buckets:
+ `CloudStorageIngestor` is a unified client for AWS S3, Google Cloud Storage, and Azure Blob Storage:
```python
- from semantica.ingest import S3Ingestor
+ from semantica.ingest import CloudStorageIngestor
import os
- ingestor = S3Ingestor(
+ # AWS S3
+ ingestor = CloudStorageIngestor(
+ provider="s3",
bucket="my-documents-bucket",
prefix="reports/2024/",
region="us-east-1",
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
- # Or omit credentials to use IAM instance profile
+ # Omit credentials to use IAM instance profile / environment variables
)
sources = ingestor.ingest()
- sources = ingestor.ingest(pattern="**/*.pdf")
- ```
-
- ### GCSIngestor
-
- Ingest files from Google Cloud Storage:
- ```python
- from semantica.ingest import GCSIngestor
-
- ingestor = GCSIngestor(
+ # Google Cloud Storage
+ ingestor = CloudStorageIngestor(
+ provider="gcs",
bucket="my-gcs-bucket",
prefix="data/",
credentials_file="gcp-credentials.json", # or use ADC
)
sources = ingestor.ingest()
- ```
-
- ### GDriveIngestor
- Ingest files from Google Drive folders via OAuth 2.0:
-
- ```python
- from semantica.ingest import GDriveIngestor
-
- ingestor = GDriveIngestor(
- credentials_file="oauth_credentials.json",
- token_file="token.json",
- folder_id="1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs9",
- file_types=["pdf", "docx", "txt"],
- recursive=True,
+ # Azure Blob Storage
+ ingestor = CloudStorageIngestor(
+ provider="azure",
+ container="documents",
+ connection_string=os.getenv("AZURE_STORAGE_CONNECTION_STRING"),
)
sources = ingestor.ingest()
```
@@ -295,47 +288,6 @@ icon: "database"
sources = ingestor.ingest(query="SELECT * FROM documents")
```
- ### MongoIngestor
-
- Ingest documents from MongoDB collections:
-
- ```python
- from semantica.ingest import MongoIngestor
- import os
-
- ingestor = MongoIngestor(
- connection_string=os.getenv("MONGO_URI"),
- database="mydb",
- collection="articles",
- query={"status": "published", "year": {"$gte": 2022}},
- projection={"title": 1, "body": 1, "author": 1},
- content_field="body",
- limit=10000,
- )
- sources = ingestor.ingest()
- ```
-
- ### DuckDBIngestor
-
- Ingest data from DuckDB databases or directly from Parquet/CSV files via DuckDB SQL:
-
- ```python
- from semantica.ingest import DuckDBIngestor
-
- # In-memory DuckDB — query a Parquet file directly
- ingestor = DuckDBIngestor(
- query="SELECT id, text, created_at FROM read_parquet('data/*.parquet') WHERE year >= 2023",
- )
- sources = ingestor.ingest()
-
- # Persistent DuckDB database file
- ingestor = DuckDBIngestor(
- database_path="analytics.duckdb",
- query="SELECT doc_id AS id, content, metadata FROM documents",
- content_field="content",
- )
- sources = ingestor.ingest()
- ```
</Tab>
<Tab title="Stream">
### StreamIngestor
@@ -459,7 +411,7 @@ method_registry.register("file", "my_format", my_ingestor)
</Tip>
<Tip>
- **All ingestors return the same `DataSource` schema.** This means you can mix sources in a single pipeline without any adapter code — `FileIngestor`, `MongoIngestor`, and `StreamIngestor` outputs are all directly composable with `DocumentParser` and `NERExtractor`.
+ **All ingestors return the same `DataSource` schema.** This means you can mix sources in a single pipeline without any adapter code — `FileIngestor`, `DBIngestor`, and `StreamIngestor` outputs are all directly composable with `DocumentParser` and `NERExtractor`.
</Tip>
<CardGroup cols={2}>
diff --git a/docs/reference/pipeline.md b/docs/reference/pipeline.md
index a1a3c90c..b461cbf6 100644
--- a/docs/reference/pipeline.md
+++ b/docs/reference/pipeline.md
@@ -40,9 +40,9 @@ You could wire Semantica modules together with plain Python code. Pipelines add:
## Quick Start
<Steps>
- <Step title="Create a pipeline and add steps">
+ <Step title="Build a pipeline">
```python
- from semantica.pipeline import Pipeline
+ from semantica.pipeline import PipelineBuilder
from semantica.ingest import FileIngestor
from semantica.parse import DocumentParser
from semantica.semantic_extract import NERExtractor
@@ -52,11 +52,21 @@ You could wire Semantica modules together with plain Python code. Pipelines add:
llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))
- pipeline = Pipeline()
- pipeline.add_step("ingest", FileIngestor())
- pipeline.add_step("parse", DocumentParser())
- pipeline.add_step("extract", NERExtractor(method="llm", llm_provider=llm))
- pipeline.add_step("build_kg", GraphBuilder(merge_entities=True))
+ ingestor = FileIngestor()
+ parser = DocumentParser()
+ extractor = NERExtractor(method="llm", llm_provider=llm)
+ kg_builder = GraphBuilder(merge_entities=True)
+
+ builder = PipelineBuilder()
+ builder.add_step("ingest", "file_ingest", handler=ingestor.ingest_file)
+ builder.add_step("parse", "document_parse", handler=parser.parse)
+ builder.add_step("extract", "ner_extract", handler=extractor.extract)
+ builder.add_step("build_kg", "graph_build", handler=kg_builder.build)
+ builder.connect_steps("ingest", "parse")
+ builder.connect_steps("parse", "extract")
+ builder.connect_steps("extract","build_kg")
+
+ pipeline = builder.build("my_pipeline")
```
</Step>
<Step title="Validate before running">
@@ -66,36 +76,46 @@ You could wire Semantica modules together with plain Python code. Pipelines add:
validator = PipelineValidator()
result = validator.validate_pipeline(pipeline)
- if not result.is_valid:
- for error in result.errors:
- print(f"Error: {error.message} (step: {error.step})")
+ if not result.valid:
+ for error in result.errors: # errors is List[str]
+ print(f"Error: {error}")
+ for warning in result.warnings:
+ print(f"Warning: {warning}")
```
</Step>
- <Step title="Run and inspect results">
+ <Step title="Execute and inspect results">
```python
- result = pipeline.run("data/", show_progress=True)
+ from semantica.pipeline import ExecutionEngine
+
+ engine = ExecutionEngine()
+ result = engine.execute_pipeline(pipeline, data="data/")
kg = result.output
- print(f"Processed: {result.processed_count}")
- print(f"Failed: {result.failed_count}")
- print(f"Duration: {result.duration_seconds:.1f}s")
+ print(f"Success: {result.success}")
+ print(f"Steps executed: {result.metrics['steps_executed']}")
+ print(f"Steps failed: {result.metrics['steps_failed']}")
+ print(f"Duration: {result.metrics['execution_time']:.1f}s")
```
</Step>
</Steps>
## Parallel Processing
-Process documents concurrently across multiple workers:
+Set parallelism on the builder and pass `max_workers` to `ExecutionEngine`:
```python
-pipeline = Pipeline(workers=4)
-
-pipeline.add_step("ingest", FileIngestor())
-pipeline.add_step("parse", DocumentParser())
-pipeline.add_step("extract", NERExtractor(), parallel=True, batch_size=10)
-pipeline.add_step("build", GraphBuilder())
-
-result = pipeline.run("data/")
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+
+builder = PipelineBuilder()
+builder.add_step("ingest", "file_ingest", handler=ingestor.ingest_file)
+builder.add_step("parse", "document_parse", handler=parser.parse)
+builder.add_step("extract", "ner_extract", handler=extractor.extract)
+builder.add_step("build", "graph_build", handler=kg_builder.build)
+builder.set_parallelism(4)
+
+pipeline = builder.build("parallel_pipeline")
+engine = ExecutionEngine(max_workers=4)
+result = engine.execute_pipeline(pipeline, data="data/")
```
## Retry and Error Handling
@@ -103,26 +123,31 @@ result = pipeline.run("data/")
<Tabs>
<Tab title="Exponential backoff (recommended)">
```python
- from semantica.pipeline import RetryPolicy, FailureHandler, Pipeline
+ from semantica.pipeline import RetryPolicy, RetryStrategy, FailureHandler, ExecutionEngine
- retry = RetryPolicy(
+ policy = RetryPolicy(
max_retries=3,
- backoff="exponential",
- initial_delay=1.0 # 1s → 2s → 4s
+ strategy=RetryStrategy.EXPONENTIAL,
+ initial_delay=1.0, # 1s → 2s → 4s
+ backoff_factor=2.0
)
- handler = FailureHandler(strategy="skip", log_failures=True)
+ handler = FailureHandler()
+ handler.retry_policies["ner_extract"] = policy # keyed by step_type
- pipeline = Pipeline(retry_policy=retry, failure_handler=handler)
+ engine = ExecutionEngine(default_max_retries=3, default_backoff_factor=2.0)
+ result = engine.execute_pipeline(pipeline, data="data/")
```
Best for transient API errors and rate limits — waits longer with each retry, giving upstream services time to recover.
</Tab>
<Tab title="Linear backoff">
```python
- retry = RetryPolicy(
+ from semantica.pipeline import RetryPolicy, RetryStrategy
+
+ policy = RetryPolicy(
max_retries=3,
- backoff="linear",
+ strategy=RetryStrategy.LINEAR,
initial_delay=2.0 # 2s → 4s → 6s
)
```
@@ -131,10 +156,12 @@ result = pipeline.run("data/")
</Tab>
<Tab title="Fixed backoff">
```python
- retry = RetryPolicy(
+ from semantica.pipeline import RetryPolicy, RetryStrategy
+
+ policy = RetryPolicy(
max_retries=5,
- backoff="fixed",
- initial_delay=1.0 # 1s → 1s → 1s → 1s → 1s
+ strategy=RetryStrategy.FIXED,
+ initial_delay=1.0 # 1s every attempt
)
```
@@ -159,58 +186,97 @@ result = pipeline.run("data/")
<Tabs>
<Tab title="Console (tqdm)">
```python
- result = pipeline.run("data/", show_progress=True)
+ from semantica.pipeline import ExecutionEngine
+
+ engine = ExecutionEngine()
+ result = engine.execute_pipeline(pipeline, data="data/")
+ # The progress tracker outputs tqdm bars to the console during execution
```
- Displays a live tqdm progress bar in the terminal. Best for scripts and CLI tools.
+ Displays a live progress bar in the terminal via Semantica's built-in progress tracker. Best for scripts and CLI tools.
</Tab>
- <Tab title="WebSocket (Explorer)">
+ <Tab title="Live status check">
```python
- result = pipeline.run("data/", websocket_port=8080)
+ from semantica.pipeline import ExecutionEngine
+ import threading, time
+
+ engine = ExecutionEngine()
+
+ # Run in a background thread, poll progress from main thread
+ def run():
+ engine.execute_pipeline(pipeline, data="data/")
+
+ t = threading.Thread(target=run, daemon=True)
+ t.start()
+
+ while t.is_alive():
+ progress = engine.get_progress(pipeline.name)
+ if progress:
+ print(f" {progress['completed_steps']}/{progress['total_steps']} steps — {progress['status']}")
+ time.sleep(2)
```
- Streams progress events to Knowledge Explorer's dashboard. Best for long-running production jobs where you want a live web UI.
+ Poll `get_progress()` for live status during execution.
</Tab>
</Tabs>
## Pipeline DSL
-`PipelineBuilder` provides a fluent chain syntax that reads as a data flow:
+`PipelineBuilder` uses `add_step(name, type, **config)` and `connect_steps(from, to)` to define a DAG:
```python
-from semantica.pipeline import PipelineBuilder
-
-pipeline = (
- PipelineBuilder()
- .ingest(FileIngestor())
- .parse(DocumentParser())
- .normalize()
- .extract(NERExtractor(method="llm", llm_provider=llm))
- .extract_relations(RelationExtractor(method="llm", llm_provider=llm))
- .build_kg(merge_entities=True)
- .deduplicate(strategy="semantic_v2")
- .export(format="turtle", path="output.ttl")
- .build()
-)
-
-result = pipeline.run("data/")
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+
+builder = PipelineBuilder()
+
+# Add steps — step_type is a string label, handler is the callable invoked at runtime
+builder.add_step("ingest", "file_ingest", handler=ingestor.ingest_file)
+builder.add_step("parse", "document_parse", handler=parser.parse)
+builder.add_step("normalize", "text_normalize", handler=normalizer.normalize)
+builder.add_step("extract", "ner_extract", handler=extractor.extract)
+builder.add_step("rel_extract", "rel_extract", handler=rel_extractor.extract)
+builder.add_step("build_kg", "graph_build", handler=kg_builder.build)
+builder.add_step("deduplicate", "dedup", handler=deduplicator.deduplicate)
+builder.add_step("export", "rdf_export", handler=exporter.export, format="turtle", path="output.ttl")
+
+# Wire the data flow
+builder.connect_steps("ingest", "parse")
+builder.connect_steps("parse", "normalize")
+builder.connect_steps("normalize", "extract")
+builder.connect_steps("extract", "rel_extract")
+builder.connect_steps("rel_extract", "build_kg")
+builder.connect_steps("build_kg", "deduplicate")
+builder.connect_steps("deduplicate", "export")
+
+pipeline = builder.build("full_pipeline")
+result = ExecutionEngine().execute_pipeline(pipeline, data="data/")
```
-## Save and Load Pipelines
+## Serialize and Restore Pipelines
-Serialize a pipeline to YAML for reproducible runs across environments:
+`PipelineSerializer` converts a pipeline to JSON or dict for storage and reloads it later:
```python
-# Save pipeline configuration
-pipeline.save("pipeline_config.yaml")
+from semantica.pipeline import PipelineSerializer
+
+serializer = PipelineSerializer()
+
+# Serialize to JSON string
+json_str = serializer.serialize_pipeline(pipeline, format="json")
-# Load and run on any machine
-pipeline = Pipeline.load("pipeline_config.yaml")
-result = pipeline.run("data/")
+# Save to file
+with open("pipeline_config.json", "w") as f:
+ f.write(json_str)
+
+# Restore on any machine and execute
+with open("pipeline_config.json") as f:
+ restored = serializer.deserialize_pipeline(f.read())
+
+result = ExecutionEngine().execute_pipeline(restored, data="data/")
```
<Tip>
- `pipeline.save()` preserves exact component configurations — LLM model names, retry policies, thresholds — everything. Without it, you can't guarantee that a re-run 3 months later uses the same settings.
+ Serialized pipelines capture step names, types, and config — but not handler functions (callables can't be serialized). Re-register handlers on the restored steps before executing.
</Tip>
## Pre-Built Templates
@@ -280,26 +346,29 @@ Fine-grained control over pipeline execution — pause, resume, cancel, and insp
```python
from semantica.pipeline import ExecutionEngine
-engine = ExecutionEngine(config={"timeout_seconds": 300, "max_workers": 4})
+engine = ExecutionEngine(max_workers=4)
+# pipeline.name is the pipeline ID used for all control operations
result = engine.execute_pipeline(pipeline, data="data/")
+pipeline_id = pipeline.name # e.g. "my_pipeline"
+
# Pause after the current step finishes
-engine.pause_pipeline(result.pipeline_id)
+engine.pause_pipeline(pipeline_id)
-progress = engine.get_progress(result.pipeline_id)
-print(f"Completed: {progress['completed']}/{progress['total']}")
-print(f"Current step: {progress['current_step']}")
+progress = engine.get_progress(pipeline_id)
+print(f"Completed: {progress['completed_steps']}/{progress['total_steps']}")
+print(f"Status: {progress['status']}")
-engine.resume_pipeline(result.pipeline_id)
-engine.stop_pipeline(result.pipeline_id)
+engine.resume_pipeline(pipeline_id)
+engine.stop_pipeline(pipeline_id)
```
| Method | Returns | Description |
| ------ | ------- | ----------- |
| `execute_pipeline(pipeline, data)` | `ExecutionResult` | Execute pipeline from start to finish |
-| `get_status(pipeline_id)` | `PipelineStatus` | Current state (RUNNING, PAUSED, STOPPED) |
-| `get_progress(pipeline_id)` | `Dict` | Step completion counts and elapsed time |
+| `get_pipeline_status(pipeline_id)` | `PipelineStatus` | Current state (RUNNING, PAUSED, STOPPED) |
+| `get_progress(pipeline_id)` | `Dict` | `completed_steps`, `total_steps`, `progress_percentage`, `status` |
| `pause_pipeline(pipeline_id)` | `None` | Suspend after current step completes |
| `resume_pipeline(pipeline_id)` | `None` | Resume from paused state |
| `stop_pipeline(pipeline_id)` | `None` | Cancel and clean up immediately |
@@ -314,12 +383,12 @@ from semantica.pipeline import PipelineValidator
validator = PipelineValidator()
result = validator.validate_pipeline(pipeline)
-if result.is_valid:
+if result.valid:
print("Pipeline is valid — safe to run")
else:
- for error in result.errors:
- print(f"Error: {error.message} (step: {error.step})")
- for warning in result.warnings:
+ for error in result.errors: # errors is List[str]
+ print(f"Error: {error}")
+ for warning in result.warnings: # warnings is List[str]
print(f"Warning: {warning}")
```
@@ -363,16 +432,15 @@ Checks performed:
Prevents memory oversubscription on large runs:
```python
-from semantica.pipeline import ResourceScheduler
+from semantica.pipeline import ResourceScheduler, ExecutionEngine
scheduler = ResourceScheduler()
+engine = ExecutionEngine()
-resources = scheduler.allocate_resources(
- pipeline, max_memory_gb=8, max_workers=4
-)
+resources = scheduler.allocate_resources(pipeline)
try:
- result = pipeline.run("data/")
+ result = engine.execute_pipeline(pipeline, data="data/")
finally:
scheduler.release_resources(resources)
```
@@ -382,23 +450,38 @@ finally:
Re-process only data that has changed since the last run:
```python
-pipeline = Pipeline()
-pipeline.add_step(
- "ingest", FileIngestor(),
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+
+builder = PipelineBuilder()
+
+# delta_mode=True tells ExecutionEngine to compute the diff between two snapshots
+# and pass only changed triples to this step's handler
+builder.add_step(
+ "ingest", "file_ingest",
+ handler=ingestor.ingest_file,
delta_mode=True, base_version_id="v1", target_version_id="v2"
)
-pipeline.add_step(
- "extract", NERExtractor(),
+builder.add_step(
+ "extract", "ner_extract",
+ handler=extractor.extract,
delta_mode=True, base_version_id="v1", target_version_id="v2"
)
-pipeline.add_step(
- "build", GraphBuilder(),
+builder.add_step(
+ "build", "graph_build",
+ handler=kg_builder.build,
delta_mode=False # always rebuild the merged graph
)
-
-result = pipeline.run("data/")
-print(f"Delta documents processed: {result.metadata.get('delta_count', 0)}")
-print(f"Skipped (unchanged): {result.metadata.get('skipped_count', 0)}")
+builder.connect_steps("ingest", "extract")
+builder.connect_steps("extract", "build")
+
+pipeline = builder.build("delta_pipeline")
+engine = ExecutionEngine()
+result = engine.execute_pipeline(
+ pipeline,
+ data="data/",
+ version_manager=version_manager, # required for delta mode
+ triplet_store=triplet_store # required for delta mode
+)
```
<Note>
@@ -408,18 +491,25 @@ print(f"Skipped (unchanged): {result.metadata.get('skipped_count', 0)}")
## Schemas
<AccordionGroup>
- <Accordion title="PipelineResult schema">
+ <Accordion title="ExecutionResult schema">
```python
@dataclass
-class PipelineResult:
- output: Any # final step output (e.g., a KnowledgeGraph)
- processed_count: int # documents successfully processed
- failed_count: int # documents that failed after retries
- duration_seconds: float # total wall-clock time
- step_metrics: Dict # per-step timing and counts
- errors: List # list of FailedDocument records
- metadata: Dict # pipeline-level metadata (delta_count, etc.)
+class ExecutionResult:
+ success: bool # True if all steps completed without failure
+ output: Any # output from the final pipeline step
+ metadata: Dict[str, Any] # {"pipeline_id": "...", "execution_time": 1.23}
+ metrics: Dict[str, Any] # {"steps_executed": 4, "steps_failed": 0, "execution_time": 1.23}
+ errors: List[str] # error messages from failed steps (empty on full success)
+
+# Access pattern
+result.success # bool
+result.output # final step output
+result.metadata["pipeline_id"] # pipeline name used as ID
+result.metadata["execution_time"] # total wall-clock seconds
+result.metrics["steps_executed"] # count of successfully completed steps
+result.metrics["steps_failed"] # count of failed steps
+result.errors # List[str] of error messages
```
</Accordion>
@@ -476,7 +566,7 @@ StepStatus.SKIPPED # Skipped due to FailureHandler "skip" strategy
</Tip>
<Tip>
- **Inspect `result.step_metrics` to find bottlenecks.** Each step reports its own duration and document count. If embedding is 10x slower than NER, that's where to optimize — increase `batch_size`, switch to a faster embedding model, or parallelize with GPU.
+ **Inspect `result.metrics` to find bottlenecks.** `result.metrics['steps_executed']` and `result.metrics['execution_time']` give a quick read on overall pipeline health. For per-step timing, check `step.result` on each `PipelineStep` after the run.
</Tip>
<CardGroup cols={2}>
diff --git a/docs/reference/vector_store.md b/docs/reference/vector_store.md
index 166bb364..9dee3169 100644
--- a/docs/reference/vector_store.md
+++ b/docs/reference/vector_store.md
@@ -45,30 +45,39 @@ icon: "database"
</Step>
<Step title="Add vectors">
```python
- store.add_vectors(
- embeddings=embeddings,
- ids=["doc1", "doc2"],
+ # Add text documents (auto-embedded)
+ ids = store.add_documents(
+ documents=["text one", "text two"],
+ metadata=[{"title": "Document 1"}, {"title": "Document 2"}]
+ )
+
+ # Add pre-computed vectors
+ ids = store.store_vectors(
+ vectors=[embedding1, embedding2],
metadata=[{"title": "Document 1"}, {"title": "Document 2"}]
)
```
</Step>
<Step title="Search by semantic similarity">
```python
- results = store.search(query_vector, top_k=10)
+ # Search by text query (auto-embeds the query)
+ results = store.search("machine learning", limit=10)
+
+ # Search by pre-computed vector
+ results = store.search_vectors(query_vector, k=10)
+
for r in results:
print(f"{r['id']} — score: {r['score']:.3f}")
- print(f" metadata: {r['metadata']}")
```
</Step>
<Step title="Filter results by metadata">
```python
- # Equality, range, and set filters
- results = store.search(query_vector, filters={
- "$and": [
- {"category": "research"},
- {"year": {"$gte": 2022}}
- ]
- })
+ from semantica.vector_store import HybridSearch, MetadataFilter
+
+ mf = MetadataFilter().eq("category", "research").gt("year", 2022)
+
+ search = HybridSearch(vector_store=store)
+ results = search.search(query=query_vector, k=10, metadata_filter=mf)
```
</Step>
</Steps>
@@ -161,65 +170,96 @@ See the [PgVector Guide](../vector_stores/pgvector) for full setup.
## Hybrid Search
-Combine vector similarity with keyword/metadata filters for higher precision:
+Use `HybridSearch` with a `MetadataFilter` to combine vector similarity with metadata conditions:
```python
-results = store.hybrid_search(
- query_vector=query_embedding,
- query_text="machine learning", # keyword component
- top_k=10,
- alpha=0.7, # 0.0 = keyword only, 1.0 = vector only
- filters={"category": "research", "year": {"$gte": 2022}}
+from semantica.vector_store import HybridSearch, MetadataFilter
+
+mf = (
+ MetadataFilter()
+ .eq("category", "research")
+ .gt("year", 2022)
)
+
+search = HybridSearch(vector_store=store)
+results = search.search(
+ query=query_vector, # np.ndarray or query string (auto-embedded)
+ k=10,
+ metadata_filter=mf
+)
+
+for r in results:
+ print(f"{r['id']} — score: {r['score']:.3f} metadata: {r['metadata']}")
```
## Metadata Filtering
+`MetadataFilter` supports chained conditions — all conditions are ANDed:
+
```python
-# Equality
-results = store.search(query_vector, filters={"author": "John Smith"})
-
-# Range
-results = store.search(query_vector, filters={"date": {"$gte": "2023-01-01"}})
-
-# Set membership
-results = store.search(query_vector, filters={"tag": {"$in": ["ai", "ml"]}})
-
-# Compound AND
-results = store.search(query_vector, filters={
- "$and": [
- {"category": "research"},
- {"year": {"$gte": 2022}}
- ]
-})
+from semantica.vector_store import MetadataFilter
+
+mf = MetadataFilter().eq("author", "John Smith") # equality
+mf = MetadataFilter().ne("status", "archived") # not equal
+mf = MetadataFilter().gt("year", 2022).lte("year", 2024) # range
+mf = MetadataFilter().in_list("tag", ["ai", "ml"]) # set membership
+mf = MetadataFilter().contains("title", "neural") # substring / list contains
+
+# Multiple conditions — all must match (AND)
+mf = (
+ MetadataFilter()
+ .eq("category", "research")
+ .gt("year", 2022)
+ .contains("title", "language model")
+)
```
## Namespace Isolation
-Isolate vectors per tenant, project, or use case:
+Use `NamespaceManager` to assign vectors to named namespaces for multi-tenant isolation:
```python
-store = VectorStore(backend="faiss", dimension=768)
+from semantica.vector_store import NamespaceManager, VectorStore
-# Write to separate namespaces
-store.add_vectors(embeddings_a, ids_a, namespace="tenant_a")
-store.add_vectors(embeddings_b, ids_b, namespace="tenant_b")
+store = VectorStore(backend="faiss", dimension=768)
+ns_manager = NamespaceManager()
-# Search is scoped to the specified namespace
-results = store.search(query_vector, namespace="tenant_a")
+ns_manager.create_namespace("tenant_a", description="Customer A data")
+ns_manager.create_namespace("tenant_b", description="Customer B data")
+
+# Store vectors, then assign them to a namespace
+ids_a = store.store_vectors(embeddings_a, metadata=metadata_a)
+for vid in ids_a:
+ ns_manager.add_vector_to_namespace(vid, "tenant_a")
+
+# List all namespace names
+for name in ns_manager.list_namespaces():
+ print(name)
+
+ns_manager.delete_namespace("tenant_a")
```
## Batch Operations
```python
-# Batch add — automatically chunked for memory efficiency
-store.add_vectors_batch(embeddings_list, ids_list, batch_size=1000)
+# Batch add text documents — chunked automatically by batch_size
+ids = store.add_documents(
+ documents=large_doc_list,
+ metadata=large_meta_list,
+ batch_size=1000
+)
+
+# Batch add pre-computed vectors
+ids = store.store_vectors(vectors=embeddings_list, metadata=meta_list)
-# Batch delete
-store.delete_vectors(ids=["doc1", "doc2", "doc3"])
+# Delete by vector ID list
+store.delete_vectors(vector_ids=["vec_0", "vec_1", "vec_2"])
-# Update metadata without re-embedding
-store.update_metadata("doc1", {"status": "archived", "reviewed": True})
+# Replace vectors (re-embed then update)
+store.update_vectors(
+ vector_ids=["vec_0"],
+ new_vectors=[new_embedding]
+)
```
## Backend Comparison
@@ -236,79 +276,87 @@ store.update_metadata("doc1", {"status": "archived", "reviewed": True})
## HybridSearch
-`HybridSearch` is the low-level class behind `store.hybrid_search()` — use it directly when you need custom result fusion logic:
+`HybridSearch` combines vector similarity with metadata filtering, and can fuse results from multiple sources:
```python
-from semantica.vector_store import HybridSearch, VectorStore
-
-store = VectorStore(backend="faiss", dimension=768)
-hybrid = HybridSearch(vector_store=store)
-
-results = hybrid.search(
- query_vector=query_embedding,
- query_text="machine learning frameworks",
- top_k=20,
- vector_weight=0.7, # weight for vector similarity leg
- keyword_weight=0.3, # weight for BM25/keyword leg
- fusion="rrf", # "rrf" (Reciprocal Rank Fusion) | "weighted_avg"
- filters={"category": "research", "year": {"$gte": 2022}},
- deduplicate=True,
+from semantica.vector_store import HybridSearch, MetadataFilter, SearchRanker
+
+# Single-source search with metadata filter
+search = HybridSearch(vector_store=store)
+mf = MetadataFilter().eq("category", "research").gt("year", 2022)
+
+results = search.search(
+ query=query_vector, # np.ndarray or query string
+ k=10,
+ metadata_filter=mf
)
-for r in results:
- print(f"{r['id']} vector_score={r['vector_score']:.3f} final_score={r['score']:.3f}")
+# Multi-source fusion (RRF across multiple stores)
+sources = [
+ {"vectors": v1, "metadata": m1, "ids": ids1},
+ {"vectors": v2, "metadata": m2, "ids": ids2},
+]
+fused = search.multi_source_search(query_vector, sources, k=10)
+
+# Custom fusion strategy
+ranker = SearchRanker(strategy="reciprocal_rank_fusion") # or "weighted_average"
+fused = ranker.rank([results_list_1, results_list_2], k=60)
```
| Fusion strategy | Description |
| --------------- | ----------- |
-| `rrf` | Reciprocal Rank Fusion — rank-based combination, robust to score scale differences |
-| `weighted_avg` | Weighted average of normalised scores — requires `vector_weight` + `keyword_weight` = 1.0 |
+| `reciprocal_rank_fusion` | Rank-based combination via RRF constant `k=60` — robust to score scale differences |
+| `weighted_average` | Weighted average of scores — pass `weights=[0.7, 0.3]` to `rank()` |
## MetadataStore
-`MetadataStore` manages structured metadata attached to vectors — query by field values without a vector:
+`MetadataStore` indexes structured metadata and lets you query by field values without a vector:
```python
from semantica.vector_store import MetadataStore
meta_store = MetadataStore()
-meta_store.register_schema({
- "author": "str",
- "year": "int",
- "category": "str",
- "score": "float",
-})
+# Define schema fields
+meta_store.add_field("author", str, required=True)
+meta_store.add_field("year", int, required=True)
+meta_store.add_field("category", str)
+meta_store.add_field("score", float, default=0.0)
+
+# Store and retrieve metadata
+meta_store.store_metadata("doc1", {"author": "Alice", "year": 2024, "category": "research"})
+meta_store.store_metadata("doc2", {"author": "Bob", "year": 2023, "category": "review"})
-meta_store.add("doc1", {"author": "Alice", "year": 2024, "category": "research"})
-meta_store.add("doc2", {"author": "Bob", "year": 2023, "category": "review"})
+# Query — returns List[str] of matching vector IDs
+ids = meta_store.query_metadata({"category": "research", "year": 2024})
-results = meta_store.filter({"category": "research", "year": {"$gte": 2023}})
-meta = meta_store.get("doc1")
-meta_store.update("doc1", {"score": 0.92})
+# Get and update metadata for a specific vector
+meta = meta_store.get_metadata("doc1")
+meta_store.update_metadata("doc1", {"score": 0.92})
```
## NamespaceManager
-Isolates vector collections per tenant, project, or model version:
+Assigns vector IDs to named namespaces for multi-tenant or multi-model isolation:
```python
-from semantica.vector_store import NamespaceManager, VectorStore
+from semantica.vector_store import NamespaceManager
-base_store = VectorStore(backend="faiss", dimension=768)
-ns_manager = NamespaceManager(vector_store=base_store)
+ns_manager = NamespaceManager()
ns_manager.create_namespace("tenant_a", description="Customer A data")
ns_manager.create_namespace("tenant_b", description="Customer B data")
-ns_manager.add_vectors("tenant_a", embeddings_a, ids_a, metadata_a)
-ns_manager.add_vectors("tenant_b", embeddings_b, ids_b, metadata_b)
+# Assign vector IDs to a namespace after storing them
+for vid in ids_a:
+ ns_manager.add_vector_to_namespace(vid, "tenant_a")
-# Search is scoped — tenant_a never sees tenant_b's data
-results = ns_manager.search("tenant_a", query_vector, top_k=10)
+# Inspect namespaces
+for name in ns_manager.list_namespaces(): # returns List[str]
+ print(name)
-for ns in ns_manager.list_namespaces():
- print(f"{ns['name']}: {ns['vector_count']} vectors")
+# Look up which namespace a vector belongs to
+ns = ns_manager.get_vector_namespace("vec_0")
ns_manager.delete_namespace("tenant_a")
```