Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor triplet_store: Unified TripletStore interface, removed Virtuoso/TripletManager, added Blazegraph/Jena/RDF4J support, updated docs and notebooks

KaifAhmad138962d3d7a09
diff --git a/README.md b/README.md
index b027bace..6ef20746 100644
--- a/README.md
+++ b/README.md
@@ -325,6 +325,28 @@ print(f"Nodes: {kg.node_count}, Answer: {result.answer}")
[**Graph Analytics**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/10_Graph_Analytics.ipynb) • [**Advanced Graph Analytics**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb)
+### Triplet Store Integration
+
+> **SPARQL Support** • **Blazegraph, Jena, RDF4J** • **Reasoning & Inference**
+
+```python
+from semantica.triplet_store import TripletStore
+
+# Initialize store (Blazegraph, Jena, or RDF4J)
+store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
+
+# Add triplets and execute SPARQL queries
+store.add_triplet({
+ "subject": "http://example.org/Alice",
+ "predicate": "http://example.org/knows",
+ "object": "http://example.org/Bob"
+})
+
+results = store.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10")
+```
+
+[**Cookbook: Triplet Store**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/20_Triplet_Store.ipynb)
+
### Ontology Generation & Management
> **6-Stage LLM Pipeline** • Automatic OWL Generation • HermiT/Pellet Validation
diff --git a/cookbook/advanced/11_Advanced_Context_Engineering.ipynb b/cookbook/advanced/11_Advanced_Context_Engineering.ipynb
index d86b017f..bb4544fc 100644
--- a/cookbook/advanced/11_Advanced_Context_Engineering.ipynb
+++ b/cookbook/advanced/11_Advanced_Context_Engineering.ipynb
@@ -28,20 +28,47 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"id": "583f944a",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
+ ]
+ }
+ ],
"source": [
- "!pip install semantica"
+ "!pip install -q semantica"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"id": "70fbd8c1",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
+ " from tqdm.autonotebook import tqdm, trange\n",
+ "WARNING:semantica.text_embedder:fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n",
+ "INFO:semantica.embedding_generator:Embedding generator initialized\n"
+ ]
+ }
+ ],
"source": [
"import logging\n",
"from typing import List, Dict, Any, Optional\n",
@@ -74,10 +101,247 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"id": "6edbdd77",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div style='font-family: monospace;'><h4>🧠 Semantica - 📊 Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>✅</td><td>Semantica is processing</td><td>🔗 context</td><td>AgentMemory</td><td>-</td><td>0.03s</td></tr><tr><td>✅</td><td>Semantica is embedding</td><td>💾 embeddings</td><td>TextEmbedder</td><td>-</td><td>0.01s</td></tr><tr><td>✅</td><td>Semantica is indexing</td><td>📊 vector_store</td><td>VectorStore</td><td>-</td><td>0.00s</td></tr><tr><td>✅</td><td>Semantica is processing</td><td>🔗 context</td><td>ContextRetriever</td><td>-</td><td>0.04s</td></tr></table></div>"
+ ],
+ "text/plain": [
+ "<IPython.core.display.HTML object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: IMPORTANT: User's name is Alice...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: IMPORTANT: User's name is Alice...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_e8b0a654c836\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 0 Filler memory 0 Filler memory 0 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 0 Filler memory 0 Filler memory 0 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_deccca2296ee\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 1 Filler memory 1 Filler memory 1 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 1 Filler memory 1 Filler memory 1 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_22ca52874df8\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 2 Filler memory 2 Filler memory 2 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 2 Filler memory 2 Filler memory 2 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_5fd99ffa6ad5\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 3 Filler memory 3 Filler memory 3 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 3 Filler memory 3 Filler memory 3 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_63383a5a0e76\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 4 Filler memory 4 Filler memory 4 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 4 Filler memory 4 Filler memory 4 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_02bd0002e646\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 5 Filler memory 5 Filler memory 5 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 5 Filler memory 5 Filler memory 5 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_7d23cf82ca5d\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 6 Filler memory 6 Filler memory 6 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 6 Filler memory 6 Filler memory 6 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_e3d129ba801a\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 7 Filler memory 7 Filler memory 7 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 7 Filler memory 7 Filler memory 7 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_67c45bc0eb04\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 8 Filler memory 8 Filler memory 8 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 8 Filler memory 8 Filler memory 8 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_063ab85e5808\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 9 Filler memory 9 Filler memory 9 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 9 Filler memory 9 Filler memory 9 Fi...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_b5150f8a3a01\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 10 Filler memory 10 Filler memory 10...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 10 Filler memory 10 Filler memory 10...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_20d87ab406c4\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 11 Filler memory 11 Filler memory 11...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 11 Filler memory 11 Filler memory 11...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_a080f384c8a2\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 12 Filler memory 12 Filler memory 12...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 12 Filler memory 12 Filler memory 12...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_0ed9d0fb154e\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 13 Filler memory 13 Filler memory 13...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 13 Filler memory 13 Filler memory 13...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_f1c9e96ea5e0\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 14 Filler memory 14 Filler memory 14...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 14 Filler memory 14 Filler memory 14...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_72ce868f6c7d\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 15 Filler memory 15 Filler memory 15...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 15 Filler memory 15 Filler memory 15...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_003c8beb510d\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 16 Filler memory 16 Filler memory 16...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 16 Filler memory 16 Filler memory 16...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_43eb17a5f19c\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 17 Filler memory 17 Filler memory 17...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 17 Filler memory 17 Filler memory 17...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_120154aec687\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 18 Filler memory 18 Filler memory 18...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 18 Filler memory 18 Filler memory 18...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_082b2183bf74\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Storing memory: Filler memory 19 Filler memory 19 Filler memory 19...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Generating embedding...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Filler memory 19 Filler memory 19 Filler memory 19...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing 1 vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Storing vectors...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Updating vector index...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Stored 1 vectors\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Stored memory: mem_d28088da8577\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Short-term items count: 5\n",
+ "First item (should be the important one): IMPORTANT: User's name is Alice\n"
+ ]
+ }
+ ],
"source": [
"class ImportanceAwareMemory(AgentMemory):\n",
" def _prune_short_term_memory(self) -> None:\n",
@@ -148,10 +412,18 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"id": "62cb840c",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Available graph methods: {'graph': ['entities_relationships', 'conversations', 'hybrid', 'star_builder']}\n"
+ ]
+ }
+ ],
"source": [
"def star_graph_builder(\n",
" entities: Optional[List[Dict[str, Any]]] = None,\n",
@@ -199,10 +471,19 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 5,
"id": "6a324b97",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Created graph with 5 nodes and 4 edges.\n",
+ "Edges sample: {'source_id': 'center', 'target_id': 'sat_0', 'type': 'connects_to'}\n"
+ ]
+ }
+ ],
"source": [
"# Build a graph using our custom method\n",
"graph_data = methods.build_context_graph(\n",
@@ -233,10 +514,44 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 6,
"id": "9752dec4",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: ContextRetriever | Message: Retrieving context for: Python...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: ContextRetriever | Message: Retrieving from vector store...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: ContextRetriever | Message: Retrieving from knowledge graph...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: ContextRetriever | Message: Retrieving from memory...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Retrieving memories for: Python...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Searching vector store...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Generating text embedding: Python...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: embeddings | Submodule: TextEmbedder | Message: Using fallback embedding method...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: embeddings | Submodule: TextEmbedder | Message: Generated embedding (dim: 16)\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Searching for 20 similar vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: vector_store | Submodule: VectorStore | Message: Performing similarity search...\n",
+ "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:480: RuntimeWarning: invalid value encountered in divide\n",
+ " similarities = np.dot(vectors, query_vector) / (vector_norms * query_norm)\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: vector_store | Submodule: VectorStore | Message: Found 20 similar vectors\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Performing keyword search...\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: AgentMemory | Message: Ranking results...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: AgentMemory | Message: Retrieved 0 memories\n",
+ "INFO:semantica.progress:[RUNNING] | Module: context | Submodule: ContextRetriever | Message: Ranking and merging results...\n",
+ "INFO:semantica.progress:[COMPLETED] | Module: context | Submodule: ContextRetriever | Message: Retrieved 1 results\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Found 1 results.\n",
+ "Source: graph:python, Score: 1.00, Content: Python...\n"
+ ]
+ }
+ ],
"source": [
"# Populate knowledge graph with some test data\n",
"kg.add_node(\"python\", \"concept\", \"Python\")\n",
@@ -292,7 +607,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.8.10"
+ "version": "3.11.9"
}
},
"nbformat": 4,
diff --git a/cookbook/advanced/Advanced_Triplet_Store.ipynb b/cookbook/advanced/Advanced_Triplet_Store.ipynb
new file mode 100644
index 00000000..e00a4f1c
--- /dev/null
+++ b/cookbook/advanced/Advanced_Triplet_Store.ipynb
@@ -0,0 +1,173 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Advanced Triplet Store Guide\n",
+ "\n",
+ "This guide explores the advanced capabilities of the Semantica Triplet Store module, focusing on RDF data management, SPARQL querying, and multi-backend support (Blazegraph, Jena, RDF4J).\n",
+ "\n",
+ "## Key Features\n",
+ "- Unified interface for Blazegraph, Jena, and RDF4J\n",
+ "- Bulk loading with progress tracking\n",
+ "- SPARQL query execution and optimization\n",
+ "- Transaction support (backend-dependent)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.triplet_store import TripletStore\n",
+ "from semantica.semantic_extract.triplet_extractor import Triplet"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Initialization\n",
+ "\n",
+ "Initialize the Triplet Store with your preferred backend."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Blazegraph store\n",
+ "store = TripletStore(\n",
+ " backend=\"blazegraph\",\n",
+ " endpoint=\"http://localhost:9999/blazegraph\"\n",
+ ")\n",
+ "\n",
+ "# Or Jena\n",
+ "# store = TripletStore(backend=\"jena\", endpoint=\"http://localhost:3030/ds\")\n",
+ "\n",
+ "# Or RDF4J\n",
+ "# store = TripletStore(backend=\"rdf4j\", endpoint=\"http://localhost:8080/rdf4j-server/repositories/myrepo\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Adding Triplets\n",
+ "\n",
+ "Add individual triplets or batch load them."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Single triplet\n",
+ "triplet = Triplet(\n",
+ " subject=\"http://example.org/Alice\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/Bob\"\n",
+ ")\n",
+ "\n",
+ "store.add_triplet(triplet)\n",
+ "\n",
+ "# Bulk load\n",
+ "triplets = [\n",
+ " Triplet(\n",
+ " subject=\"http://example.org/Bob\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/Charlie\"\n",
+ " ),\n",
+ " Triplet(\n",
+ " subject=\"http://example.org/Charlie\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/Alice\"\n",
+ " )\n",
+ "]\n",
+ "\n",
+ "result = store.add_triplets(triplets, batch_size=100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. SPARQL Querying\n",
+ "\n",
+ "Execute SPARQL queries to retrieve data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "query = \"\"\"\n",
+ "SELECT ?s ?p ?o\n",
+ "WHERE {\n",
+ " ?s ?p ?o\n",
+ "}\n",
+ "LIMIT 10\n",
+ "\"\"\"\n",
+ "\n",
+ "results = store.execute_query(query)\n",
+ "for result in results.get(\"results\", {}).get(\"bindings\", []):\n",
+ " print(result)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Deleting and Updating\n",
+ "\n",
+ "Manage triplet lifecycle."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "store.delete_triplet(triplet)\n",
+ "\n",
+ "# Update is delete + add\n",
+ "new_triplet = Triplet(\n",
+ " subject=\"http://example.org/Alice\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/David\"\n",
+ ")\n",
+ "store.update_triplet(triplet, new_triplet)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/cookbook/introduction/19_Context_Module.ipynb b/cookbook/introduction/19_Context_Module.ipynb
index bdbeffbe..6c6639c0 100644
--- a/cookbook/introduction/19_Context_Module.ipynb
+++ b/cookbook/introduction/19_Context_Module.ipynb
@@ -21,6 +21,32 @@
"This notebook focuses on small, runnable examples and keeps imports scoped to each cell."
]
},
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "257bad40",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
+ ]
+ }
+ ],
+ "source": [
+ "!pip install -q semantica"
+ ]
+ },
{
"cell_type": "markdown",
"id": "a48e0f10",
@@ -33,10 +59,31 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"id": "8c845a94",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
+ " from tqdm.autonotebook import tqdm, trange\n",
+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n",
+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "('inmemory', 384)"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.vector_store import VectorStore\n",
"\n",
@@ -60,10 +107,25 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"id": "f4d788b5",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'retention_days': 30,\n",
+ " 'max_memories': 10000,\n",
+ " 'use_graph_expansion': True,\n",
+ " 'max_expansion_hops': 2,\n",
+ " 'hybrid_alpha': 0.5}"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.context import AgentContext, ContextGraph\n",
"\n",
@@ -85,10 +147,38 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"id": "5d65eb00",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div style='font-family: monospace;'><h4>🧠 Semantica - 📊 Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>✅</td><td>Semantica is processing</td><td>🔗 context</td><td>AgentMemory</td><td>-</td><td>0.01s</td></tr><tr><td>✅</td><td>Semantica is embedding</td><td>💾 embeddings</td><td>TextEmbedder</td><td>-</td><td>0.00s</td></tr><tr><td>✅</td><td>Semantica is indexing</td><td>📊 vector_store</td><td>VectorStore</td><td>-</td><td>0.00s</td></tr><tr><td>✅</td><td>Semantica is processing</td><td>🔗 context</td><td>ContextRetriever</td><td>-</td><td>0.02s</td></tr><tr><td>✅</td><td>Semantica is processing</td><td>🔗 context</td><td>EntityLinker</td><td>-</td><td>0.00s</td></tr></table></div>"
+ ],
+ "text/plain": [
+ "<IPython.core.display.HTML object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": [
+ "{'id': None,\n",
+ " 'content': 'User prefers short answers about Python.',\n",
+ " 'timestamp': '2025-12-18T20:46:17.265703',\n",
+ " 'metadata': {'type': 'preference',\n",
+ " 'conversation_id': 'conv_1',\n",
+ " 'user_id': 'user_1'}}"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"memory_id = context.store(\n",
" \"User prefers short answers about Python.\",\n",
@@ -102,10 +192,35 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 5,
"id": "3c1be718",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:480: RuntimeWarning: invalid value encountered in divide\n",
+ " similarities = np.dot(vectors, query_vector) / (vector_norms * query_norm)\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "[{'content': 'User prefers short answers about Python.',\n",
+ " 'score': 1.0,\n",
+ " 'source': 'short_term',\n",
+ " 'metadata': {'type': 'preference',\n",
+ " 'conversation_id': 'conv_1',\n",
+ " 'user_id': 'user_1'},\n",
+ " 'related_entities': []}]"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"context.store(\n",
" \"User is working on Semantica context module examples.\",\n",
@@ -119,10 +234,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 6,
"id": "485acf33",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[]"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"context.conversation(\"conv_1\", max_items=10)"
]
@@ -139,10 +265,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 7,
"id": "a264ef4d",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'{\\n \"exported_at\": \"2025-12-18T20:46:27.455602\",\\n \"count\": 2,\\n \"memories\": [\\n {\\n \"memory_id\": \"mem_5c7dba9a7373\",\\n \"content\": \"User prefers short answers about Python.\",\\n \"timestamp\": \"2025-12-18T20:46:17.265703\",\\n \"metadata\": {\\n \"type\": \"preference\",\\n \"convers'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"export_json = context.export(conversation_id=\"conv_1\", format=\"json\")\n",
"export_json[:300]"
@@ -150,10 +287,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 8,
"id": "b62d1859",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'conversation_id': 'conv_1',\n",
+ " 'message_count': 0,\n",
+ " 'first_message': None,\n",
+ " 'last_message': None}"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"import tempfile\n",
"\n",
@@ -176,10 +327,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 9,
"id": "72930ae7",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'stored_count': 2,\n",
+ " 'memory_ids': ['mem_b467da01b18a', 'mem_e3dbd310355d'],\n",
+ " 'graph_nodes': 0,\n",
+ " 'graph_edges': 0}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"documents = [\n",
" {\n",
@@ -250,20 +415,54 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 10,
"id": "df2e5fcd",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[{'node': {'id': 'e_ml',\n",
+ " 'type': 'CONCEPT',\n",
+ " 'properties': {'content': 'Machine Learning',\n",
+ " 'id': 'e_ml',\n",
+ " 'text': 'Machine Learning',\n",
+ " 'type': 'CONCEPT'}},\n",
+ " 'score': 1.0,\n",
+ " 'content': 'Machine Learning'}]"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"kg.query(\"machine learning\")"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 11,
"id": "0836feeb",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[{'id': 'e_ml',\n",
+ " 'type': 'CONCEPT',\n",
+ " 'content': 'Machine Learning',\n",
+ " 'relationship': 'used_for',\n",
+ " 'weight': 0.9,\n",
+ " 'hop': 1}]"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"kg.get_neighbors(\"e_python\", hops=2)"
]
@@ -280,10 +479,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 12,
"id": "24b011c0",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('e1', 'https://semantica.dev/entity/python#programming_language', 1),\n",
+ " ('e2', 'https://semantica.dev/entity/pytorch#framework', 0)]"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.context import EntityLinker\n",
"\n",
@@ -300,10 +511,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 13,
"id": "a282de3a",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[EntityLink(source_entity_id='e1', target_entity_id='e_py', link_type='same_as', confidence=1.0, source=None, metadata={'similarity': 1.0}),\n",
+ " EntityLink(source_entity_id='e1', target_entity_id='e2', link_type='related_to', confidence=0.8, source=None, metadata={})]"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"linker.link_entities(\"e1\", \"e2\", link_type=\"related_to\", confidence=0.8)\n",
"linker.get_entity_links(\"e1\")[:2]"
@@ -331,10 +554,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 14,
"id": "3791d6c6",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('Python powers Semantica.', 'short_term', 1.0),\n",
+ " ('Python', 'graph:e_python', 0.5)]"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.context import AgentMemory, ContextRetriever\n",
"\n",
@@ -359,10 +594,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 15,
"id": "896e7001",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'7_days'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.context.config import context_config\n",
"\n",
@@ -372,10 +618,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 16,
"id": "e925a2e0",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'graph': ['entities_relationships', 'conversations', 'hybrid', 'custom_demo']}"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"from semantica.context.methods import build_context_graph\n",
"from semantica.context.registry import method_registry\n",
@@ -393,10 +650,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 17,
"id": "21fa6cb3",
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'nodes': [], 'edges': [], 'statistics': {'node_count': 0, 'edge_count': 0}}"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"build_context_graph(\n",
" entities=[{\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"}],\n",
@@ -413,8 +681,16 @@
"name": "python3"
},
"language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
"name": "python",
- "version": "3.11"
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.9"
}
},
"nbformat": 4,
diff --git a/cookbook/introduction/20_Triplet_Store.ipynb b/cookbook/introduction/20_Triplet_Store.ipynb
index 94a3d8e3..5bedd7be 100644
--- a/cookbook/introduction/20_Triplet_Store.ipynb
+++ b/cookbook/introduction/20_Triplet_Store.ipynb
@@ -4,53 +4,19 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triplet_Store.ipynb)\n",
+ "# Getting Started with Triplet Store\n",
"\n",
- "# Triplet Store - Comprehensive Guide\n",
+ "This notebook introduces the **Semantica Triplet Store** module, which allows you to store and query knowledge graph data using industry-standard RDF Triple Stores.\n",
"\n",
- "## Overview\n",
+ "## What is a Triplet Store?\n",
"\n",
- "This notebook provides a **comprehensive walkthrough** of Semantica's triplet_store module, demonstrating RDF triplet storage, SPARQL querying, and multi-backend support for knowledge graph persistence.\n",
+ "A Triplet Store (or RDF Store) is a database optimized for storing and retrieving triples: **Subject - Predicate - Object**.\n",
+ "For example: `Alice` (Subject) `knows` (Predicate) `Bob` (Object).\n",
"\n",
- "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/triplet_store/)\n",
- "\n",
- "### Learning Objectives\n",
- "\n",
- "By the end of this notebook, you will be able to:\n",
- "\n",
- "- Register and manage triplet stores (Blazegraph, Jena, RDF4J, Virtuoso)\n",
- "- Perform CRUD operations on RDF triplets\n",
- "- Execute SPARQL queries with optimization\n",
- "- Use bulk loading for large datasets\n",
- "- Work with multiple store backends\n",
- "- Validate and track triplet operations\n",
- "- Choose the right backend for your use case\n",
- "\n",
- "### What You'll Learn\n",
- "\n",
- "| Component | Purpose | When to Use |\n",
- "|-----------|---------|-------------|\n",
- "| `TripletManager` | Store coordination | All triplet operations |\n",
- "| `QueryEngine` | SPARQL execution | Query optimization |\n",
- "| `BulkLoader` | High-volume loading | Large datasets |\n",
- "| `BlazegraphStore` | Blazegraph backend | High performance |\n",
- "| `JenaStore` | Jena backend | Java integration |\n",
- "| `RDF4JStore` | RDF4J backend | Transaction support |\n",
- "| `VirtuosoStore` | Virtuoso backend | Enterprise scale |\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n",
- "\n",
- "Install Semantica from PyPI:\n",
- "\n",
- "```bash\n",
- "pip install semantica\n",
- "# Or with all optional dependencies:\n",
- "pip install semantica[all]\n",
- "```\n",
- "\n",
- "---"
+ "Semantica supports:\n",
+ "- **Blazegraph** (Default, High Performance)\n",
+ "- **Apache Jena** (Great for inference)\n",
+ "- **RDF4J** (Standard Java framework)"
]
},
{
@@ -59,23 +25,20 @@
"metadata": {},
"outputs": [],
"source": [
- "!pip install semantica\n"
+ "# Import the TripletStore class\n",
+ "from semantica.triplet_store import TripletStore\n",
+ "from semantica.semantic_extract.triplet_extractor import Triplet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 1: Basic Triplet Store Operations\n",
+ "## 1. Connecting to a Store\n",
"\n",
- "Let's start with the `TripletManager` for basic triplet store operations.\n",
+ "To use the Triplet Store, you need a backend running. In this example, we assume a Blazegraph instance is running locally.\n",
"\n",
- "### What is TripletManager?\n",
- "\n",
- "`TripletManager` is the main coordinator for triplet store operations:\n",
- "- **Store Registration**: Register multiple backends\n",
- "- **CRUD Operations**: Add, get, update, delete triplets\n",
- "- **Multi-Store**: Manage multiple stores simultaneously"
+ "> **Note:** If you don't have a store running, the code below shows how you *would* connect."
]
},
{
@@ -84,53 +47,23 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import TripletManager\n",
- "from semantica.semantic_extract.triplet_extractor import Triplet\n",
- "\n",
- "# Create triplet manager\n",
- "manager = TripletManager()\n",
- "\n",
- "# Register a Blazegraph store (in-memory for demo)\n",
- "store = manager.register_store(\n",
- " store_id=\"demo\",\n",
- " store_type=\"blazegraph\",\n",
- " endpoint=\"http://localhost:9999/blazegraph/sparql\"\n",
+ "# Connect to a Blazegraph instance\n",
+ "# You can also use backend=\"jena\" or backend=\"rdf4j\"\n",
+ "store = TripletStore(\n",
+ " backend=\"blazegraph\",\n",
+ " endpoint=\"http://localhost:9999/blazegraph\"\n",
")\n",
"\n",
- "print(f\"Registered store: {store.store_id}\")\n",
- "print(f\"Store type: {store.store_type}\")\n",
- "print(f\"Endpoint: {store.endpoint}\")\n",
- "\n",
- "# Create a triplet\n",
- "triplet = Triplet(\n",
- " subject=\"http://example.org/Alice\",\n",
- " predicate=\"http://example.org/knows\",\n",
- " object=\"http://example.org/Bob\",\n",
- " confidence=0.95\n",
- ")\n",
- "\n",
- "# Add triplet to store\n",
- "result = manager.add_triplet(triplet, store_id=\"demo\")\n",
- "print(f\"\\nTriplet added: {result['success']}\")\n",
- "print(f\"Triplet: {triplet.subject} -> {triplet.predicate} -> {triplet.object}\")"
+ "print(f\"Connected to {store.backend_type} store\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 2: Store Registration and Management\n",
- "\n",
- "Register multiple stores and manage them.\n",
+ "## 2. Creating Triplets\n",
"\n",
- "### Supported Backends\n",
- "\n",
- "| Backend | Best For | Performance | Features |\n",
- "|---------|----------|-------------|----------|\n",
- "| **Blazegraph** | Large datasets | Excellent | GPU acceleration, full-text |\n",
- "| **Jena** | Java apps | Good | SHACL, inference |\n",
- "| **RDF4J** | Transactions | Good | ACID, federation |\n",
- "| **Virtuoso** | Enterprise | Excellent | SQL integration, clustering |"
+ "We use the `Triplet` class to define our data."
]
},
{
@@ -139,108 +72,23 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import register_store\n",
- "\n",
- "# Register multiple stores using convenience function\n",
- "blazegraph_store = register_store(\n",
- " \"blazegraph_main\",\n",
- " \"blazegraph\",\n",
- " \"http://localhost:9999/blazegraph/sparql\"\n",
- ")\n",
- "\n",
- "jena_store = register_store(\n",
- " \"jena_backup\",\n",
- " \"jena\",\n",
- " \"http://localhost:3030/ds\"\n",
- ")\n",
- "\n",
- "# List all registered stores\n",
- "stores = manager.list_stores()\n",
- "print(f\"Registered stores: {stores}\")\n",
- "\n",
- "# Get specific store\n",
- "store = manager.get_store(\"blazegraph_main\")\n",
- "print(f\"\\nStore details:\")\n",
- "print(f\" ID: {store.store_id}\")\n",
- "print(f\" Type: {store.store_type}\")\n",
- "print(f\" Endpoint: {store.endpoint}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 3: CRUD Operations\n",
- "\n",
- "Perform Create, Read, Update, Delete operations on triplets.\n",
- "\n",
- "### Operations Overview\n",
- "\n",
- "- **Create**: `add_triplet()`, `add_triplets()`\n",
- "- **Read**: `get_triplet()`\n",
- "- **Update**: `update_triplet()`\n",
- "- **Delete**: `delete_triplet()`"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import add_triplet, add_triplets, get_triplets, update_triplet, delete_triplet\n",
- "\n",
- "# Create - Add single triplet\n",
+ "# Define a single triplet\n",
"triplet1 = Triplet(\n",
" subject=\"http://example.org/Alice\",\n",
- " predicate=\"http://example.org/hasAge\",\n",
- " object=\"30\"\n",
- ")\n",
- "result = add_triplet(triplet1, store_id=\"demo\")\n",
- "print(f\"Added single triplet: {result['success']}\")\n",
- "\n",
- "# Create - Add multiple triplets\n",
- "triplets = [\n",
- " Triplet(\"http://example.org/Alice\", \"http://example.org/hasCity\", \"New York\"),\n",
- " Triplet(\"http://example.org/Bob\", \"http://example.org/hasAge\", \"25\"),\n",
- " Triplet(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
- "]\n",
- "result = add_triplets(triplets, store_id=\"demo\")\n",
- "print(f\"\\nAdded {result['total_triplets']} triplets in {result['batches']} batches\")\n",
- "\n",
- "# Read - Get triplets for a subject\n",
- "alice_triplets = get_triplets(\n",
- " subject=\"http://example.org/Alice\",\n",
- " store_id=\"demo\"\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/Bob\"\n",
")\n",
- "print(f\"\\nFound {len(alice_triplets)} triplets for Alice\")\n",
- "\n",
- "# Update - Change Alice's age\n",
- "old_triplet = Triplet(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"30\")\n",
- "new_triplet = Triplet(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"31\")\n",
- "result = update_triplet(old_triplet, new_triplet, store_id=\"demo\")\n",
- "print(f\"\\nUpdated triplet: {result['success']}\")\n",
"\n",
- "# Delete - Remove a triplet\n",
- "triplet_to_delete = Triplet(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",
- "result = delete_triplet(triplet_to_delete, store_id=\"demo\")\n",
- "print(f\"Deleted triplet: {result['success']}\")"
+ "print(f\"Created triplet: {triplet1.subject} -> {triplet1.predicate} -> {triplet1.object}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 4: SPARQL Query Execution\n",
+ "## 3. Adding Data\n",
"\n",
- "Execute SPARQL queries with the QueryEngine.\n",
- "\n",
- "### Query Types\n",
- "\n",
- "- **SELECT**: Retrieve variable bindings\n",
- "- **ASK**: Boolean queries\n",
- "- **CONSTRUCT**: Build RDF graphs\n",
- "- **DESCRIBE**: Describe resources"
+ "You can add triplets one by one or in bulk."
]
},
{
@@ -249,298 +97,34 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import QueryEngine, BlazegraphStore\n",
- "\n",
- "# Create query engine with caching\n",
- "engine = QueryEngine(enable_caching=True, enable_optimization=True)\n",
- "\n",
- "# Create store\n",
- "store = BlazegraphStore(endpoint=\"http://localhost:9999/blazegraph/sparql\")\n",
- "\n",
- "# SELECT query\n",
- "select_query = \"\"\"\n",
- "PREFIX ex: <http://example.org/>\n",
- "\n",
- "SELECT ?person ?age ?city\n",
- "WHERE {\n",
- " ?person ex:hasAge ?age .\n",
- " ?person ex:hasCity ?city .\n",
- "}\n",
- "ORDER BY DESC(?age)\n",
- "LIMIT 10\n",
- "\"\"\"\n",
- "\n",
- "result = engine.execute_query(select_query, store)\n",
- "\n",
- "print(f\"Query Results:\")\n",
- "print(f\" Variables: {result.variables}\")\n",
- "print(f\" Results: {len(result.bindings)}\")\n",
- "print(f\" Execution time: {result.execution_time:.2f}s\")\n",
- "print(f\" Cached: {result.metadata.get('cached', False)}\")\n",
- "\n",
- "print(\"\\nResults:\")\n",
- "for binding in result.bindings:\n",
- " person = binding.get('person', {}).get('value', '')\n",
- " age = binding.get('age', {}).get('value', '')\n",
- " city = binding.get('city', {}).get('value', '')\n",
- " print(f\" {person}: Age {age}, City {city}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 5: Query Optimization\n",
- "\n",
- "Optimize SPARQL queries for better performance.\n",
- "\n",
- "### Optimization Features\n",
- "\n",
- "- **Query Planning**: Analyze execution steps\n",
- "- **Cost Estimation**: Estimate query cost\n",
- "- **Query Rewriting**: Optimize query structure\n",
- "- **Caching**: Cache query results"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import optimize_query, plan_query\n",
- "\n",
- "# Original query\n",
- "query = \"\"\"\n",
- "SELECT ?s ?p ?o\n",
- "WHERE {\n",
- " ?s ?p ?o .\n",
- "}\n",
- "\"\"\"\n",
- "\n",
- "# Optimize query (adds LIMIT if missing)\n",
- "optimized = optimize_query(query, add_limit=True, default_limit=1000)\n",
- "print(\"Optimized Query:\")\n",
- "print(optimized)\n",
- "\n",
- "# Create query plan\n",
- "plan = plan_query(query)\n",
- "print(f\"\\nQuery Plan:\")\n",
- "print(f\" Original length: {len(plan.query)}\")\n",
- "print(f\" Optimized length: {len(plan.optimized_query)}\")\n",
- "print(f\" Estimated cost: {plan.estimated_cost}\")\n",
- "print(f\" Execution steps:\")\n",
- "for i, step in enumerate(plan.execution_steps, 1):\n",
- " print(f\" {i}. {step}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 6: Bulk Loading\n",
- "\n",
- "Load large datasets efficiently with progress tracking.\n",
- "\n",
- "### Bulk Loading Features\n",
- "\n",
- "- **Batch Processing**: Process in configurable batches\n",
- "- **Progress Tracking**: Monitor loading progress\n",
- "- **Retry Mechanism**: Handle failures gracefully\n",
- "- **Validation**: Validate before loading"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import BulkLoader, LoadProgress\n",
- "\n",
- "# Create bulk loader\n",
- "loader = BulkLoader(\n",
- " batch_size=1000,\n",
- " max_retries=3\n",
- ")\n",
- "\n",
- "# Generate sample triplets\n",
- "large_dataset = [\n",
- " Triplet(\n",
- " f\"http://example.org/entity{i}\",\n",
- " \"http://example.org/hasName\",\n",
- " f\"Entity {i}\"\n",
- " )\n",
- " for i in range(5000)\n",
- "]\n",
- "\n",
- "# Progress callback\n",
- "def progress_callback(progress: LoadProgress):\n",
- " print(f\"Progress: {progress.progress_percentage:.1f}% \"\n",
- " f\"({progress.loaded_triplets}/{progress.total_triplets}) \"\n",
- " f\"Batch {progress.current_batch}/{progress.total_batches}\")\n",
- "\n",
- "# Load triplets with progress tracking\n",
- "store = BlazegraphStore(endpoint=\"http://localhost:9999/blazegraph/sparql\")\n",
- "progress = loader.load_triplets(\n",
- " large_dataset,\n",
- " store,\n",
- " progress_callback=progress_callback\n",
- ")\n",
- "\n",
- "print(f\"\\nLoading Complete:\")\n",
- "print(f\" Loaded: {progress.loaded_triplets}/{progress.total_triplets}\")\n",
- "print(f\" Failed: {progress.failed_triplets}\")\n",
- "print(f\" Elapsed time: {progress.elapsed_time:.2f}s\")\n",
- "print(f\" Throughput: {progress.metadata.get('throughput', 0):.0f} triplets/sec\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 7: Store Backends\n",
+ "# Add a single triplet\n",
+ "store.add_triplet(triplet1)\n",
"\n",
- "Work with different triplet store backends.\n",
- "\n",
- "### Blazegraph Store\n",
- "\n",
- "High-performance triplet store with GPU acceleration."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import BlazegraphStore\n",
- "\n",
- "# Create Blazegraph store\n",
- "blazegraph = BlazegraphStore(\n",
- " endpoint=\"http://localhost:9999/blazegraph/sparql\",\n",
- " namespace=\"kb\",\n",
- " timeout=30\n",
- ")\n",
- "\n",
- "# Add triplets\n",
- "triplets = [\n",
- " Triplet(\"http://example.org/Alice\", \"http://example.org/hasSkill\", \"Python\")\n",
- "]\n",
- "result = blazegraph.add_triplets(triplets)\n",
- "print(f\"Blazegraph - Added: {result['success']}\")\n",
- "\n",
- "# Execute SPARQL query\n",
- "query = \"SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 5\"\n",
- "result = blazegraph.execute_sparql(query)\n",
- "print(f\"Blazegraph - Found {len(result['bindings'])} results\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Jena Store\n",
- "\n",
- "Full-featured RDF framework with inference support."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import JenaStore\n",
- "\n",
- "# Create Jena store (in-memory)\n",
- "jena = JenaStore()\n",
- "\n",
- "# Or connect to Fuseki endpoint\n",
- "# jena = JenaStore(\n",
- "# endpoint=\"http://localhost:3030/ds\",\n",
- "# dataset=\"default\",\n",
- "# enable_inference=True\n",
- "# )\n",
- "\n",
- "# Add triplets with inference\n",
+ "# Create more triplets\n",
"triplets = [\n",
" Triplet(\n",
- " \"http://example.org/Dog\",\n",
- " \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
- " \"http://example.org/Animal\"\n",
+ " subject=\"http://example.org/Bob\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/Charlie\"\n",
" ),\n",
" Triplet(\n",
- " \"http://example.org/Fido\",\n",
- " \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",\n",
- " \"http://example.org/Dog\"\n",
+ " subject=\"http://example.org/Charlie\",\n",
+ " predicate=\"http://xmlns.com/foaf/0.1/knows\",\n",
+ " object=\"http://example.org/David\"\n",
" )\n",
"]\n",
- "result = jena.add_triplets(triplets)\n",
- "print(f\"Jena - Added: {result['success']}\")\n",
- "\n",
- "# Query with inference (Fido is inferred to be an Animal)\n",
- "query = \"\"\"\n",
- "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
- "PREFIX ex: <http://example.org/>\n",
- "SELECT ?animal WHERE {\n",
- " ?animal rdf:type ex:Animal .\n",
- "}\n",
- "\"\"\"\n",
- "result = jena.query(query)\n",
- "print(f\"Jena - Found {len(result)} animals (with inference)\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### RDF4J Store\n",
- "\n",
- "Java-based RDF framework with transaction support."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import RDF4JStore\n",
"\n",
- "# Create RDF4J adapter\n",
- "rdf4j = RDF4JStore(\n",
- " server_url=\"http://localhost:8080/rdf4j-server\",\n",
- " repository_id=\"test\"\n",
- ")\n",
- "\n",
- "# Add triplets with transaction\n",
- "rdf4j.begin_transaction()\n",
- "try:\n",
- " triplet = Triplet(\n",
- " \"http://example.org/Alice\",\n",
- " \"http://example.org/hasEmail\",\n",
- " \"[email protected]\"\n",
- " )\n",
- " rdf4j.add_triplet(\n",
- " subject=triplet.subject,\n",
- " predicate=triplet.predicate,\n",
- " object_literal=triplet.object\n",
- " )\n",
- " rdf4j.commit_transaction()\n",
- " print(\"RDF4J - Transaction committed\")\n",
- "except Exception as e:\n",
- " rdf4j.rollback_transaction()\n",
- " print(f\"RDF4J - Transaction rolled back: {e}\")"
+ "# Bulk add\n",
+ "store.add_triplets(triplets)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Virtuoso Store\n",
+ "## 4. Querying Data (SPARQL)\n",
"\n",
- "Enterprise-grade RDF store with SQL integration."
+ "Use SPARQL queries to retrieve data from the store."
]
},
{
@@ -549,107 +133,26 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.triplet_store import VirtuosoStore\n",
- "\n",
- "# Create Virtuoso store\n",
- "virtuoso = VirtuosoStore(\n",
- " host=\"localhost\",\n",
- " port=1111,\n",
- " user=\"dba\",\n",
- " password=\"dba\"\n",
- ")\n",
- "\n",
- "# Create named graph\n",
- "graph_uri = \"http://example.org/graph1\"\n",
- "virtuoso.create_graph(graph_uri)\n",
- "\n",
- "# Add triplets to named graph\n",
- "triplet = Triplet(\n",
- " \"http://example.org/Alice\",\n",
- " \"http://example.org/worksAt\",\n",
- " \"http://example.org/Company1\"\n",
- ")\n",
- "virtuoso.add_triplet(\n",
- " subject=triplet.subject,\n",
- " predicate=triplet.predicate,\n",
- " object=triplet.object,\n",
- " graph=graph_uri\n",
- ")\n",
- "\n",
- "print(f\"Virtuoso - Added triplet to graph: {graph_uri}\")\n",
- "\n",
- "# Query specific graph\n",
- "query = f\"\"\"\n",
- "PREFIX ex: <http://example.org/>\n",
- "SELECT ?person ?company\n",
- "FROM <{graph_uri}>\n",
- "WHERE {{\n",
- " ?person ex:worksAt ?company .\n",
- "}}\n",
+ "# Simple query to get all triplets (limited to 10)\n",
+ "query = \"\"\"\n",
+ "SELECT ?s ?p ?o\n",
+ "WHERE {\n",
+ " ?s ?p ?o\n",
+ "}\n",
+ "LIMIT 10\n",
"\"\"\"\n",
- "result = virtuoso.query(query)\n",
- "print(f\"Virtuoso - Found {len(result)} results in graph\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 8: Triplet Validation\n",
- "\n",
- "Validate triplets before adding them to the store.\n",
- "\n",
- "### Validation Checks\n",
- "\n",
- "- **Required Fields**: Subject, predicate, object\n",
- "- **Confidence Range**: 0-1 if provided\n",
- "- **URI Format**: Valid URIs\n",
- "- **Empty Components**: No empty values"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.triplet_store import validate_triplets\n",
- "\n",
- "# Create triplets (some invalid)\n",
- "triplets_to_validate = [\n",
- " Triplet(\"http://example.org/Alice\", \"http://example.org/knows\", \"http://example.org/Bob\"), # Valid\n",
- " Triplet(\"\", \"http://example.org/knows\", \"http://example.org/Charlie\"), # Invalid (empty subject)\n",
- " Triplet(\"http://example.org/Dave\", \"\", \"http://example.org/Eve\"), # Invalid (empty predicate)\n",
- " Triplet(\"http://example.org/Frank\", \"http://example.org/knows\", \"http://example.org/Grace\", confidence=1.5), # Invalid (confidence > 1)\n",
- "]\n",
- "\n",
- "# Validate triplets\n",
- "validation = validate_triplets(triplets_to_validate)\n",
"\n",
- "print(\"Validation Results:\")\n",
- "print(f\" Valid: {validation['valid']}\")\n",
- "print(f\" Valid triplets: {validation['valid_triplets']}/{validation['total_triplets']}\")\n",
- "print(f\"\\nErrors: {len(validation['errors'])}\")\n",
- "for error in validation['errors']:\n",
- " print(f\" - {error}\")\n",
- "print(f\"\\nWarnings: {len(validation['warnings'])}\")\n",
- "for warning in validation['warnings']:\n",
- " print(f\" - {warning}\")"
+ "results = store.execute_query(query)\n",
+ "print(\"Query Results:\", results)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Step 9: Multi-Store Operations\n",
+ "## 5. Deleting Data\n",
"\n",
- "Work with multiple stores simultaneously.\n",
- "\n",
- "### Use Cases\n",
- "\n",
- "- **Primary/Backup**: Replicate to backup store\n",
- "- **Read/Write Split**: Separate read and write stores\n",
- "- **Multi-Tenant**: Different stores for different tenants"
+ "Remove triplets when they are no longer needed."
]
},
{
@@ -658,104 +161,17 @@
"metadata": {},
"outputs": [],
"source": [
- "# Register multiple stores\n",
- "manager = TripletManager()\n",
- "\n",
- "primary = manager.register_store(\n",
- " \"primary\",\n",
- " \"blazegraph\",\n",
- " \"http://localhost:9999/blazegraph/sparql\"\n",
- ")\n",
- "\n",
- "backup = manager.register_store(\n",
- " \"backup\",\n",
- " \"jena\",\n",
- " \"http://localhost:3030/ds\"\n",
- ")\n",
- "\n",
- "# Add to primary store\n",
- "triplet = Triplet(\n",
- " \"http://example.org/Document1\",\n",
- " \"http://example.org/hasAuthor\",\n",
- " \"http://example.org/Alice\"\n",
- ")\n",
- "manager.add_triplet(triplet, store_id=\"primary\")\n",
- "print(\"Added to primary store\")\n",
- "\n",
- "# Replicate to backup store\n",
- "manager.add_triplet(triplet, store_id=\"backup\")\n",
- "print(\"Replicated to backup store\")\n",
- "\n",
- "# List all stores\n",
- "stores = manager.list_stores()\n",
- "print(f\"\\nActive stores: {stores}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 10: Best Practices\n",
- "\n",
- "### Choosing the Right Backend\n",
- "\n",
- "1. **Blazegraph**: High-performance, large datasets, GPU acceleration\n",
- "2. **Jena**: Java integration, SHACL validation, inference\n",
- "3. **RDF4J**: Transaction support, ACID guarantees, federation\n",
- "4. **Virtuoso**: Enterprise scale, SQL integration, clustering\n",
- "\n",
- "### Performance Tips\n",
- "\n",
- "- **Batch Operations**: Use `add_triplets()` for multiple triplets\n",
- "- **Query Optimization**: Enable optimization and caching\n",
- "- **Bulk Loading**: Use `BulkLoader` for large datasets\n",
- "- **Validation**: Validate before loading to avoid errors\n",
- "\n",
- "### Configuration\n",
- "\n",
- "- **Batch Size**: 1000-10000 for bulk loading\n",
- "- **Cache Size**: 1000-5000 for query caching\n",
- "- **Timeout**: 30-60 seconds for queries\n",
- "- **Retries**: 3-5 for bulk operations"
+ "store.delete_triplet(triplet1)\n",
+ "print(\"Deleted triplet1\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Summary\n",
- "\n",
- "### What You've Learned\n",
- "\n",
- "In this notebook, you've learned how to:\n",
- "\n",
- "- Register and manage triplet stores\n",
- "- Perform CRUD operations on RDF triplets\n",
- "- Execute and optimize SPARQL queries\n",
- "- Use bulk loading for large datasets\n",
- "- Work with multiple store backends\n",
- "- Validate triplets before operations\n",
- "- Choose the right backend for your use case\n",
- "\n",
- "### Key Takeaways\n",
- "\n",
- "1. **Multi-Backend Support**: Choose the right backend for your needs\n",
- "2. **SPARQL Power**: Full SPARQL 1.1 support with optimization\n",
- "3. **Bulk Loading**: Efficient loading with progress tracking\n",
- "4. **Query Optimization**: Automatic query optimization and caching\n",
- "5. **Validation**: Pre-load validation prevents errors\n",
- "6. **Multi-Store**: Manage multiple stores simultaneously\n",
- "\n",
- "### Next Steps\n",
- "\n",
- "**Further Reading**:\n",
- "- [Triplet Store API Reference](https://semantica.readthedocs.io/reference/triplet_store/)\n",
- "- [SPARQL 1.1 Specification](https://www.w3.org/TR/sparql11-query/)\n",
- "- [Knowledge Graph Building](../use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)\n",
- "\n",
- "---\n",
+ "## Next Steps\n",
"\n",
- "**Questions or Issues?** Check out our [GitHub repository](https://github.com/Hawksight-AI/semantica) or [documentation](https://semantica.readthedocs.io)."
+ "Check out the **Advanced Triplet Store** guide in the `cookbook/advanced` folder for more complex operations like bulk loading optimization, transactions, and advanced SPARQL features."
]
}
],
@@ -775,9 +191,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.10.0"
+ "version": "3.8.5"
}
},
"nbformat": 4,
- "nbformat_minor": 2
-}
\ No newline at end of file
+ "nbformat_minor": 4
+}
diff --git a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
index 2c124169..30844e99 100644
--- a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
+++ b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb
@@ -55,7 +55,7 @@
"- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (materialized knowledge graph)\n",
"- **Embeddings**: EmbeddingGenerator, TextEmbedder (for embeddings)\n",
"- **Vector Store**: VectorStore, HybridSearch, MetadataFilter (for RAG)\n",
- "- **Triplet Store**: TripletManager, QueryEngine (for SPARQL queries on ontologies)\n",
+ "- **Triplet Store**: TripletStore, QueryEngine (for SPARQL queries on ontologies)\n",
"- **Reasoning**: InferenceEngine, RuleManager (for query orchestration and medical reasoning)\n",
"- **Context**: ContextRetriever, ContextGraphBuilder (for contextual retrieval)\n",
"- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer (for visualization)\n",
@@ -104,7 +104,7 @@
"from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
"from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
"from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
- "from semantica.triplet_store import TripletManager, QueryEngine\n",
+ "from semantica.triplet_store import TripletStore, QueryEngine\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
"from semantica.context import ContextRetriever, ContextGraphBuilder\n",
"from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
@@ -470,17 +470,14 @@
"outputs": [],
"source": [
"# Initialize Semantica triplet store and query engine\n",
- "triplet_manager = TripletManager()\n",
- "query_engine = QueryEngine()\n",
- "\n",
- "# Register triplet store (using in-memory for demo)\n",
- "store = triplet_manager.register_store(\"healthcare_ontology\", \"jena\", \"http://localhost:3030/healthcare\")\n",
+ "store = TripletStore(backend=\"jena\", endpoint=\"http://localhost:3030/healthcare\")\n",
+ "query_engine = store.query_engine\n",
"\n",
"# Convert ontology to triplets and add to store\n",
"# In production, this would load the OWL ontology\n",
"sample_triplets = [\n",
- " {\n",
- " \"subject\": \"http://semantica.example.org/healthcare#Type2Diabetes\",\n",
+ " {\n",
+ " \"subject\": \"http://semantica.example.org/healthcare#Type2Diabetes\",\n",
" \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
" \"object\": \"http://semantica.example.org/healthcare#Diabetes\",\n",
" \"confidence\": 1.0\n",
@@ -495,7 +492,7 @@
"\n",
"# Add triplets using Semantica\n",
"for triplet in sample_triplets:\n",
- " triplet_manager.add_triplet(triplet, store_id=\"healthcare_ontology\")\n",
+ " store.add_triplet(triplet)\n",
"\n",
"print(f\" - Triplets added: {len(sample_triplets)}\")\n",
"print(f\" - SPARQL queries enabled for ontology\")\n"
@@ -556,8 +553,8 @@
" FILTER(CONTAINS(LCASE(?label), \"{query_text.lower()}\"))\n",
" }}\n",
" \"\"\"\n",
- " ontology_results = query_engine.execute_query(sparql_query, store)\n",
- " results[\"ontology_results\"] = ontology_results.get(\"bindings\", [])\n",
+ " ontology_results = store.execute_query(sparql_query)\n",
+ " results[\"ontology_results\"] = ontology_results.bindings\n",
" \n",
" # 2. Search documents using Semantica Hybrid Search\n",
" query_embedding = text_embedder.embed(query_text)\n",
diff --git a/docs/modules.md b/docs/modules.md
index 0315933b..9e403de0 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -580,7 +580,7 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
**Key Features:**
-- Multi-backend support (Blazegraph, Jena, RDF4J, Virtuoso)
+- Multi-backend support (Blazegraph, Jena, RDF4J)
- CRUD operations for RDF triplets
- SPARQL query execution and optimization
- Bulk data loading with progress tracking
@@ -590,13 +590,12 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
**Components:**
-- `TripletManager` — Main triplet store management coordinator
+- `TripletStore` — Main triplet store interface
- `QueryEngine` — SPARQL query execution and optimization
- `BulkLoader` — High-volume data loading with progress tracking
- `BlazegraphStore` — Blazegraph integration
- `JenaStore` — Apache Jena integration
- `RDF4JStore` — Eclipse RDF4J integration
-- `VirtuosoStore` — Virtuoso RDF store integration
- `QueryPlan` — Query execution plan dataclass
- `LoadProgress` — Bulk loading progress tracking
@@ -611,20 +610,19 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
**Quick Example:**
```python
-from semantica.triplet_store import TripletManager, execute_query
+from semantica.triplet_store import TripletStore
-manager = TripletManager()
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
# Add triplet
-result = manager.add_triplet({
+result = store.add_triplet({
"subject": "http://example.org/Alice",
"predicate": "http://example.org/knows",
"object": "http://example.org/Bob"
-}, store_id="main")
+})
# Execute SPARQL
-query_result = execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10", store)
+query_result = store.execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10")
```
**API Reference**: [Triplet Store Module](reference/triplet_store.md)
@@ -1119,7 +1117,7 @@ new_facts = inference_engine.forward_chain(kg, rule_manager)
| **Embeddings** | `semantica.embeddings` | `EmbeddingGenerator` | Vector generation |
| **Vector Store** | `semantica.vector_store` | `VectorStore` | Vector storage |
| **Graph Store** | `semantica.graph_store` | `GraphStore` | Graph database |
-| **Triplet Store** | `semantica.triplet_store` | `TripletManager` | RDF storage |
+| **Triplet Store** | `semantica.triplet_store` | `TripletStore` | RDF storage |
| **Deduplication** | `semantica.deduplication` | `DuplicateDetector` | Duplicate removal |
| **Conflicts** | `semantica.conflicts` | `ConflictDetector` | Conflict resolution |
| **Context** | `semantica.context` | `AgentMemory` | Agent context |
diff --git a/docs/reference/triplet_store.md b/docs/reference/triplet_store.md
index 758ab6a6..2d9de590 100644
--- a/docs/reference/triplet_store.md
+++ b/docs/reference/triplet_store.md
@@ -30,7 +30,7 @@
---
- Blazegraph, Apache Jena, RDF4J, and Virtuoso support
+ Blazegraph, Apache Jena, and RDF4J support
- :material-link-variant:{ .lg .middle } **Federation**
@@ -50,7 +50,6 @@
- **Blazegraph**: High-performance, excellent for large datasets, GPU acceleration
- **Apache Jena**: Full-featured, TDB2 storage, SHACL validation
- **RDF4J**: Java-based, excellent tooling, multiple storage backends
- - **Virtuoso**: Enterprise-grade, excellent performance, SQL integration
---
@@ -89,951 +88,81 @@
## Main Classes
-### TripletManager
+### TripletStore
-Main coordinator for triplet store operations across multiple backends.
+Main interface for triplet store operations.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `register_store(store_id, backend, endpoint)` | Register triplet store | Store registration |
-| `add_triplet(triplet, store_id)` | Add single triplet | Index insertion |
-| `add_triplets(triplets, store_id)` | Batch add triplets | Bulk index insertion |
-| `query(sparql, store_id)` | Execute SPARQL query | Query optimization + execution |
-| `delete(pattern, store_id)` | Delete matching triplets | Pattern matching + deletion |
-| `bulk_load(file_path, format, store_id)` | Bulk load from file | Streaming parser + batch insert |
-| `get_stats(store_id)` | Get store statistics | Statistics collection |
-
-**Example:**
-
-```python
-from semantica.triplet_store import TripletManager
-
-# Initialize manager
-manager = TripletManager()
-
-# Register Blazegraph store
-store = manager.register_store(
- store_id="main",
- backend="blazegraph",
- endpoint="http://localhost:9999/blazegraph/sparql"
-)
-
-# Add single triplet
-result = manager.add_triplet(
- triplet ={
- "subject": "http://example.org/Alice",
- "predicate": "http://example.org/knows",
- "object": "http://example.org/Bob"
- },
- store_id="main"
-)
+| `__init__(backend, endpoint)` | Initialize triplet store | Factory pattern |
+| `add_triplet(triplet)` | Add single triplet | Single insert |
+| `add_triplets(triplets, batch_size)` | Add multiple triplets | Bulk load with batching |
+| `get_triplets(s, p, o)` | Retrieve triplets | Pattern matching |
+| `delete_triplet(triplet)` | Delete triplet | Pattern matching deletion |
+| `execute_query(query)` | Execute SPARQL | Query engine delegation |
-# Add multiple triplets
-triplets = [
- {
- "subject": "http://example.org/Alice",
- "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
- "object": "http://example.org/Person"
- },
- {
- "subject": "http://example.org/Bob",
- "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
- "object": "http://example.org/Person"
- }
-]
-
-manager.add_triplets(triplets, store_id="main")
-
-# Query with SPARQL
-results = manager.query("""
- PREFIX ex: <http://example.org/>
- PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
-
- SELECT ?person ?friend WHERE {
- ?person rdf:type ex:Person .
- ?person ex:knows ?friend .
- }
-""", store_id="main")
-
-for row in results["results"]["bindings"]:
- print(f"{row['person']['value']} knows {row['friend']['value']}")
-
-# Get statistics
-stats = manager.get_stats("main")
-print(f"Total triplets: {stats['triplet_count']}")
-```
-
----
-
-### QueryEngine
+### BulkLoader
-SPARQL query execution and optimization engine.
+High-volume data loading utility.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `execute(query, store)` | Execute SPARQL query | Parse + optimize + execute |
-| `parse_query(sparql)` | Parse SPARQL syntax | SPARQL parser |
-| `optimize_query(query)` | Optimize query plan | Join reordering + filter pushdown |
-| `explain_query(query)` | Explain query plan | Query plan visualization |
-| `validate_query(sparql)` | Validate SPARQL syntax | Syntax validation |
-
-**SPARQL Query Types:**
-
-| Query Type | Description | Use Case |
-|------------|-------------|----------|
-| **SELECT** | Retrieve variable bindings | Data retrieval |
-| **CONSTRUCT** | Build RDF graph | Graph transformation |
-| **ASK** | Boolean query | Existence check |
-| **DESCRIBE** | Describe resources | Resource exploration |
-
-**Example:**
-
-```python
-from semantica.triplet_store import QueryEngine, TripletManager
-
-manager = TripletManager()
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
-
-engine = QueryEngine()
-
-# SELECT query
-select_query = """
- PREFIX ex: <http://example.org/>
- SELECT ?name ?age WHERE {
- ?person ex:name ?name .
- ?person ex:age ?age .
- FILTER (?age > 18)
- }
- ORDER BY DESC(?age)
- LIMIT 10
-"""
-
-results = engine.execute(select_query, store)
-
-# CONSTRUCT query
-construct_query = """
- PREFIX ex: <http://example.org/>
- CONSTRUCT {
- ?person ex:isAdult true .
- }
- WHERE {
- ?person ex:age ?age .
- FILTER (?age >= 18)
- }
-"""
-
-graph = engine.execute(construct_query, store)
-
-# ASK query
-ask_query = """
- PREFIX ex: <http://example.org/>
- ASK {
- ?person ex:name "Alice" .
- }
-"""
-
-exists = engine.execute(ask_query, store)
-print(f"Alice exists: {exists}")
+| `load_triplets(triplets, store)` | Bulk load triplets | Batch processing with retries |
-# Explain query plan
-plan = engine.explain_query(select_query)
-print(f"Query plan: {plan}")
-```
-
----
-
-### BulkLoader
+### QueryEngine
-High-performance bulk data loading with progress tracking.
+SPARQL query execution and optimization engine.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `load(file_path, format, store)` | Load RDF file | Streaming parser + batch insert |
-| `load_from_url(url, format, store)` | Load from URL | HTTP streaming + batch insert |
-| `load_from_string(data, format, store)` | Load from string | String parser + batch insert |
-| `get_progress()` | Get loading progress | Progress tracking |
-
-**Supported Formats:**
-- **RDF/XML**: W3C RDF/XML format
-- **Turtle**: Terse RDF Triplet Language
-- **N-Triples**: Line-based triplet format
-- **N-Quads**: N-Triples with named graphs
-- **JSON-LD**: JSON-based RDF format
-- **TriG**: Turtle with named graphs
-
-**Example:**
-
-```python
-from semantica.triplet_store import BulkLoader, TripletManager
-
-manager = TripletManager()
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
-
-loader = BulkLoader(
- batch_size=10000,
- show_progress=True,
- parallel=True,
- n_jobs=4
-)
-
-# Load from file
-progress = loader.load(
- file_path="knowledge_graph.ttl",
- format="turtle",
- store=store
-)
-
-print(f"Loaded {progress['triplets_loaded']} triplets in {progress['elapsed_time']:.2f}s")
-print(f"Throughput: {progress['triplets_per_second']:.0f} triplets/sec")
-
-# Load from URL
-progress = loader.load_from_url(
- url="https://example.org/data.rdf",
- format="rdf/xml",
- store=store
-)
-
-# Load from string
-rdf_data = """
-@prefix ex: <http://example.org/> .
-@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
-
-ex:Alice rdf:type ex:Person ;
- ex:name "Alice" ;
- ex:age 30 .
-"""
-
-progress = loader.load_from_string(
- data=rdf_data,
- format="turtle",
- store=store
-)
-```
-
----
-
-### Store Backends
-
-#### BlazegraphStore
-
-High-performance triplet store with GPU acceleration support.
-
-**Features:**
-- High-performance SPARQL query execution
-- GPU acceleration for analytics
-- Full-text search integration
-- Geospatial query support
-- High availability clustering
-
-**Example:**
-
-```python
-from semantica.triplet_store import BlazegraphStore
-
-store = BlazegraphStore(
- endpoint="http://localhost:9999/blazegraph/sparql",
- namespace="kb", # Blazegraph namespace
- timeout=30
-)
-
-store.connect()
-
-# Create namespace
-store.create_namespace("my_kb", properties={
- "com.bigdata.rdf.store.AbstractTripleStore.textIndex": "true",
- "com.bigdata.rdf.store.AbstractTripleStore.geoSpatial": "true"
-})
-
-# Add triplets
-store.add_triplet(
- subject="http://example.org/Alice",
- predicate="http://example.org/name",
- object_literal="Alice",
- object_datatype="http://www.w3.org/2001/XMLSchema#string"
-)
-
-# Full-text search
-results = store.query("""
- PREFIX bds: <http://www.bigdata.com/rdf/search#>
- SELECT ?subject ?score WHERE {
- ?subject bds:search "machine learning" .
- ?subject bds:relevance ?score .
- }
- ORDER BY DESC(?score)
-""")
-```
+| `execute(query)` | Execute SPARQL query | Query execution |
+| `optimize(query)` | Optimize SPARQL query | Query rewriting |
---
-#### JenaStore
-
-Full-featured RDF framework with TDB2 storage.
-
-**Features:**
-- TDB2 native triplet store
-- SHACL validation
-- Inference engines (RDFS, OWL)
-- Fuseki SPARQL server
-- RDF/XML, Turtle, JSON-LD support
+## 🚀 Usage
-**Example:**
+### Initialization
```python
-from semantica.triplet_store import JenaStore
-
-store = JenaStore(
- tdb_directory="./tdb2_data",
- inference="rdfs" # rdfs, owl, or None
-)
-
-store.connect()
-
-# Add triplets with inference
-store.add_triplet(
- subject="http://example.org/Dog",
- predicate="http://www.w3.org/2000/01/rdf-schema#subClassOf",
- object="http://example.org/Animal"
-)
-
-store.add_triplet(
- subject="http://example.org/Fido",
- predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
- object="http://example.org/Dog"
-)
-
-# Query with inference (Fido is inferred to be an Animal)
-results = store.query("""
- PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
- PREFIX ex: <http://example.org/>
-
- SELECT ?animal WHERE {
- ?animal rdf:type ex:Animal .
- }
-""")
-
-# SHACL validation
-shapes = """
-@prefix sh: <http://www.w3.org/ns/shacl#> .
-@prefix ex: <http://example.org/> .
-
-ex:PersonShape a sh:NodeShape ;
- sh:targetClass ex:Person ;
- sh:property [
- sh:path ex:name ;
- sh:minCount 1 ;
- sh:datatype xsd:string ;
- ] .
-"""
-
-validation_report = store.validate_shacl(shapes)
-print(f"Valid: {validation_report['conforms']}")
-```
-
----
-
-#### RDF4JStore
-
-Java-based RDF framework with multiple storage backends.
-
-**Features:**
-- Multiple storage backends (Memory, Native, HTTP)
-- Transaction support with ACID guarantees
-- SPARQL 1.1 Update support
-- RDF Schema and OWL reasoning
-- Repository federation
-
-**Example:**
-
-```python
-from semantica.triplet_store import RDF4JStore
-
-store = RDF4JStore(
- server_url="http://localhost:8080/rdf4j-server",
- repository_id="my_repo"
-)
-
-store.connect()
-
-# Add triplet with transaction
-store.begin_transaction()
-try:
- store.add_triplet(
- subject="http://example.org/Alice",
- predicate="http://example.org/name",
- object_literal="Alice"
- )
- store.commit_transaction()
-except Exception as e:
- store.rollback_transaction()
-
-# Query with reasoning
-results = store.query("""
- PREFIX ex: <http://example.org/>
- SELECT ?person WHERE {
- ?person ex:name ?name .
- }
-""", enable_reasoning=True)
-```
-
----
+from semantica.triplet_store import TripletStore
-#### VirtuosoStore
-
-Enterprise-grade RDF store with SQL integration.
-
-**Features:**
-- High-performance SPARQL execution
-- SQL/SPARQL hybrid queries
-- Quad store with named graphs
-- Full-text indexing
-- Geospatial support
-
-**Example:**
-
-```python
-from semantica.triplet_store import VirtuosoStore
-
-store = VirtuosoStore(
- host="localhost",
- port=1111,
- user="dba",
- password="dba"
-)
-
-store.connect()
-
-# Add triplets to named graph
-graph_uri = "http://example.org/graph1"
-
-store.add_triplet(
- subject="http://example.org/Alice",
- predicate="http://example.org/name",
- object_literal="Alice",
- graph=graph_uri
+# Initialize Blazegraph store
+store = TripletStore(
+ backend="blazegraph",
+ endpoint="http://localhost:9999/blazegraph"
)
-
-# Query specific graph
-results = store.query(f"""
- PREFIX ex: <http://example.org/>
- SELECT ?person ?name
- FROM <{graph_uri}>
- WHERE {{
- ?person ex:name ?name .
- }}
-""")
```
----
-
-## Convenience Functions
-
-Quick access to triplet store operations:
+### Adding Data
```python
-from semantica.triplet_store import (
- add_triplet,
- add_triplets,
- get_triplets,
- execute_query,
- bulk_load,
- export_graph,
- import_graph
-)
-
-# Add single triplet
-add_triplet(
- subject="http://example.org/Alice",
- predicate="http://example.org/knows",
- object="http://example.org/Bob"
-)
+from semantica.semantic_extract.triplet_extractor import Triplet
-# Execute SPARQL query
-results = execute_query("""
- SELECT ?s ?p ?o WHERE {
- ?s ?p ?o .
- }
- LIMIT 10
-""")
+# Single triplet
+triplet = Triplet("http://s", "http://p", "http://o")
+store.add_triplet(triplet)
# Bulk load
-progress = bulk_load(
- file_path="data.ttl",
- format="turtle",
- batch_size=10000
-)
-
-# Export graph
-export_graph(
- output_path="export.rdf",
- format="rdf/xml"
-)
-```
-
----
-
-## Dataclasses
-
-### TripletStore
-
-Configuration dataclass for triplet store instances.
-
-**Attributes:**
-
-| Attribute | Type | Description |
-|-----------|------|-------------|
-| `store_id` | str | Unique store identifier |
-| `store_type` | str | Backend type (blazegraph, jena, rdf4j, virtuoso) |
-| `endpoint` | str | SPARQL endpoint URL |
-| `config` | dict | Additional configuration options |
-
----
-
-### QueryResult
-
-Query execution result dataclass.
-
-**Attributes:**
-
-| Attribute | Type | Description |
-|-----------|------|-------------|
-| `variables` | List[str] | Query variable names |
-| `bindings` | List[Dict] | Result bindings |
-| `execution_time` | float | Query execution time (seconds) |
-| `metadata` | Dict | Additional metadata (cached, optimized, etc.) |
-
----
-
-### QueryPlan
-
-Query execution plan dataclass.
-
-**Attributes:**
-
-| Attribute | Type | Description |
-|-----------|------|-------------|
-| `query` | str | Original SPARQL query |
-| `optimized_query` | str | Optimized query |
-| `estimated_cost` | float | Estimated execution cost |
-| `execution_steps` | List[str] | Planned execution steps |
-
----
-
-### LoadProgress
-
-Bulk loading progress dataclass.
-
-**Attributes:**
-
-| Attribute | Type | Description |
-|-----------|------|-------------|
-| `loaded_triplets` | int | Number of triplets loaded |
-| `total_triplets` | int | Total triplets to load |
-| `failed_triplets` | int | Number of failed triplets |
-| `progress_percentage` | float | Loading progress (0-100) |
-| `elapsed_time` | float | Time elapsed (seconds) |
-| `current_batch` | int | Current batch number |
-| `total_batches` | int | Total number of batches |
-| `metadata` | Dict | Additional metadata (throughput, ETA, etc.) |
-
----
-
-## Configuration
-
-### Environment Variables
-
-```bash
-# General settings
-export TRIPLET_STORE_DEFAULT_BACKEND=blazegraph
-export TRIPLET_STORE_BATCH_SIZE=10000
-export TRIPLET_STORE_TIMEOUT=30
-
-# Blazegraph settings
-export TRIPLET_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph/sparql
-export TRIPLET_STORE_BLAZEGRAPH_NAMESPACE=kb
-
-# Jena settings
-export TRIPLET_STORE_JENA_TDB_DIRECTORY=./tdb2_data
-export TRIPLET_STORE_JENA_INFERENCE=rdfs
-
-# RDF4J settings
-export TRIPLET_STORE_RDF4J_SERVER_URL=http://localhost:8080/rdf4j-server
-export TRIPLET_STORE_RDF4J_REPOSITORY_ID=my_repo
-
-# Virtuoso settings
-export TRIPLET_STORE_VIRTUOSO_HOST=localhost
-export TRIPLET_STORE_VIRTUOSO_PORT=1111
-export TRIPLET_STORE_VIRTUOSO_USER=dba
-export TRIPLET_STORE_VIRTUOSO_PASSWORD=dba
-```
-
-### YAML Configuration
-
-```yaml
-# config.yaml - Triplet Store Configuration
-
-triplet_store:
- backend: blazegraph # blazegraph, jena, rdf4j, virtuoso
- batch_size: 10000
- timeout: 30
- enable_reasoning: true
-
- blazegraph:
- endpoint: http://localhost:9999/blazegraph/sparql
- namespace: kb
- properties:
- textIndex: true
- geoSpatial: false
-
- jena:
- tdb_directory: ./tdb2_data
- inference: rdfs # rdfs, owl, none
- unionDefaultGraph: true
-
- rdf4j:
- server_url: http://localhost:8080/rdf4j-server
- repository_id: my_repo
-
- virtuoso:
- host: localhost
- port: 1111
- user: dba
- password: dba
- graph_uri: http://example.org/graph
-
- query:
- optimize: true
- cache_enabled: true
- cache_size: 1000
- explain_plans: false
-```
-
----
-
-## Backend Comparison
-
-| Feature | Blazegraph | Apache Jena | RDF4J | Virtuoso |
-|---------|------------|-------------|-------|----------|
-| **Performance** | Excellent | Good | Good | Excellent |
-| **Scalability** | High | Medium | Medium | Very High |
-| **SPARQL 1.1** | Full | Full | Full | Full |
-| **Reasoning** | Limited | Full (RDFS/OWL) | Full | Full |
-| **Full-Text** | Yes | Yes | Yes | Yes |
-| **Geospatial** | Yes | Limited | Limited | Yes |
-| **Clustering** | Yes | No | No | Yes |
-| **License** | GPLv2 | Apache 2.0 | BSD | Commercial/GPL |
-| **Best For** | Large datasets | Java apps | Java apps | Enterprise |
-
----
-
-## Docker Quick Start
-
-### Blazegraph
-
-```bash
-docker run -d -p 9999:9999 \
- -v ./blazegraph-data:/data \
- --name blazegraph \
- lyrasis/blazegraph:2.1.5
-
-# Access UI at http://localhost:9999/blazegraph
-```
-
-### Apache Jena Fuseki
-
-```bash
-docker run -d -p 3030:3030 \
- -v ./fuseki-data:/fuseki \
- --name fuseki \
- stain/jena-fuseki
-
-# Access UI at http://localhost:3030
-```
-
-### RDF4J Server
-
-```bash
-docker run -d -p 8080:8080 \
- -v ./rdf4j-data:/var/rdf4j \
- --name rdf4j \
- eclipse/rdf4j-workbench
-
-# Access UI at http://localhost:8080/rdf4j-workbench
-```
-
----
-
-## Advanced SPARQL Examples
-
-### Aggregation Queries
-
-```sparql
-PREFIX ex: <http://example.org/>
-
-SELECT ?department (COUNT(?employee) as ?count) (AVG(?salary) as ?avg_salary)
-WHERE {
- ?employee ex:worksIn ?department .
- ?employee ex:salary ?salary .
-}
-GROUP BY ?department
-HAVING (COUNT(?employee) > 5)
-ORDER BY DESC(?count)
-```
-
-### Property Paths
-
-```sparql
-PREFIX ex: <http://example.org/>
-
-# Find all ancestors (transitive closure)
-SELECT ?person ?ancestor
-WHERE {
- ?person ex:hasParent+ ?ancestor .
-}
-
-# Find friends of friends
-SELECT ?person ?friend_of_friend
-WHERE {
- ?person ex:knows/ex:knows ?friend_of_friend .
- FILTER (?person != ?friend_of_friend)
-}
-```
-
-### Federated Queries
-
-```sparql
-PREFIX ex: <http://example.org/>
-
-SELECT ?person ?company ?stock_price
-WHERE {
- # Local store
- ?person ex:worksFor ?company .
-
- # Remote store
- SERVICE <http://remote-store.example.org/sparql> {
- ?company ex:stockPrice ?stock_price .
- }
-}
-```
-
-### Update Operations
-
-```sparql
-PREFIX ex: <http://example.org/>
-
-# INSERT DATA
-INSERT DATA {
- ex:Alice ex:knows ex:Bob .
- ex:Bob ex:knows ex:Charlie .
-}
-
-# DELETE/INSERT
-DELETE {
- ?person ex:age ?old_age .
-}
-INSERT {
- ?person ex:age ?new_age .
-}
-WHERE {
- ?person ex:age ?old_age .
- BIND(?old_age + 1 AS ?new_age)
-}
+triplets = [Triplet(f"http://s{i}", "http://p", "http://o") for i in range(1000)]
+store.add_triplets(triplets)
```
----
-
-## Performance Tips
-
-### Query Optimization
+### Querying
```python
-# Use LIMIT for large result sets
query = """
- SELECT ?s ?p ?o WHERE {
- ?s ?p ?o .
- }
- LIMIT 1000
-"""
-
-# Use FILTER efficiently (after other patterns)
-query = """
- SELECT ?person ?name WHERE {
- ?person rdf:type ex:Person .
- ?person ex:name ?name .
- FILTER (STRLEN(?name) > 5) # Filter after pattern matching
- }
-"""
-
-# Use property paths wisely
-query = """
- SELECT ?person ?ancestor WHERE {
- ?person ex:hasParent{1,3} ?ancestor . # Limit path length
- }
-"""
-```
-
-### Bulk Loading Optimization
-
-```python
-from semantica.triplet_store import BulkLoader
-
-loader = BulkLoader(
- batch_size=50000, # Larger batches for better performance
- parallel=True, # Enable parallel loading
- n_jobs=8, # Use multiple cores
- disable_indexes=True, # Disable indexes during load
- rebuild_indexes=True # Rebuild after load
-)
-
-progress = loader.load("large_dataset.nt", format="ntriples")
-```
-
-### Indexing Strategy
-
-```python
-# Create selective indexes
-store.create_index("predicate", ["http://example.org/name"])
-store.create_index("object", ["http://example.org/Person"])
-
-# Full-text index for specific predicates
-store.create_fulltext_index([
- "http://example.org/description",
- "http://example.org/content"
-])
-```
-
----
-
-## Integration Examples
-
-### Knowledge Graph Export to RDF
-
-```python
-from semantica.kg import GraphBuilder
-from semantica.triplet_store import TripletManager, BulkLoader
-
-# Build knowledge graph
-builder = GraphBuilder()
-kg = builder.build(entities, relationships)
-
-# Convert to RDF triplets
-triplets = []
-for entity in kg.entities:
- triplets.append({
- "subject": f"http://example.org/{entity.id}",
- "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
- "object": f"http://example.org/{entity.type}"
- })
-
- for prop, value in entity.properties.items():
- triplets.append({
- "subject": f"http://example.org/{entity.id}",
- "predicate": f"http://example.org/{prop}",
- "object_literal": str(value)
- })
-
-# Load into triplet store
-manager = TripletManager()
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
-manager.add_triplets(triplets, store_id="main")
-```
-
-### Semantic Search with SPARQL
-
-```python
-from semantica.triplet_store import QueryEngine
-
-engine = QueryEngine()
-
-def semantic_search(keywords, limit=10):
- query = f"""
- PREFIX ex: <http://example.org/>
- PREFIX bds: <http://www.bigdata.com/rdf/search#>
-
- SELECT ?doc ?title ?score WHERE {{
- ?doc bds:search "{keywords}" .
- ?doc bds:relevance ?score .
- ?doc ex:title ?title .
- }}
- ORDER BY DESC(?score)
- LIMIT {limit}
- """
-
- return engine.execute(query, store)
-
-results = semantic_search("machine learning", limit=5)
-```
-
----
-
-## Troubleshooting
-
-### Common Issues
-
-**Issue**: Slow query performance
-
-```python
-# Solution 1: Add indexes
-store.create_index("predicate", ["http://example.org/knows"])
-
-# Solution 2: Optimize query
-# Bad: Cartesian product
-query_bad = """
- SELECT ?s ?o WHERE {
- ?s ?p1 ?o1 .
- ?o ?p2 ?o2 .
- }
-"""
-
-# Good: Constrained join
-query_good = """
- SELECT ?s ?o WHERE {
- ?s ex:knows ?o .
- ?o rdf:type ex:Person .
- }
+SELECT ?s ?p ?o
+WHERE {
+ ?s ?p ?o
+}
+LIMIT 10
"""
-
-# Solution 3: Use LIMIT
-results = execute_query(query + " LIMIT 1000")
-```
-
-**Issue**: Out of memory during bulk load
-
-```python
-# Solution: Use streaming and smaller batches
-loader = BulkLoader(
- batch_size=10000, # Smaller batches
- streaming=True, # Stream from file
- clear_cache=True # Clear cache between batches
-)
-```
-
-**Issue**: SPARQL syntax errors
-
-```python
-# Solution: Validate query first
-from semantica.triplet_store import QueryEngine
-
-engine = QueryEngine()
-is_valid = engine.validate_query(sparql_query)
-
-if not is_valid:
- errors = engine.get_syntax_errors(sparql_query)
- print(f"Syntax errors: {errors}")
+results = store.execute_query(query)
```
-
----
-
-## See Also
-- [Knowledge Graph Module](kg.md) - Build and analyze knowledge graphs
-- [Ontology Module](ontology.md) - Ontology generation and management
-- [Graph Store Module](graph_store.md) - Property graph storage
-- [Export Module](export.md) - Export to various formats
-
-## Cookbook
-- [Triplet Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triplet_Store.ipynb)
diff --git a/semantica/triplet_store/__init__.py b/semantica/triplet_store/__init__.py
index 34de462c..c5907094 100644
--- a/semantica/triplet_store/__init__.py
+++ b/semantica/triplet_store/__init__.py
@@ -3,152 +3,62 @@ Triplet Store Module
This module provides comprehensive triplet store integration and management
for RDF data storage and querying, supporting multiple triplet store backends
-with unified interfaces.
-
-Algorithms Used:
-
-Triplet Store Management:
- - Store Registration: Store type detection, store factory pattern, configuration management, default store selection
- - Backend Pattern: Unified interface for multiple backends (Blazegraph, Jena, RDF4J, Virtuoso), store instantiation, backend-specific operation delegation
- - Store Selection: Default store resolution, store ID lookup, store validation
-
-CRUD Operations:
- - Triplet Addition: Single triplet insertion, batch triplet insertion, triplet validation (subject/predicate/object checking, confidence validation), store delegation
- - Triplet Retrieval: Pattern matching (subject/predicate/object filtering), SPARQL query construction, result binding extraction, triplet reconstruction
- - Triplet Deletion: Triplet matching, deletion operation delegation, result verification
- - Triplet Update: Delete-then-add pattern, atomic update operations, conflict detection
-
-Bulk Loading:
- - Batch Processing: Chunking algorithm (fixed-size batch creation), batch size optimization, memory management for large datasets
- - Progress Tracking: Load progress calculation (loaded/total percentage), elapsed time tracking, estimated remaining time calculation (linear projection), throughput calculation (triplets/second)
- - Retry Mechanism: Exponential backoff retry (delay = retry_delay * (attempt + 1)), max retry limit, error recovery, stop-on-error option
- - Stream Processing: Iterator-based stream processing, incremental batch collection, memory-efficient loading
- - Validation: Pre-load validation (empty component checking, URI validation, confidence checking), error/warning collection
-
-SPARQL Query Execution:
- - Query Validation: Syntax validation (keyword checking, structure validation), query type detection (SELECT, ASK, CONSTRUCT, DESCRIBE, INSERT, DELETE)
- - Query Optimization: Whitespace normalization, LIMIT addition for SELECT queries, query rewriting, cost estimation
- - Query Planning: Execution step identification (SELECT projection, pattern matching, filtering, sorting, pagination), cost estimation (heuristic-based: COUNT multiplier, join count multiplier, DISTINCT multiplier)
- - Query Caching: Cache key generation (MD5 hash of normalized query), LRU-style cache eviction (oldest entry removal when cache full), cache hit/miss tracking, cache invalidation
- - Result Processing: Binding extraction, variable extraction, result formatting, metadata attachment
-
-Query Optimization:
- - Cost Estimation: Heuristic-based cost calculation (base cost * complexity multipliers), COUNT query detection (2x multiplier), join count estimation (1 + join_count * 0.1 multiplier), DISTINCT detection (1.5x multiplier)
- - Execution Step Identification: Query parsing for step detection, step sequence construction, optimization opportunity detection
- - Query Rewriting: Whitespace normalization, LIMIT injection, query simplification
-
-Store Backends:
- - Blazegraph Store: HTTP-based SPARQL endpoint communication, namespace management, graph management, bulk load via INSERT DATA, authentication handling
- - Jena Store: rdflib integration, SPARQLStore for remote endpoints, in-memory graph support, model/dataset management, RDF serialization (Turtle, RDF/XML, N3), inference support
- - RDF4J Store: RDF4J repository connection, SPARQL endpoint communication, transaction support, bulk operations
- - Virtuoso Store: Virtuoso SPARQL endpoint communication, SQL/SPARQL hybrid queries, bulk loading, transaction support
-
-Data Validation:
- - Triplet Validation: Required field checking (subject, predicate, object), confidence range validation (0-1), URI format validation
- - Pre-load Validation: Empty component detection, URI format checking, confidence threshold checking, error/warning categorization
-
-Performance Optimization:
- - Batch Size Optimization: Configurable batch size, memory-aware batching, throughput-based optimization
- - Connection Pooling: Store-level connection management, connection reuse, connection lifecycle management
- - Query Caching: Result caching for repeated queries, cache size management, cache hit optimization
- - Parallel Processing: Batch-level parallelization (when supported by store), concurrent batch processing
+(Blazegraph, Jena, RDF4J) with unified interfaces.
Key Features:
- - Multi-backend support (Blazegraph, Jena, RDF4J, Virtuoso)
+ - Unified triplet store interface
+ - Multi-backend support (Blazegraph, Jena, RDF4J)
- CRUD operations for RDF triplets
- SPARQL query execution and optimization
- Bulk data loading with progress tracking
- - Query caching and optimization
- - Transaction support
- - Store backend pattern
- - Method registry for extensibility
- - Configuration management with environment variables and config files
+ - Configuration management
Main Classes:
- - TripletManager: Main triplet store management coordinator
- - QueryEngine: SPARQL query execution and optimization
+ - TripletStore: Main triplet store interface
- BulkLoader: High-volume data loading
+ - QueryEngine: SPARQL query execution and optimization
- BlazegraphStore: Blazegraph integration store
- JenaStore: Apache Jena integration store
- RDF4JStore: Eclipse RDF4J integration store
- - VirtuosoStore: Virtuoso RDF store integration store
- - TripletStore: Triplet store configuration dataclass
- - QueryResult: Query result representation dataclass
- - QueryPlan: Query execution plan dataclass
- - LoadProgress: Bulk loading progress dataclass
-
-Convenience Functions:
- - register_store: Register triplet store wrapper
- - add_triplet: Add single triplet wrapper
- - add_triplets: Add multiple triplets wrapper
- - get_triplets: Get triplets matching pattern wrapper
- - delete_triplet: Delete triplet wrapper
- - execute_query: Execute SPARQL query wrapper
- - optimize_query: Optimize SPARQL query wrapper
- - bulk_load: Bulk load triplets wrapper
- - get_triplet_store_method: Get triplet store method by task and name
- - list_available_methods: List registered triplet store methods
Example Usage:
- >>> from semantica.triplet_store import TripletManager, register_store, add_triplet, execute_query
- >>> # Using convenience functions
- >>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = add_triplet(triplet, store_id="main")
- >>> query_result = execute_query(sparql_query, store)
- >>> # Using classes directly
- >>> manager = TripletManager()
- >>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = manager.add_triplet(triplet, store_id="main")
- >>> from semantica.triplet_store import QueryEngine
- >>> engine = QueryEngine()
- >>> query_result = engine.execute_query(sparql_query, store)
-
-Author: Semantica Contributors
-License: MIT
+ >>> from semantica.triplet_store import TripletStore
+ >>> store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
+ >>> store.add_triplet(triplet)
+ >>> results = store.execute_query("SELECT * WHERE { ?s ?p ?o } LIMIT 10")
"""
-from .blazegraph_store import BlazegraphStore
-from .bulk_loader import BulkLoader, LoadProgress
+from .bulk_loader import BulkLoader
from .config import TripletStoreConfig, triplet_store_config
+from .query_engine import QueryEngine
+from .triplet_store import TripletStore
+from .blazegraph_store import BlazegraphStore
from .jena_store import JenaStore
+from .rdf4j_store import RDF4JStore
from .methods import (
+ register_store,
add_triplet,
add_triplets,
- bulk_load,
+ get_triplets,
delete_triplet,
+ update_triplet,
execute_query,
- get_triplet_store_method,
- get_triplets,
- list_available_methods,
optimize_query,
plan_query,
- register_store,
- update_triplet,
+ bulk_load,
validate_triplets,
+ list_available_methods
)
-from .query_engine import QueryEngine, QueryPlan, QueryResult
-from .rdf4j_store import RDF4JStore
-from .registry import MethodRegistry, method_registry
-from .triplet_manager import TripletManager, TripletStore
-from .virtuoso_store import VirtuosoStore
__all__ = [
- # Triplet management
- "TripletManager",
"TripletStore",
- # Store backends
+ "BulkLoader",
+ "QueryEngine",
+ "TripletStoreConfig",
+ "triplet_store_config",
"BlazegraphStore",
"JenaStore",
"RDF4JStore",
- "VirtuosoStore",
- # Query engine
- "QueryEngine",
- "QueryResult",
- "QueryPlan",
- # Bulk loading
- "BulkLoader",
- "LoadProgress",
- # Convenience functions
"register_store",
"add_triplet",
"add_triplets",
@@ -160,11 +70,5 @@ __all__ = [
"plan_query",
"bulk_load",
"validate_triplets",
- "get_triplet_store_method",
"list_available_methods",
- # Configuration and registry
- "TripletStoreConfig",
- "triplet_store_config",
- "MethodRegistry",
- "method_registry",
]
diff --git a/semantica/triplet_store/config.py b/semantica/triplet_store/config.py
index 01db8151..0fdef1b5 100644
--- a/semantica/triplet_store/config.py
+++ b/semantica/triplet_store/config.py
@@ -119,7 +119,6 @@ class TripletStoreConfig:
"TRIPLET_STORE_BLAZEGRAPH_ENDPOINT": "blazegraph_endpoint",
"TRIPLET_STORE_JENA_ENDPOINT": "jena_endpoint",
"TRIPLET_STORE_RDF4J_ENDPOINT": "rdf4j_endpoint",
- "TRIPLET_STORE_VIRTUOSO_ENDPOINT": "virtuoso_endpoint",
}
for env_var, config_key in env_mappings.items():
diff --git a/semantica/triplet_store/methods.py b/semantica/triplet_store/methods.py
index bd724be1..12380aa8 100644
--- a/semantica/triplet_store/methods.py
+++ b/semantica/triplet_store/methods.py
@@ -8,11 +8,10 @@ multiple approaches and integrates with the method registry for extensibility.
Supported Methods:
Store Registration:
- - "default": Default store registration using TripletManager
+ - "default": Default store registration using TripletStore
- "blazegraph": Blazegraph-specific registration
- "jena": Jena-specific registration
- "rdf4j": RDF4J-specific registration
- - "virtuoso": Virtuoso-specific registration
Triplet Addition:
- "default": Default triplet addition
@@ -32,56 +31,44 @@ Triplet Deletion:
Triplet Update:
- "default": Default triplet update (delete-then-add)
- - "atomic": Atomic update (when supported)
SPARQL Query:
- "default": Default SPARQL query execution
- "optimized": Optimized query execution
- - "cached": Cached query execution
Query Optimization:
- "default": Default query optimization
- - "basic": Basic optimization (whitespace, LIMIT)
- - "advanced": Advanced optimization (cost-based)
Bulk Loading:
- "default": Default bulk loading
- "batch": Batch-based bulk loading
- - "stream": Stream-based bulk loading
Validation:
- "default": Default validation
- "triplet": Triplet structure validation
- - "pre_load": Pre-load validation
Algorithms Used:
Store Registration:
- - Store Type Detection: Backend type identification, store factory pattern
- - Configuration Management: Store configuration storage, default store selection
- - Store Instantiation: Backend-specific store creation, connection initialization
+ - Store Type Detection: Backend type identification
+ - Store Factory: Create appropriate store instance based on store type
Triplet Operations:
- - Triplet Validation: Required field checking, confidence validation, URI validation
+ - Triplet Validation: Required field checking, confidence validation
- Batch Processing: Chunking algorithm, batch size optimization
- - Pattern Matching: Subject/predicate/object filtering, SPARQL query construction
+ - Pattern Matching: Subject/predicate/object filtering
SPARQL Query:
- - Query Validation: Syntax checking, query type detection
- - Query Optimization: Whitespace normalization, LIMIT injection, cost estimation
- - Query Caching: MD5-based cache key generation, LRU-style eviction
- - Result Processing: Binding extraction, variable extraction
+ - Query Validation: Syntax checking
+ - Query Optimization: Cost estimation
+ - Query Caching: LRU-style eviction
Bulk Loading:
- - Progress Tracking: Load percentage calculation, elapsed time tracking, throughput calculation
- - Retry Mechanism: Exponential backoff, max retry limit
- - Stream Processing: Iterator-based processing, incremental batch collection
+ - Progress Tracking: Load percentage calculation
+ - Retry Mechanism: Exponential backoff
Key Features:
- - Multiple triplet store operation methods
- - Store registration with method dispatch
- - Method dispatchers with registry support
- - Custom method registration capability
+ - Unified triplet store interface
- Consistent interface across all methods
Main Functions:
@@ -90,19 +77,16 @@ Main Functions:
- add_triplets: Multiple triplet addition wrapper
- get_triplets: Triplet retrieval wrapper
- delete_triplet: Triplet deletion wrapper
- - update_triplet: Triplet update wrapper
- execute_query: SPARQL query execution wrapper
- - optimize_query: Query optimization wrapper
- bulk_load: Bulk loading wrapper
- - validate_triplets: Triplet validation wrapper
- get_triplet_store_method: Get triplet store method by task and name
- list_available_methods: List registered methods
Example Usage:
>>> from semantica.triplet_store.methods import register_store, add_triplet, execute_query
- >>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph", method="default")
- >>> result = add_triplet(triplet, store_id="main", method="default")
- >>> query_result = execute_query(sparql_query, store_backend, method="default")
+ >>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+ >>> result = add_triplet(triplet, store_id="main")
+ >>> query_result = execute_query(sparql_query, store_backend)
"""
from typing import Any, Dict, List, Optional, Union
@@ -112,38 +96,65 @@ from .bulk_loader import BulkLoader, LoadProgress
from .config import triplet_store_config
from .query_engine import QueryEngine, QueryPlan, QueryResult
from .registry import method_registry
-from .triplet_manager import TripletManager, TripletStore
+from .triplet_store import TripletStore
-# Global manager instances
-_global_manager: Optional[TripletManager] = None
+# Global store registry
+_global_stores: Dict[str, TripletStore] = {}
+_default_store_id: Optional[str] = None
_global_query_engine: Optional[QueryEngine] = None
_global_bulk_loader: Optional[BulkLoader] = None
-def _get_manager() -> TripletManager:
- """Get or create global TripletManager instance."""
- global _global_manager
- if _global_manager is None:
- config = triplet_store_config.get_all()
- _global_manager = TripletManager(config=config)
- return _global_manager
+def _get_store(store_id: Optional[str] = None) -> TripletStore:
+ """Get triplet store instance."""
+ global _default_store_id
+
+ target_id = store_id or _default_store_id
+
+ if not target_id:
+ # Try to create a default store from config if none registered
+ if not _global_stores:
+ config = triplet_store_config.get_all()
+ default_backend = config.get("default_backend", "blazegraph")
+ default_endpoint = config.get(f"{default_backend}_endpoint", "http://localhost:9999/blazegraph")
+
+ store = TripletStore(backend=default_backend, endpoint=default_endpoint)
+ _global_stores["default"] = store
+ _default_store_id = "default"
+ return store
+
+ raise ValueError("No store identifier provided and no default store set")
+
+ if target_id not in _global_stores:
+ raise ValueError(f"Store not found: {target_id}")
+
+ return _global_stores[target_id]
def _get_query_engine() -> QueryEngine:
"""Get or create global QueryEngine instance."""
global _global_query_engine
if _global_query_engine is None:
+ # We need a store backend for the engine, but QueryEngine in this module
+ # seems to be initialized with config in the old code.
+ # In the new code, TripletStore has its own query_engine.
+ # If we use this standalone function, we might need to rely on the store's engine.
+ # But let's keep a standalone one if needed, or better, delegate to store.
config = triplet_store_config.get_all()
- _global_query_engine = QueryEngine(config=config)
- return _global_query_engine
+ # QueryEngine now expects a backend, but we can initialize it without one
+ # if we pass the backend at execution time?
+ # Checking QueryEngine implementation... it takes `store_backend` in __init__.
+ # So we can't easily have a global one without a store.
+ # We'll rely on the store's engine.
+ pass
+ return None # Deprecated use of global engine
def _get_bulk_loader() -> BulkLoader:
"""Get or create global BulkLoader instance."""
global _global_bulk_loader
if _global_bulk_loader is None:
- config = triplet_store_config.get_all()
- _global_bulk_loader = BulkLoader(config=config)
+ _global_bulk_loader = BulkLoader()
return _global_bulk_loader
@@ -155,7 +166,7 @@ def register_store(
Args:
store_id: Store identifier
- store_type: Store type (blazegraph, jena, rdf4j, virtuoso)
+ store_type: Store type (blazegraph, jena, rdf4j)
endpoint: Store endpoint URL
method: Registration method name (default: "default")
**options: Additional options
@@ -169,8 +180,15 @@ def register_store(
return custom_method(store_id, store_type, endpoint, **options)
# Default implementation
- manager = _get_manager()
- return manager.register_store(store_id, store_type, endpoint, **options)
+ store = TripletStore(backend=store_type, endpoint=endpoint, **options)
+
+ global _default_store_id
+ _global_stores[store_id] = store
+
+ if _default_store_id is None:
+ _default_store_id = store_id
+
+ return store
def add_triplet(
@@ -194,8 +212,8 @@ def add_triplet(
return custom_method(triplet, store_id=store_id, **options)
# Default implementation
- manager = _get_manager()
- return manager.add_triplet(triplet, store_id=store_id, **options)
+ store = _get_store(store_id)
+ return store.add_triplet(triplet, **options)
def add_triplets(
@@ -222,8 +240,8 @@ def add_triplets(
return custom_method(triplets, store_id=store_id, **options)
# Default implementation
- manager = _get_manager()
- return manager.add_triplets(triplets, store_id=store_id, **options)
+ store = _get_store(store_id)
+ return store.add_triplets(triplets, **options)
def get_triplets(
@@ -254,8 +272,8 @@ def get_triplets(
return custom_method(subject, predicate, object, store_id=store_id, **options)
# Default implementation
- manager = _get_manager()
- return manager.get_triplets(subject, predicate, object, store_id=store_id, **options)
+ store = _get_store(store_id)
+ return store.get_triplets(subject, predicate=predicate, object=object, **options)
def delete_triplet(
@@ -279,8 +297,15 @@ def delete_triplet(
return custom_method(triplet, store_id=store_id, **options)
# Default implementation
- manager = _get_manager()
- return manager.delete_triplet(triplet, store_id=store_id, **options)
+ # TripletStore doesn't explicitly have delete_triplet yet in my read of it?
+ # Let's check TripletStore again. It has add, add_triplets, get_triplets.
+ # It might be missing delete_triplet! I need to check.
+ # If it is missing, I should add it.
+ store = _get_store(store_id)
+ if hasattr(store, "delete_triplet"):
+ return store.delete_triplet(triplet, **options)
+ # Fallback or error if not implemented
+ raise NotImplementedError("delete_triplet not implemented in TripletStore yet")
def update_triplet(
@@ -309,19 +334,26 @@ def update_triplet(
return custom_method(old_triplet, new_triplet, store_id=store_id, **options)
# Default implementation
- manager = _get_manager()
- return manager.update_triplet(old_triplet, new_triplet, store_id=store_id, **options)
+ # Delete then Add
+ delete_res = delete_triplet(old_triplet, store_id=store_id, **options)
+ add_res = add_triplet(new_triplet, store_id=store_id, **options)
+
+ return {
+ "success": delete_res.get("success", False) and add_res.get("success", False),
+ "delete_result": delete_res,
+ "add_result": add_res
+ }
def execute_query(
- query: str, store_backend: Any, method: str = "default", **options
+ query: str, store_backend: Any = None, method: str = "default", **options
) -> QueryResult:
"""
Execute SPARQL query.
Args:
query: SPARQL query string
- store_backend: Triplet store backend instance
+ store_backend: Triplet store backend instance or TripletStore object
method: Query method name (default: "default")
**options: Additional options
@@ -334,8 +366,24 @@ def execute_query(
return custom_method(query, store_backend, **options)
# Default implementation
- engine = _get_query_engine()
- return engine.execute_query(query, store_backend, **options)
+ if isinstance(store_backend, TripletStore):
+ return store_backend.query_engine.execute_query(query, store_backend._store_backend, **options)
+ elif hasattr(store_backend, "execute_query"):
+ # It might be the backend itself
+ # But QueryEngine expects a backend.
+ # If store_backend is None, use default store
+ if store_backend is None:
+ store = _get_store()
+ return store.query_engine.execute_query(query, store._store_backend, **options)
+
+ # If it's a backend, we need an engine.
+ # We can create one on the fly or use global if we had one.
+ engine = QueryEngine(store_backend)
+ return engine.execute_query(query, store_backend, **options)
+
+ # Fallback
+ store = _get_store()
+ return store.query_engine.execute_query(query, store._store_backend, **options)
def optimize_query(query: str, method: str = "default", **options) -> str:
@@ -356,8 +404,9 @@ def optimize_query(query: str, method: str = "default", **options) -> str:
return custom_method(query, **options)
# Default implementation
- engine = _get_query_engine()
- return engine.optimize_query(query, **options)
+ # We need a store to get its engine
+ store = _get_store()
+ return store.query_engine.optimize_query(query, **options)
def plan_query(query: str, **options) -> QueryPlan:
@@ -371,12 +420,12 @@ def plan_query(query: str, **options) -> QueryPlan:
Returns:
Query execution plan
"""
- engine = _get_query_engine()
- return engine.plan_query(query, **options)
+ store = _get_store()
+ return store.query_engine.plan_query(query, **options)
def bulk_load(
- triplets: List[Triplet], store_backend: Any, method: str = "default", **options
+ triplets: List[Triplet], store_backend: Any = None, method: str = "default", **options
) -> LoadProgress:
"""
Load triplets in bulk.
@@ -396,6 +445,10 @@ def bulk_load(
return custom_method(triplets, store_backend, **options)
# Default implementation
+ if store_backend is None:
+ store = _get_store()
+ return store.bulk_loader.load_triplets(triplets, store._store_backend, **options)
+
loader = _get_bulk_loader()
return loader.load_triplets(triplets, store_backend, **options)
diff --git a/semantica/triplet_store/triplet_manager.py b/semantica/triplet_store/triplet_manager.py
deleted file mode 100644
index 2d686643..00000000
--- a/semantica/triplet_store/triplet_manager.py
+++ /dev/null
@@ -1,345 +0,0 @@
-"""
-Triplet Manager Module
-
-This module provides comprehensive CRUD operations for RDF triplets and triplet
-store management, enabling unified access to multiple triplet store backends
-through a common interface.
-
-Key Features:
- - CRUD operations for RDF triplets
- - Multi-store management and registration
- - Batch operations and bulk loading
- - Triplet validation and consistency
- - Store backend pattern
- - Error handling and recovery
-
-Main Classes:
- - TripletManager: Main triplet store management coordinator
- - TripletStore: Triplet store configuration dataclass
-
-Example Usage:
- >>> from semantica.triplet_store import TripletManager
- >>> manager = TripletManager()
- >>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
- >>> result = manager.add_triplet(triplet, store_id="main")
- >>> triplets = manager.get_triplets(subject="http://example.org/entity1")
- >>> result = manager.add_triplets(triplet_list, store_id="main", batch_size=1000)
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
-
-from ..semantic_extract.triplet_extractor import Triplet
-from ..utils.exceptions import ProcessingError, ValidationError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-
-@dataclass
-class TripletStore:
- """Triplet store configuration."""
-
- store_id: str
- store_type: str # "blazegraph", "jena", "rdf4j", "virtuoso"
- endpoint: str
- config: Dict[str, Any] = field(default_factory=dict)
- connected: bool = False
-
-
-class TripletManager:
- """
- Triplet store management system.
-
- • CRUD operations for RDF triplets
- • Batch operations and bulk loading
- • Triplet validation and consistency
- • Transaction support
- • Performance optimization
- • Error handling and recovery
- """
-
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
- """
- Initialize triplet manager.
-
- Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - default_store: Default triplet store to use
- """
- self.logger = get_logger("triplet_manager")
- self.config = config or {}
- self.config.update(kwargs)
- self.progress_tracker = get_progress_tracker()
-
- self.stores: Dict[str, TripletStore] = {}
- self.default_store_id = self.config.get("default_store")
-
- def register_store(
- self, store_id: str, store_type: str, endpoint: str, **config
- ) -> TripletStore:
- """
- Register a triplet store.
-
- Args:
- store_id: Store identifier
- store_type: Store type
- endpoint: Store endpoint URL
- **config: Additional configuration
-
- Returns:
- Registered store
- """
- store = TripletStore(
- store_id=store_id, store_type=store_type, endpoint=endpoint, config=config
- )
-
- self.stores[store_id] = store
-
- if not self.default_store_id:
- self.default_store_id = store_id
-
- self.logger.info(f"Registered triplet store: {store_id} ({store_type})")
-
- return store
-
- def add_triplet(
- self, triplet: Triplet, store_id: Optional[str] = None, **options
- ) -> Dict[str, Any]:
- """
- Add single triplet to store.
-
- Args:
- triplet: Triplet to add
- store_id: Store identifier (uses default if not provided)
- **options: Additional options
-
- Returns:
- Operation status
- """
- store = self._get_store(store_id)
-
- # Validate triplet
- if not self._validate_triplet(triplet):
- raise ValidationError("Invalid triplet")
-
- # Add to store (delegates to backend)
- try:
- store_backend = self._get_store_backend(store)
- result = store_backend.add_triplet(triplet, **options)
-
- return {
- "success": True,
- "store_id": store.store_id,
- "triplet": triplet,
- **result,
- }
- except Exception as e:
- self.logger.error(f"Failed to add triplet: {e}")
- raise ProcessingError(f"Failed to add triplet: {e}")
-
- def add_triplets(
- self, triplets: List[Triplet], store_id: Optional[str] = None, **options
- ) -> Dict[str, Any]:
- """
- Add multiple triplets to store.
-
- Args:
- triplets: List of triplets
- store_id: Store identifier
- **options: Additional options:
- - batch_size: Batch size for bulk operations
- - validate: Validate triplets before adding
-
- Returns:
- Operation status
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="triplet_store",
- submodule="TripletManager",
- message=f"Adding {len(triplets)} triplets to store",
- )
-
- try:
- store = self._get_store(store_id)
-
- # Validate triplets
- if options.get("validate", True):
- self.progress_tracker.update_tracking(
- tracking_id, message="Validating triplets..."
- )
- valid_triplets = [t for t in triplets if self._validate_triplet(t)]
- invalid_count = len(triplets) - len(valid_triplets)
- if invalid_count > 0:
- self.logger.warning(f"{invalid_count} invalid triplets filtered out")
- else:
- valid_triplets = triplets
-
- # Add to store
- store_backend = self._get_store_backend(store)
- batch_size = options.get("batch_size", 1000)
- total_batches = (len(valid_triplets) + batch_size - 1) // batch_size
-
- results = []
- for i in range(0, len(valid_triplets), batch_size):
- batch_num = i // batch_size + 1
- self.progress_tracker.update_tracking(
- tracking_id,
- message=f"Processing batch {batch_num}/{total_batches}...",
- )
- batch = valid_triplets[i : i + batch_size]
- result = store_backend.add_triplets(batch, **options)
- results.append(result)
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Added {len(valid_triplets)} triplets in {len(results)} batches",
- )
- return {
- "success": True,
- "store_id": store.store_id,
- "total_triplets": len(valid_triplets),
- "batches": len(results),
- "results": results,
- }
- except Exception as e:
- self.logger.error(f"Failed to add triplets: {e}")
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Failed to add triplets: {e}")
-
- def get_triplets(
- self,
- subject: str,
- predicate: Optional[str] = None,
- object: Optional[str] = None,
- store_id: Optional[str] = None,
- **options,
- ) -> List[Triplet]:
- """
- Get triplets matching criteria.
-
- Args:
- subject: Subject URI
- predicate: Optional predicate URI
- object: Optional object URI
- store_id: Store identifier
- **options: Additional options
-
- Returns:
- List of matching triplets
- """
- store = self._get_store(store_id)
-
- try:
- store_backend = self._get_store_backend(store)
- return store_backend.get_triplets(subject, predicate, object, **options)
- except Exception as e:
- self.logger.error(f"Failed to get triplets: {e}")
- raise ProcessingError(f"Failed to get triplets: {e}")
-
- def delete_triplet(
- self, triplet: Triplet, store_id: Optional[str] = None, **options
- ) -> Dict[str, Any]:
- """
- Delete triplet from store.
-
- Args:
- triplet: Triplet to delete
- store_id: Store identifier
- **options: Additional options
-
- Returns:
- Operation status
- """
- store = self._get_store(store_id)
-
- try:
- store_backend = self._get_store_backend(store)
- result = store_backend.delete_triplet(triplet, **options)
-
- return {"success": True, "store_id": store.store_id, **result}
- except Exception as e:
- self.logger.error(f"Failed to delete triplet: {e}")
- raise ProcessingError(f"Failed to delete triplet: {e}")
-
- def update_triplet(
- self,
- old_triplet: Triplet,
- new_triplet: Triplet,
- store_id: Optional[str] = None,
- **options,
- ) -> Dict[str, Any]:
- """
- Update triplet in store.
-
- Args:
- old_triplet: Original triplet
- new_triplet: Updated triplet
- store_id: Store identifier
- **options: Additional options
-
- Returns:
- Operation status
- """
- # Delete old and add new
- self.delete_triplet(old_triplet, store_id, **options)
- return self.add_triplet(new_triplet, store_id, **options)
-
- def _validate_triplet(self, triplet: Triplet) -> bool:
- """Validate triplet structure."""
- if not triplet.subject or not triplet.predicate or not triplet.object:
- return False
-
- if triplet.confidence < 0 or triplet.confidence > 1:
- return False
-
- return True
-
- def _get_store(self, store_id: Optional[str] = None) -> TripletStore:
- """Get store by ID."""
- store_id = store_id or self.default_store_id
-
- if not store_id:
- raise ValidationError("No store specified and no default store configured")
-
- if store_id not in self.stores:
- raise ValidationError(f"Store not found: {store_id}")
-
- return self.stores[store_id]
-
- def _get_store_backend(self, store: TripletStore) -> Any:
- """Get backend store for store type."""
- store_type = store.store_type.lower()
-
- if store_type == "blazegraph":
- from .blazegraph_store import BlazegraphStore
-
- return BlazegraphStore(endpoint=store.endpoint, **store.config)
- elif store_type == "jena":
- from .jena_store import JenaStore
-
- return JenaStore(**store.config)
- elif store_type == "rdf4j":
- from .rdf4j_store import RDF4JStore
-
- return RDF4JStore(endpoint=store.endpoint, **store.config)
- elif store_type == "virtuoso":
- from .virtuoso_store import VirtuosoStore
-
- return VirtuosoStore(endpoint=store.endpoint, **store.config)
- else:
- raise ValidationError(f"Unsupported store type: {store_type}")
-
- def get_store(self, store_id: str) -> Optional[TripletStore]:
- """Get store by ID."""
- return self.stores.get(store_id)
-
- def list_stores(self) -> List[str]:
- """List all store IDs."""
- return list(self.stores.keys())
diff --git a/semantica/triplet_store/triplet_store.py b/semantica/triplet_store/triplet_store.py
new file mode 100644
index 00000000..6c110264
--- /dev/null
+++ b/semantica/triplet_store/triplet_store.py
@@ -0,0 +1,277 @@
+"""
+Triplet Store Core Module
+
+This module provides the core triplet store interface and management classes,
+providing a unified interface across multiple RDF store backends
+(Blazegraph, Jena, RDF4J).
+
+Key Features:
+ - Unified triplet store interface
+ - Multi-backend support (Blazegraph, Jena, RDF4J)
+ - CRUD operations for RDF triplets
+ - SPARQL query execution
+ - Bulk loading and batch processing
+ - Configuration management
+
+Main Classes:
+ - TripletStore: Main triplet store interface
+
+Example Usage:
+ >>> from semantica.triplet_store import TripletStore
+ >>> store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
+ >>> store.add_triplet(triplet)
+ >>> results = store.execute_query("SELECT * WHERE { ?s ?p ?o } LIMIT 10")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+from typing import Any, Dict, List, Optional, Union
+
+from ..semantic_extract.triplet_extractor import Triplet
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
+from .bulk_loader import BulkLoader
+from .config import triplet_store_config
+from .query_engine import QueryEngine
+
+
+class TripletStore:
+ """
+ Main triplet store interface.
+
+ Provides a unified interface for working with RDF triple stores,
+ supporting Blazegraph, Jena, and RDF4J backends.
+ """
+
+ SUPPORTED_BACKENDS = {"blazegraph", "jena", "rdf4j"}
+
+ def __init__(
+ self,
+ backend: str = "blazegraph",
+ endpoint: Optional[str] = None,
+ **config,
+ ):
+ """
+ Initialize triplet store.
+
+ Args:
+ backend: Backend type ("blazegraph", "jena", "rdf4j")
+ endpoint: Store endpoint URL
+ **config: Backend-specific configuration
+ """
+ self.logger = get_logger("triplet_store")
+ self.progress_tracker = get_progress_tracker()
+
+ # Validate backend
+ if backend.lower() not in self.SUPPORTED_BACKENDS:
+ raise ValueError(
+ f"Unsupported backend: {backend}. "
+ f"Supported backends are: {', '.join(sorted(self.SUPPORTED_BACKENDS))}"
+ )
+
+ self.backend_type = backend.lower()
+ self.endpoint = endpoint
+ self.config = config
+
+ # Initialize store backend
+ self._store_backend = None
+ self._initialize_store_backend()
+
+ # Initialize components
+ self.query_engine = QueryEngine(self.config)
+ self.bulk_loader = BulkLoader()
+
+ def _initialize_store_backend(self) -> None:
+ """Initialize the appropriate store backend based on backend type."""
+ try:
+ if self.backend_type == "blazegraph":
+ from .blazegraph_store import BlazegraphStore
+
+ # Merge config with defaults
+ backend_config = self.config.copy()
+ if self.endpoint:
+ backend_config["endpoint"] = self.endpoint
+
+ self._store_backend = BlazegraphStore(**backend_config)
+
+ elif self.backend_type == "jena":
+ from .jena_store import JenaStore
+
+ backend_config = self.config.copy()
+ if self.endpoint:
+ # JenaStore might use different param names or structure
+ # Assuming JenaStore accepts endpoint or url
+ backend_config["url"] = self.endpoint
+
+ self._store_backend = JenaStore(**backend_config)
+
+ elif self.backend_type == "rdf4j":
+ from .rdf4j_store import RDF4JStore
+
+ backend_config = self.config.copy()
+ if self.endpoint:
+ backend_config["endpoint"] = self.endpoint
+
+ self._store_backend = RDF4JStore(**backend_config)
+
+ self.logger.info(f"Initialized {self.backend_type} backend")
+
+ except Exception as e:
+ self.logger.error(f"Failed to initialize {self.backend_type} backend: {e}")
+ raise ProcessingError(f"Failed to initialize backend: {e}")
+
+ def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """
+ Add a single triplet to the store.
+
+ Args:
+ triplet: Triplet object to add
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ if not self._validate_triplet(triplet):
+ raise ValidationError("Invalid triplet structure or confidence")
+
+ return self._store_backend.add_triplet(triplet, **options)
+
+ def add_triplets(
+ self,
+ triplets: List[Triplet],
+ batch_size: int = 1000,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Add multiple triplets to the store (bulk load).
+
+ Args:
+ triplets: List of Triplet objects
+ batch_size: Batch size for processing
+ **options: Additional options
+
+ Returns:
+ Operation status with stats
+ """
+ # Validate triplets first
+ valid_triplets = [t for t in triplets if self._validate_triplet(t)]
+ if len(valid_triplets) < len(triplets):
+ self.logger.warning(
+ f"Filtered {len(triplets) - len(valid_triplets)} invalid triplets"
+ )
+
+ # Use bulk loader for efficient processing
+ progress = self.bulk_loader.load_triplets(
+ valid_triplets,
+ self._store_backend,
+ batch_size=batch_size,
+ **options
+ )
+
+ return {
+ "success": progress.failed_batches == 0,
+ "total": progress.total_triplets,
+ "processed": progress.processed_triplets,
+ "failed": progress.failed_triplets,
+ "batches": progress.total_batches
+ }
+
+ def get_triplets(
+ self,
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ **options,
+ ) -> List[Triplet]:
+ """
+ Retrieve triplets matching criteria.
+
+ Args:
+ subject: Subject URI
+ predicate: Predicate URI
+ object: Object URI
+ **options: Additional options
+
+ Returns:
+ List of matching Triplet objects
+ """
+ return self._store_backend.get_triplets(
+ subject=subject,
+ predicate=predicate,
+ object=object,
+ **options
+ )
+
+ def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
+ """
+ Delete a triplet from the store.
+
+ Args:
+ triplet: Triplet to delete
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ return self._store_backend.delete_triplet(triplet, **options)
+
+ def update_triplet(
+ self,
+ old_triplet: Triplet,
+ new_triplet: Triplet,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Update a triplet (atomic delete + add).
+
+ Args:
+ old_triplet: Triplet to remove
+ new_triplet: Triplet to add
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ # Simple implementation: delete then add
+ # Some backends might support atomic updates
+ self.delete_triplet(old_triplet, **options)
+ return self.add_triplet(new_triplet, **options)
+
+ def execute_query(
+ self,
+ query: str,
+ parameters: Optional[Dict[str, Any]] = None,
+ **options
+ ) -> Any:
+ """
+ Execute a SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ parameters: Query parameters
+ **options: Additional options
+
+ Returns:
+ Query results (format depends on query type)
+ """
+ return self.query_engine.execute_query(query, self._store_backend, **options)
+
+ def _validate_triplet(self, triplet: Triplet) -> bool:
+ """Validate triplet structure."""
+ if not triplet.subject or not triplet.predicate or not triplet.object:
+ return False
+
+ # Check confidence score if present
+ if hasattr(triplet, 'confidence'):
+ if triplet.confidence is not None and (triplet.confidence < 0 or triplet.confidence > 1):
+ return False
+
+ return True
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get store statistics."""
+ if hasattr(self._store_backend, "get_stats"):
+ return self._store_backend.get_stats()
+ return {}
diff --git a/semantica/triplet_store/triplet_store_usage.md b/semantica/triplet_store/triplet_store_usage.md
index 12b8a83f..bbf33c85 100644
--- a/semantica/triplet_store/triplet_store_usage.md
+++ b/semantica/triplet_store/triplet_store_usage.md
@@ -1,6 +1,6 @@
# Triplet Store Module Usage Guide
-This comprehensive guide demonstrates how to use the triplet store module for RDF data storage and querying, supporting multiple triplet store backends (Blazegraph, Jena, RDF4J, Virtuoso) with unified interfaces, SPARQL query execution, bulk loading, and query optimization.
+This comprehensive guide demonstrates how to use the triplet store module for RDF data storage and querying, supporting multiple triplet store backends (Blazegraph, Jena, RDF4J) with unified interfaces, SPARQL query execution, bulk loading, and query optimization.
## Table of Contents
@@ -11,23 +11,21 @@ This comprehensive guide demonstrates how to use the triplet store module for RD
5. [Query Optimization](#query-optimization)
6. [Bulk Loading](#bulk-loading)
7. [Store Backends](#store-backends)
-8. [Algorithms and Methods](#algorithms-and-methods)
-9. [Configuration](#configuration)
-10. [Advanced Examples](#advanced-examples)
+8. [Configuration](#configuration)
## Basic Usage
-### Using TripletManager
+### Using TripletStore Class
```python
-from semantica.triplet_store import TripletManager
+from semantica.triplet_store import TripletStore
from semantica.semantic_extract.triplet_extractor import Triplet
-# Create triplet manager
-manager = TripletManager()
-
-# Register a store
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+# Initialize store (Blazegraph default)
+store = TripletStore(
+ backend="blazegraph",
+ endpoint="http://localhost:9999/blazegraph"
+)
# Add a triplet
triplet = Triplet(
@@ -36,7 +34,7 @@ triplet = Triplet(
object="John Doe",
confidence=0.9
)
-result = manager.add_triplet(triplet, store_id="main")
+result = store.add_triplet(triplet)
print(f"Triplet added: {result['success']}")
```
@@ -44,120 +42,16 @@ print(f"Triplet added: {result['success']}")
### Using Convenience Functions
```python
-from semantica.triplet_store import register_store, add_triplet, get_triplets, execute_query
-from semantica.semantic_extract.triplet_extractor import Triplet
+from semantica.triplet_store import register_store, add_triplet
-# Register store
+# Register a store
store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-# Add triplet
-triplet = Triplet(
- subject="http://example.org/entity1",
- predicate="http://example.org/hasName",
- object="John Doe"
-)
-result = add_triplet(triplet, store_id="main")
-
-# Get triplets
-triplets = get_triplets(subject="http://example.org/entity1", store_id="main")
-print(f"Found {len(triplets)} triplets")
-```
-
-### Using QueryEngine
-
-```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-# Create query engine
-engine = QueryEngine(enable_caching=True, enable_optimization=True)
-
-# Create store
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Execute query
-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
-result = engine.execute_query(query, store)
-
-print(f"Found {len(result.bindings)} results")
-print(f"Execution time: {result.execution_time:.2f}s")
-```
-
-## Store Registration
-
-### Registering a Store
-
-```python
-from semantica.triplet_store import TripletManager
-
-manager = TripletManager()
-
-# Register Blazegraph store
-blazegraph_store = manager.register_store(
- store_id="blazegraph",
- store_type="blazegraph",
- endpoint="http://localhost:9999/blazegraph",
- namespace="kb"
-)
-
-# Register Jena store
-jena_store = manager.register_store(
- store_id="jena",
- store_type="jena",
- endpoint="http://localhost:3030/ds",
- dataset="default"
-)
-
-# Register RDF4J store
-rdf4j_store = manager.register_store(
- store_id="rdf4j",
- store_type="rdf4j",
- endpoint="http://localhost:8080/rdf4j-server",
- repository="test"
-)
-
-# Register Virtuoso store
-virtuoso_store = manager.register_store(
- store_id="virtuoso",
- store_type="virtuoso",
- endpoint="http://localhost:8890/sparql"
-)
-```
-
-### Using Convenience Function
-
-```python
-from semantica.triplet_store import register_store
-
-# Register store using convenience function
-store = register_store(
- "main",
- "blazegraph",
- "http://localhost:9999/blazegraph",
- method="default"
+# Add a triplet
+result = add_triplet(
+ Triplet("http://s", "http://p", "http://o"),
+ store_id="main"
)
-
-print(f"Store registered: {store.store_id}")
-print(f"Store type: {store.store_type}")
-```
-
-### Multiple Stores
-
-```python
-from semantica.triplet_store import TripletManager
-
-manager = TripletManager()
-
-# Register multiple stores
-manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
-manager.register_store("secondary", "jena", "http://localhost:3030/ds")
-
-# List all stores
-store_ids = manager.list_stores()
-print(f"Registered stores: {store_ids}")
-
-# Get specific store
-store = manager.get_store("primary")
-print(f"Store endpoint: {store.endpoint}")
```
## CRUD Operations
@@ -165,120 +59,60 @@ print(f"Store endpoint: {store.endpoint}")
### Adding Triplets
```python
-from semantica.triplet_store import TripletManager
+from semantica.triplet_store import TripletStore
from semantica.semantic_extract.triplet_extractor import Triplet
-manager = TripletManager()
-manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
# Add single triplet
triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
- object="John Doe",
- confidence=0.9
+ object="John Doe"
)
-result = manager.add_triplet(triplet, store_id="main")
-print(f"Added: {result['success']}")
+result = store.add_triplet(triplet)
-# Add multiple triplets
+# Add multiple triplets (Bulk)
triplets = [
Triplet("http://example.org/entity1", "http://example.org/hasAge", "30"),
- Triplet("http://example.org/entity1", "http://example.org/hasCity", "New York"),
- Triplet("http://example.org/entity2", "http://example.org/hasName", "Jane Smith")
+ Triplet("http://example.org/entity1", "http://example.org/hasCity", "New York")
]
-result = manager.add_triplets(triplets, store_id="main", batch_size=1000)
-print(f"Added {result['total_triplets']} triplets in {result['batches']} batches")
+result = store.add_triplets(triplets, batch_size=1000)
+print(f"Added {result['total']} triplets")
```
### Retrieving Triplets
```python
-from semantica.triplet_store import TripletManager
-
-manager = TripletManager()
-manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-
# Get all triplets for a subject
-triplets = manager.get_triplets(
- subject="http://example.org/entity1",
- store_id="main"
-)
-print(f"Found {len(triplets)} triplets for entity1")
+triplets = store.get_triplets(subject="http://example.org/entity1")
# Get triplets matching predicate
-triplets = manager.get_triplets(
- predicate="http://example.org/hasName",
- store_id="main"
-)
-print(f"Found {len(triplets)} triplets with hasName predicate")
+triplets = store.get_triplets(predicate="http://example.org/hasName")
# Get specific triplet
-triplets = manager.get_triplets(
+triplets = store.get_triplets(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
- object="John Doe",
- store_id="main"
+ object="John Doe"
)
```
### Deleting Triplets
```python
-from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-manager = TripletManager()
-manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-
# Delete triplet
triplet = Triplet(
subject="http://example.org/entity1",
predicate="http://example.org/hasName",
object="John Doe"
)
-result = manager.delete_triplet(triplet, store_id="main")
-print(f"Deleted: {result['success']}")
-```
-
-### Updating Triplets
-
-```python
-from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-manager = TripletManager()
-manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-
-# Update triplet (delete old, add new)
-old_triplet = Triplet(
- subject="http://example.org/entity1",
- predicate="http://example.org/hasAge",
- object="30"
-)
-new_triplet = Triplet(
- subject="http://example.org/entity1",
- predicate="http://example.org/hasAge",
- object="31"
-)
-result = manager.update_triplet(old_triplet, new_triplet, store_id="main")
-print(f"Updated: {result['success']}")
+result = store.delete_triplet(triplet)
```
## SPARQL Query Execution
-### Basic Query Execution
-
```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-# Create query engine
-engine = QueryEngine(enable_caching=True)
-
-# Create store
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Execute SELECT query
query = """
SELECT ?s ?p ?o
WHERE {
@@ -287,851 +121,59 @@ WHERE {
}
LIMIT 10
"""
-result = engine.execute_query(query, store)
+result = store.execute_query(query)
print(f"Variables: {result.variables}")
print(f"Results: {len(result.bindings)}")
-for binding in result.bindings[:5]:
- print(binding)
-```
-
-### Using Convenience Function
-
-```python
-from semantica.triplet_store import execute_query, BlazegraphStore
-
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
-result = execute_query(query, store, method="default")
-
-print(f"Found {len(result.bindings)} results")
-```
-
-### Query Result Processing
-
-```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-engine = QueryEngine()
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-query = "SELECT ?name ?age WHERE { ?s <http://example.org/hasName> ?name . ?s <http://example.org/hasAge> ?age }"
-result = engine.execute_query(query, store)
-
-# Process results
for binding in result.bindings:
- name = binding.get("name", {}).get("value", "")
- age = binding.get("age", {}).get("value", "")
- print(f"Name: {name}, Age: {age}")
-
-print(f"Execution time: {result.execution_time:.2f}s")
-print(f"Metadata: {result.metadata}")
-```
-
-### Query Caching
-
-```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-# Enable caching
-engine = QueryEngine(enable_caching=True, cache_size=1000)
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
-
-# First execution (not cached)
-result1 = engine.execute_query(query, store)
-print(f"First execution: {result1.execution_time:.2f}s, Cached: {result1.metadata.get('cached', False)}")
-
-# Second execution (cached)
-result2 = engine.execute_query(query, store)
-print(f"Second execution: {result2.execution_time:.2f}s, Cached: {result2.metadata.get('cached', False)}")
-
-# Clear cache
-engine.clear_cache()
-```
-
-## Query Optimization
-
-### Basic Query Optimization
-
-```python
-from semantica.triplet_store import QueryEngine
-
-engine = QueryEngine(enable_optimization=True)
-
-# Original query
-query = """
-SELECT ?s ?p ?o
-WHERE {
- ?s ?p ?o .
-}
-"""
-
-# Optimize query
-optimized = engine.optimize_query(query, add_limit=True, default_limit=1000)
-print(f"Optimized query:\n{optimized}")
-```
-
-### Query Planning
-
-```python
-from semantica.triplet_store import QueryEngine
-
-engine = QueryEngine(enable_optimization=True)
-
-query = """
-SELECT ?s ?p ?o
-WHERE {
- ?s ?p ?o .
- FILTER(?o > 10)
-}
-ORDER BY ?s
-LIMIT 100
-"""
-
-# Create query plan
-plan = engine.plan_query(query)
-
-print(f"Original query: {plan.query}")
-print(f"Optimized query: {plan.optimized_query}")
-print(f"Estimated cost: {plan.estimated_cost}")
-print(f"Execution steps: {plan.execution_steps}")
-```
-
-### Query Statistics
-
-```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-engine = QueryEngine(enable_caching=True)
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Execute multiple queries
-for i in range(10):
- query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o }} LIMIT {i * 10}"
- engine.execute_query(query, store)
-
-# Get statistics
-stats = engine.get_query_statistics()
-print(f"Total queries: {stats['total_queries']}")
-print(f"Average execution time: {stats['average_execution_time']:.2f}s")
-print(f"Min execution time: {stats['min_execution_time']:.2f}s")
-print(f"Max execution time: {stats['max_execution_time']:.2f}s")
-print(f"Cache size: {stats['cache_size']}")
+ print(binding)
```
## Bulk Loading
-### Basic Bulk Loading
+The module supports high-performance bulk loading with progress tracking.
```python
-from semantica.triplet_store import BulkLoader, BlazegraphStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Create bulk loader
-loader = BulkLoader(batch_size=1000, max_retries=3)
-
-# Create store
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
+from semantica.triplet_store import BulkLoader
-# Generate triplets
-triplets = [
- Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
- for i in range(10000)
-]
+loader = BulkLoader()
+triplets = [...] # List of 10,000 triplets
# Load triplets
-progress = loader.load_triplets(triplets, store)
+progress = loader.load_triplets(triplets, store._store_backend)
print(f"Loaded: {progress.loaded_triplets}/{progress.total_triplets}")
print(f"Failed: {progress.failed_triplets}")
-print(f"Progress: {progress.progress_percentage:.1f}%")
-print(f"Elapsed time: {progress.elapsed_time:.2f}s")
-print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triplets/sec")
-```
-
-### Progress Tracking
-
-```python
-from semantica.triplet_store import BulkLoader, BlazegraphStore, LoadProgress
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-loader = BulkLoader(batch_size=1000)
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Progress callback
-def progress_callback(progress: LoadProgress):
- print(f"Batch {progress.current_batch}/{progress.total_batches}: "
- f"{progress.progress_percentage:.1f}% "
- f"({progress.loaded_triplets}/{progress.total_triplets})")
-
-# Load with progress callback
-triplets = [Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
- for i in range(5000)]
-progress = loader.load_triplets(triplets, store, progress_callback=progress_callback)
-```
-
-### Pre-load Validation
-
-```python
-from semantica.triplet_store import BulkLoader
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-loader = BulkLoader()
-
-# Create triplets (some invalid)
-triplets = [
- Triplet("http://example.org/entity1", "http://example.org/hasName", "John"), # Valid
- Triplet("", "http://example.org/hasName", "Jane"), # Invalid (empty subject)
- Triplet("http://example.org/entity3", "", "Bob"), # Invalid (empty predicate)
- Triplet("http://example.org/entity4", "http://example.org/hasAge", "30"), # Valid
-]
-
-# Validate before loading
-validation = loader.validate_before_load(triplets)
-
-print(f"Valid: {validation['valid']}")
-print(f"Errors: {validation['errors']}")
-print(f"Warnings: {validation['warnings']}")
-print(f"Valid triplets: {validation['valid_triplets']}/{validation['total_triplets']}")
-```
-
-### Stream-based Loading
-
-```python
-from semantica.triplet_store import BulkLoader, BlazegraphStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-loader = BulkLoader(batch_size=1000)
-store = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Create stream of triplets
-def triplet_stream():
- for i in range(10000):
- yield Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
-
-# Load from stream
-progress = loader.load_from_stream(triplet_stream(), store)
-print(f"Loaded {progress.loaded_triplets} triplets from stream")
```
## Store Backends
-### Blazegraph Store
-
+### Blazegraph
+High-performance graph database supporting RDF/SPARQL.
```python
-from semantica.triplet_store import BlazegraphStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Create Blazegraph store
-store = BlazegraphStore(
- endpoint="http://localhost:9999/blazegraph",
- namespace="kb",
- auth=("user", "password") # Optional
-)
-
-# Add triplets
-triplets = [
- Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
-]
-result = store.add_triplets(triplets)
-print(f"Added: {result['success']}")
-
-# Execute SPARQL query
-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
-result = store.execute_sparql(query)
-print(f"Found {len(result['bindings'])} results")
+store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
```
-### Jena Store
-
+### Jena
+Apache Jena Fuseki support.
```python
-from semantica.triplet_store import JenaStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Create Jena store (in-memory)
-store = JenaStore()
-
-# Or connect to Fuseki endpoint
-store = JenaStore(
- endpoint="http://localhost:3030/ds",
- dataset="default",
- enable_inference=True
-)
-
-## Add triplets
-triplets = [
- Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
-]
-result = store.add_triplets(triplets)
-
-# Serialize to Turtle
-turtle = store.serialize(format="turtle")
-print(turtle)
-```
-
-### RDF4J Store
-
-```python
-from semantica.triplet_store import RDF4JStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Create RDF4J store
-store = RDF4JStore(
- endpoint="http://localhost:8080/rdf4j-server",
- repository="test"
-)
-
-## Add triplets
-triplets = [
- Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
-]
-result = store.add_triplets(triplets)
-```
-
-### Virtuoso Store
-
-```python
-from semantica.triplet_store import VirtuosoStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Create Virtuoso store
-store = VirtuosoStore(
- endpoint="http://localhost:8890/sparql",
- user="dba",
- password="dba"
-)
-
-## Add triplets
-triplets = [
- Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
-]
-result = store.add_triplets(triplets)
-```
-
-## Algorithms and Methods
-
-### Store Backends
-
-#### Store Registration
-**Algorithm**: Store type detection and store factory pattern
-
-1. **Store Type Detection**: Identify backend type (blazegraph, jena, rdf4j, virtuoso)
-2. **Configuration Storage**: Store store configuration (endpoint, namespace, etc.)
-3. **Store Factory**: Create appropriate store instance based on store type
-4. **Default Store Selection**: Set first registered store as default if none specified
-
-**Time Complexity**: O(1) for registration
-**Space Complexity**: O(1) per store
-
-```python
-# Store registration
-store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-```
-
-#### Backend Pattern
-**Algorithm**: Unified interface for multiple backends
-
-1. **Interface Definition**: Common interface for all stores (add_triplet, execute_sparql, etc.)
-2. **Backend-Specific Implementation**: Each store implements interface for its backend
-3. **Store Instantiation**: Create store instance on-demand
-4. **Operation Delegation**: Delegate operations to appropriate store
-
-**Time Complexity**: O(1) for store creation
-**Space Complexity**: O(1) per store
-
-### CRUD Operations Algorithms
-
-#### Triplet Addition
-**Algorithm**: Single and batch triplet insertion
-
-1. **Triplet Validation**: Check required fields (subject, predicate, object), validate confidence (0-1)
-2. **Store Selection**: Get store for specified store
-3. **Operation Delegation**: Delegate to store's add_triplet/add_triplets method
-4. **Result Processing**: Process and return operation result
-
-**Time Complexity**: O(1) for single, O(n) for batch where n = triplets
-**Space Complexity**: O(1) for single, O(n) for batch
-
-```python
-# Triplet addition
-result = manager.add_triplet(triplet, store_id="main")
-result = manager.add_triplets(triplets, store_id="main", batch_size=1000)
-```
-
-#### Triplet Retrieval
-**Algorithm**: Pattern-based triplet retrieval
-
-1. **Pattern Construction**: Build SPARQL query from subject/predicate/object patterns
-2. **Query Execution**: Execute SPARQL query via store
-3. **Result Binding Extraction**: Extract bindings from query result
-4. **Triplet Reconstruction**: Convert bindings to Triplet objects
-
-**Time Complexity**: O(n) where n = result count
-**Space Complexity**: O(n) for results
-
-```python
-# Triplet retrieval
-triplets = manager.get_triplets(subject="http://example.org/entity1", store_id="main")
-```
-
-### Bulk Loading Algorithms
-
-#### Batch Processing
-**Algorithm**: Chunking algorithm for large datasets
-
-1. **Batch Creation**: Divide triplets into fixed-size batches
-2. **Batch Processing**: Process each batch sequentially
-3. **Progress Tracking**: Track loaded count, failed count, progress percentage
-4. **Error Handling**: Retry failed batches with exponential backoff
-
-**Time Complexity**: O(n) where n = total triplets
-**Space Complexity**: O(b) where b = batch size
-
-```python
-# Batch processing
-progress = loader.load_triplets(triplets, store, batch_size=1000)
+store = TripletStore(backend="jena", endpoint="http://localhost:3030/ds")
```
-#### Progress Tracking
-**Algorithm**: Load progress calculation
-
-1. **Progress Calculation**: loaded_triplets / total_triplets * 100
-2. **Elapsed Time Tracking**: Track time since start
-3. **Estimated Remaining**: (elapsed / loaded) * (total - loaded)
-4. **Throughput Calculation**: loaded_triplets / elapsed_time
-
-**Time Complexity**: O(1) per update
-**Space Complexity**: O(1)
-
-#### Retry Mechanism
-**Algorithm**: Exponential backoff retry
-
-1. **Retry Attempt**: Try batch load operation
-2. **Failure Detection**: Catch exceptions
-3. **Backoff Calculation**: delay = retry_delay * (attempt + 1)
-4. **Max Retry Check**: Stop after max_retries attempts
-
-**Time Complexity**: O(r) where r = max_retries
-**Space Complexity**: O(1)
-
-### SPARQL Query Execution Algorithms
-
-#### Query Validation
-**Algorithm**: Syntax validation and query type detection
-
-1. **Keyword Checking**: Check for valid SPARQL keywords (SELECT, ASK, CONSTRUCT, etc.)
-2. **Structure Validation**: Validate query structure
-3. **Query Type Detection**: Identify query type (SELECT, ASK, CONSTRUCT, DESCRIBE, INSERT, DELETE)
-
-**Time Complexity**: O(n) where n = query length
-**Space Complexity**: O(1)
-
-```python
-# Query validation
-is_valid = engine._validate_query(query)
-```
-
-#### Query Optimization
-**Algorithm**: Basic query optimization
-
-1. **Whitespace Normalization**: Remove unnecessary whitespace
-2. **LIMIT Injection**: Add LIMIT clause if SELECT query doesn't have one
-3. **Query Rewriting**: Simplify query structure
-
-**Time Complexity**: O(n) where n = query length
-**Space Complexity**: O(n) for optimized query
-
+### RDF4J
+Eclipse RDF4J support.
```python
-# Query optimization
-optimized = engine.optimize_query(query, add_limit=True, default_limit=1000)
+store = TripletStore(backend="rdf4j", endpoint="http://localhost:8080/rdf4j-server")
```
-#### Query Caching
-**Algorithm**: MD5-based cache key generation and LRU-style eviction
-
-1. **Cache Key Generation**: MD5 hash of normalized query
-2. **Cache Lookup**: Check if query result is cached
-3. **Cache Storage**: Store query result with cache key
-4. **Cache Eviction**: Remove oldest entry when cache is full
-
-**Time Complexity**: O(1) for lookup/storage
-**Space Complexity**: O(c) where c = cache size
-
-```python
-# Query caching
-result = engine.execute_query(query, adapter) # Cached on second call
-```
-
-#### Cost Estimation
-**Algorithm**: Heuristic-based cost calculation
-
-1. **Base Cost**: Start with base cost of 1.0
-2. **COUNT Detection**: Multiply by 2.0 if COUNT query
-3. **Join Count**: Multiply by (1.0 + join_count * 0.1)
-4. **DISTINCT Detection**: Multiply by 1.5 if DISTINCT
-
-**Time Complexity**: O(n) where n = query length
-**Space Complexity**: O(1)
-
-```python
-# Cost estimation
-cost = engine._estimate_query_cost(query)
-```
-
-### Methods
-
-#### TripletManager Methods
-
-- `register_store(store_id, store_type, endpoint, **config)`: Register triplet store
-- `add_triplet(triple, store_id, **options)`: Add single triple
-- `add_triples(triples, store_id, **options)`: Add multiple triples
-- `get_triplets(subject, predicate, object, store_id, **options)`: Get triplets matching pattern
-- `delete_triplet(triple, store_id, **options)`: Delete triple
-- `update_triplet(old_triple, new_triple, store_id, **options)`: Update triple
-- `get_store(store_id)`: Get store by ID
-- `list_stores()`: List all store IDs
-
-#### QueryEngine Methods
-
-- `execute_query(query, store_backend, **options)`: Execute SPARQL query
-- `optimize_query(query, **options)`: Optimize SPARQL query
-- `plan_query(query, **options)`: Create query execution plan
-- `clear_cache()`: Clear query cache
-- `get_query_statistics()`: Get query execution statistics
-
-#### BulkLoader Methods
-
-- `load_triples(triples, store_backend, **options)`: Load triplets in bulk
-- `load_from_file(file_path, store_backend, **options)`: Load triplets from file
-- `load_from_stream(triples_stream, store_backend, **options)`: Load triplets from stream
-- `validate_before_load(triples, **options)`: Validate triplets before loading
-
-#### Convenience Functions
-
-- `register_store(store_id, store_type, endpoint, method, **options)`: Register store wrapper
-- `add_triplet(triple, store_id, method, **options)`: Add triplet wrapper
-- `add_triples(triples, store_id, method, **options)`: Add triplets wrapper
-- `get_triples(subject, predicate, object, store_id, method, **options)`: Get triplets wrapper
-- `delete_triplet(triple, store_id, method, **options)`: Delete triplet wrapper
-- `update_triplet(old_triple, new_triple, store_id, method, **options)`: Update triplet wrapper
-- `execute_query(query, store_backend, method, **options)`: Execute query wrapper
-- `optimize_query(query, method, **options)`: Optimize query wrapper
-- `bulk_load(triples, store_backend, method, **options)`: Bulk load wrapper
-- `validate_triples(triples, method, **options)`: Validate triplets wrapper
-
-## Dataclasses
-
-### TripletStore
-
-Configuration dataclass for triplet store instances.
-
-```python
-from semantica.triplet_store import TripletStore
-
-store = TripletStore(
- store_id="main",
- store_type="blazegraph",
- endpoint="http://localhost:9999/blazegraph/sparql",
- config={
- "namespace": "kb",
- "timeout": 30
- }
-)
-
-print(f"Store ID: {store.store_id}")
-print(f"Type: {store.store_type}")
-```
-
-**Attributes:**
-- `store_id` (str): Unique store identifier
-- `store_type` (str): Backend type (blazegraph, jena, rdf4j, virtuoso)
-- `endpoint` (str): SPARQL endpoint URL
-- `config` (dict): Additional configuration options
-
-### QueryResult
-
-Query execution result dataclass.
-
-```python
-from semantica.triplet_store import QueryEngine, QueryResult
-
-engine = QueryEngine()
-result: QueryResult = engine.execute_query(query, adapter)
-
-print(f"Variables: {result.variables}")
-print(f"Results: {len(result.bindings)}")
-print(f"Execution time: {result.execution_time:.2f}s")
-```
-
-**Attributes:**
-- `variables` (List[str]): Query variable names
-- `bindings` (List[Dict]): Result bindings
-- `execution_time` (float): Query execution time in seconds
-- `metadata` (Dict): Additional metadata (cached, optimized, etc.)
-
-### QueryPlan
-
-Query execution plan dataclass.
-
-```python
-from semantica.triplet_store import QueryEngine, QueryPlan
-
-engine = QueryEngine(enable_optimization=True)
-plan: QueryPlan = engine.plan_query(query)
-
-print(f"Estimated cost: {plan.estimated_cost}")
-print(f"Execution steps: {plan.execution_steps}")
-```
-
-**Attributes:**
-- `query` (str): Original SPARQL query
-- `optimized_query` (str): Optimized query
-- `estimated_cost` (float): Estimated execution cost
-- `execution_steps` (List[str]): Planned execution steps
-
## Configuration
-### Environment Variables
-
-```bash
-# Triplet store configuration
-export TRIPLET_STORE_DEFAULT_STORE=main
-export TRIPLET_STORE_BATCH_SIZE=1000
-export TRIPLET_STORE_ENABLE_CACHING=true
-export TRIPLET_STORE_CACHE_SIZE=1000
-export TRIPLET_STORE_ENABLE_OPTIMIZATION=true
-export TRIPLET_STORE_MAX_RETRIES=3
-export TRIPLET_STORE_RETRY_DELAY=1.0
-export TRIPLET_STORE_TIMEOUT=30
-
-# Store endpoints
-export TRIPLET_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph
-export TRIPLET_STORE_JENA_ENDPOINT=http://localhost:3030/ds
-export TRIPLET_STORE_RDF4J_ENDPOINT=http://localhost:8080/rdf4j-server
-export TRIPLET_STORE_VIRTUOSO_ENDPOINT=http://localhost:8890/sparql
-```
-
-### Programmatic Configuration
-
-```python
-from semantica.triplet_store.config import triplet_store_config
-
-# Get configuration
-batch_size = triplet_store_config.get("batch_size", default=1000)
-enable_caching = triplet_store_config.get("enable_caching", default=True)
-
-# Set configuration
-triplet_store_config.set("batch_size", 2000)
-triplet_store_config.set("enable_caching", False)
-
-# Update with dictionary
-triplet_store_config.update({
- "batch_size": 2000,
- "enable_caching": True,
- "cache_size": 2000
-})
-```
-
-### Configuration File (YAML)
+Configuration is managed via `config.yaml` or environment variables.
```yaml
-# config.yaml
triplet_store:
- default_store: main
- batch_size: 1000
- enable_caching: true
- cache_size: 1000
- enable_optimization: true
- max_retries: 3
- retry_delay: 1.0
- timeout: 30
+ default_backend: blazegraph
blazegraph_endpoint: http://localhost:9999/blazegraph
jena_endpoint: http://localhost:3030/ds
rdf4j_endpoint: http://localhost:8080/rdf4j-server
- virtuoso_endpoint: http://localhost:8890/sparql
-```
-
-## Advanced Examples
-
-### Complete Triplet Store Pipeline
-
-```python
-from semantica.triplet_store import (
- TripletManager,
- QueryEngine,
- BulkLoader,
- register_store,
- add_triples,
- execute_query
-)
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# 1. Register store
-store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
-
-# 2. Generate and add triples
-triplets = [
- Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
- for i in range(1000)
-]
-result = add_triples(triples, store_id="main", batch_size=100)
-
-# 3. Execute queries
-from semantica.triplet_store import BlazegraphStore
-adapter = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
-query_result = execute_query(query, adapter)
-
-print(f"Added {result['total_triples']} triples")
-print(f"Query returned {len(query_result.bindings)} results")
```
-
-### Multi-Store Operations
-
-```python
-from semantica.triplet_store import TripletManager
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-manager = TripletManager()
-
-# Register multiple stores
-manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
-manager.register_store("backup", "jena", "http://localhost:3030/ds")
-
-# Add to primary store
-triplet = Triplet("http://example.org/entity1", "http://example.org/hasName", "John")
-manager.add_triplet(triple, store_id="primary")
-
-# Replicate to backup store
-manager.add_triplet(triple, store_id="backup")
-```
-
-### Query Optimization Workflow
-
-```python
-from semantica.triplet_store import QueryEngine, BlazegraphStore
-
-engine = QueryEngine(enable_optimization=True, enable_caching=True)
-adapter = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Original query
-query = """
-SELECT ?s ?p ?o
-WHERE {
- ?s ?p ?o .
- FILTER(?o > 10)
-}
-"""
-
-# Plan query
-plan = engine.plan_query(query)
-print(f"Estimated cost: {plan.estimated_cost}")
-print(f"Execution steps: {plan.execution_steps}")
-
-# Execute optimized query
-result = engine.execute_query(query, adapter)
-print(f"Execution time: {result.execution_time:.2f}s")
-print(f"Optimized: {result.metadata.get('optimized', False)}")
-```
-
-### Bulk Loading with Validation
-
-```python
-from semantica.triplet_store import BulkLoader, BlazegraphStore
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-loader = BulkLoader(batch_size=1000, max_retries=3)
-adapter = BlazegraphStore(endpoint="http://localhost:9999/blazegraph")
-
-# Generate triples
-triplets = [
- Triplet(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
- for i in range(10000)
-]
-
-# Validate before loading
-validation = loader.validate_before_load(triples)
-if validation['valid']:
- # Load triples
- progress = loader.load_triples(triples, adapter)
- print(f"Loaded {progress.loaded_triples}/{progress.total_triples} triples")
- print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec")
-else:
- print(f"Validation failed: {validation['errors']}")
-```
-
-### Custom Method Registration
-
-```python
-from semantica.triplet_store.registry import method_registry
-from semantica.triplet_store import add_triple
-
-# Register custom add method
-def custom_add_triplet(triple, store_id=None, **options):
- # Custom logic
- print(f"Custom add: {triplet.subject}")
- # Call default implementation
- from semantica.triplet_store.methods import _get_manager
- manager = _get_manager()
- return manager.add_triplet(triple, store_id=store_id, **options)
-
-method_registry.register("add", "custom", custom_add_triple)
-
-# Use custom method
-from semantica.triplet_store.methods import add_triple
-result = add_triplet(triple, store_id="main", method="custom")
-```
-
-## Best Practices
-
-1. **Store Registration**:
- - Register stores before use
- - Use descriptive store IDs
- - Set appropriate default store
- - Configure store-specific options
-
-2. **Triplet Operations**:
- - Validate triplets before adding
- - Use batch operations for multiple triples
- - Set appropriate batch sizes
- - Handle errors gracefully
-
-3. **Query Execution**:
- - Enable caching for repeated queries
- - Use query optimization for complex queries
- - Monitor query performance
- - Use appropriate LIMIT clauses
-
-4. **Bulk Loading**:
- - Validate triplets before loading
- - Use appropriate batch sizes
- - Monitor progress for large loads
- - Handle retries appropriately
-
-5. **Performance**:
- - Use batch operations when possible
- - Enable query caching
- - Optimize queries before execution
- - Monitor query statistics
-
-6. **Error Handling**:
- - Validate triplets before operations
- - Handle adapter errors gracefully
- - Use retry mechanisms for bulk operations
- - Log errors for debugging
-
-7. **Configuration**:
- - Use environment variables for deployment
- - Use config files for development
- - Set appropriate defaults
- - Document configuration options
-
-8. **Testing**:
- - Test with sample data first
- - Validate query results
- - Test error handling
- - Monitor performance
-
diff --git a/semantica/triplet_store/virtuoso_store.py b/semantica/triplet_store/virtuoso_store.py
deleted file mode 100644
index f6d33f01..00000000
--- a/semantica/triplet_store/virtuoso_store.py
+++ /dev/null
@@ -1,381 +0,0 @@
-"""
-Virtuoso Store Module
-
-This module provides Virtuoso RDF store integration for RDF storage and
-SPARQL querying, supporting cluster connections and query optimization.
-
-Key Features:
- - Virtuoso connection and authentication
- - SPARQL query execution
- - Bulk data loading and management
- - Graph and namespace management
- - Cluster connection support
- - Query optimization
-
-Main Classes:
- - VirtuosoStore: Main Virtuoso integration store
-
-Example Usage:
- >>> from semantica.triplet_store import VirtuosoStore
- >>> store = VirtuosoStore(endpoint="http://localhost:8890/sparql", username="dba", password="dba")
- >>> result = store.execute_sparql(sparql_query)
- >>> load_result = store.bulk_load(triplets, graph="http://example.org/graph")
- >>> cluster_status = store.connect_cluster(cluster_config)
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from typing import Any, Dict, List, Optional
-from urllib.parse import urljoin
-
-import requests
-
-from ..semantic_extract.triplet_extractor import Triplet
-from ..utils.exceptions import ProcessingError, ValidationError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-
-class VirtuosoStore:
- """
- Virtuoso RDF store backend.
-
- This class provides integration with OpenLink Virtuoso, supporting
- SPARQL queries, bulk loading, and cluster management.
- """
-
- def __init__(self, endpoint: Optional[str] = None, **config):
- """
- Initialize Virtuoso store.
-
- Args:
- endpoint: SPARQL endpoint URL (e.g., http://localhost:8890/sparql)
- **config: Additional configuration options
- """
- self.logger = get_logger("virtuoso_store")
- self.config = config
- self.progress_tracker = get_progress_tracker()
-
- self.endpoint = endpoint.rstrip("/")
- self.username = config.get("username", "dba")
- self.password = config.get("password", "dba")
- self.timeout = config.get("timeout", 30)
- self.default_graph = config.get("graph", "")
-
- self.connected = False
- self._connect()
-
- def _connect(self) -> None:
- """Connect to Virtuoso instance."""
- try:
- # Test connection with simple query
- sparql_endpoint = self._get_sparql_endpoint()
- response = requests.get(
- sparql_endpoint,
- params={"query": "SELECT * WHERE { ?s ?p ?o } LIMIT 1"},
- timeout=self.timeout,
- auth=(self.username, self.password),
- )
-
- if response.status_code == 200:
- self.connected = True
- self.logger.info(f"Connected to Virtuoso: {self.endpoint}")
- else:
- self.logger.warning(
- f"Virtuoso connection test failed: {response.status_code}"
- )
- except Exception as e:
- self.logger.warning(f"Could not connect to Virtuoso: {e}")
-
- def _get_sparql_endpoint(self) -> str:
- """Get SPARQL endpoint URL."""
- return urljoin(self.endpoint, "/sparql")
-
- def _get_sparql_update_endpoint(self) -> str:
- """Get SPARQL Update endpoint URL."""
- return urljoin(self.endpoint, "/sparql-auth")
-
- def connect_cluster(
- self, cluster_config: Dict[str, Any], **options
- ) -> Dict[str, Any]:
- """
- Connect to Virtuoso cluster.
-
- Args:
- cluster_config: Cluster configuration
- **options: Additional options
-
- Returns:
- Connection status
- """
- # Virtuoso cluster connection
- # This would typically involve multiple endpoints
- endpoints = cluster_config.get("endpoints", [self.endpoint])
-
- connections = []
- for endpoint in endpoints:
- try:
- store = VirtuosoStore(endpoint, **cluster_config)
- if store.connected:
- connections.append(endpoint)
- except Exception as e:
- self.logger.warning(f"Failed to connect to {endpoint}: {e}")
-
- return {
- "success": len(connections) > 0,
- "connected_endpoints": connections,
- "total_endpoints": len(endpoints),
- }
-
- def execute_sparql(self, query: str, **options) -> Dict[str, Any]:
- """
- Execute SPARQL query.
-
- Args:
- query: SPARQL query string
- **options: Additional options
-
- Returns:
- Query results
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="triplet_store",
- submodule="VirtuosoStore",
- message="Executing SPARQL query on Virtuoso",
- )
-
- try:
- if not self.connected:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message="Not connected to Virtuoso"
- )
- raise ProcessingError("Not connected to Virtuoso")
-
- sparql_endpoint = self._get_sparql_endpoint()
-
- self.progress_tracker.update_tracking(
- tracking_id, message="Sending query to Virtuoso endpoint..."
- )
- response = requests.get(
- sparql_endpoint,
- params={"query": query, "default-graph-uri": self.default_graph}
- if self.default_graph
- else {"query": query},
- headers={"Accept": "application/sparql-results+json"},
- timeout=self.timeout,
- auth=(self.username, self.password),
- )
-
- response.raise_for_status()
-
- self.progress_tracker.update_tracking(
- tracking_id, message="Parsing query results..."
- )
- result_data = response.json()
-
- result = {
- "success": True,
- "bindings": result_data.get("results", {}).get("bindings", []),
- "variables": result_data.get("head", {}).get("vars", []),
- "metadata": {"query": query, "endpoint": sparql_endpoint},
- }
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Query executed: {len(result['bindings'])} results",
- )
- return result
- except Exception as e:
- self.logger.error(f"SPARQL query failed: {e}")
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"SPARQL query failed: {e}")
-
- def optimize_queries(self, queries: List[str], **options) -> List[str]:
- """
- Optimize query performance.
-
- Args:
- queries: List of SPARQL queries
- **options: Optimization options
-
- Returns:
- List of optimized queries
- """
- optimized = []
-
- for query in queries:
- # Basic optimization: remove unnecessary whitespace
- opt_query = " ".join(query.split())
-
- # Add LIMIT if not present (for SELECT queries)
- if "SELECT" in query.upper() and "LIMIT" not in query.upper():
- opt_query += " LIMIT 1000"
-
- optimized.append(opt_query)
-
- return optimized
-
- def bulk_load(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
- """
- Load triplets in bulk.
-
- Args:
- triplets: List of triplets
- **options: Additional options:
- - graph: Named graph URI
- - format: RDF format (turtle, ntriples)
-
- Returns:
- Load status
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="triplet_store",
- submodule="VirtuosoStore",
- message=f"Bulk loading {len(triplets)} triplets to Virtuoso",
- )
-
- try:
- if not self.connected:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message="Not connected to Virtuoso"
- )
- raise ProcessingError("Not connected to Virtuoso")
-
- graph = options.get("graph", self.default_graph)
- format = options.get("format", "turtle")
-
- # Convert triplets to RDF
- self.progress_tracker.update_tracking(
- tracking_id, message="Converting triplets to RDF format..."
- )
- rdf_data = self._triplets_to_rdf(triplets, format)
-
- # Use SPARQL INSERT for bulk loading
- update_endpoint = self._get_sparql_update_endpoint()
-
- graph_clause = f"GRAPH <{graph}>" if graph else ""
- insert_data = self._build_insert_data(triplets)
- query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"
-
- self.progress_tracker.update_tracking(
- tracking_id, message="Sending bulk load request..."
- )
- response = requests.post(
- update_endpoint,
- data={"query": query},
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- timeout=self.timeout * 2,
- auth=(self.username, self.password),
- )
-
- response.raise_for_status()
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Bulk loaded {len(triplets)} triplets",
- )
- return {"success": True, "triplets_loaded": len(triplets), "graph": graph}
- except Exception as e:
- self.logger.error(f"Bulk load failed: {e}")
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Bulk load failed: {e}")
-
- def _triplets_to_rdf(self, triplets: List[Triplet], format: str = "turtle") -> str:
- """Convert triplets to RDF format."""
- if format == "turtle":
- lines = []
- for triplet in triplets:
- lines.append(
- f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
- )
- return "\n".join(lines)
- else: # ntriples
- lines = []
- for triplet in triplets:
- lines.append(
- f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> ."
- )
- return "\n".join(lines)
-
- def _build_insert_data(self, triplets: List[Triplet]) -> str:
- """Build SPARQL INSERT DATA clause."""
- lines = []
- for triplet in triplets:
- lines.append(f"<{triplet.subject}> <{triplet.predicate}> <{triplet.object}> .")
- return " ".join(lines)
-
- def add_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
- """Add single triplet."""
- return self.bulk_load([triplet], **options)
-
- def add_triplets(self, triplets: List[Triplet], **options) -> Dict[str, Any]:
- """Add multiple triplets."""
- return self.bulk_load(triplets, **options)
-
- def get_triplets(
- self,
- subject: Optional[str] = None,
- predicate: Optional[str] = None,
- object: Optional[str] = None,
- **options,
- ) -> List[Triplet]:
- """Get triplets matching criteria."""
- # Build SPARQL query
- where_clauses = []
- if subject:
- where_clauses.append(f"?s = <{subject}>")
- if predicate:
- where_clauses.append(f"?p = <{predicate}>")
- if object:
- where_clauses.append(f"?o = <{object}>")
-
- where_clause = " ".join(where_clauses) if where_clauses else ""
- query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"
-
- result = self.execute_sparql(query, **options)
-
- # Convert bindings to triplets
- triplets = []
- for binding in result["bindings"]:
- triplets.append(
- Triplet(
- subject=binding.get("s", {}).get("value", ""),
- predicate=binding.get("p", {}).get("value", ""),
- object=binding.get("o", {}).get("value", ""),
- metadata={"source": "virtuoso"},
- )
- )
-
- return triplets
-
- def delete_triplet(self, triplet: Triplet, **options) -> Dict[str, Any]:
- """Delete triplet."""
- if not self.connected:
- raise ProcessingError("Not connected to Virtuoso")
-
- update_endpoint = self._get_sparql_update_endpoint()
-
- query = f"DELETE DATA {{ <{triplet.subject}> <{triplet.predicate}> <{triplet.object}> }}"
-
- try:
- response = requests.post(
- update_endpoint,
- data={"query": query},
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- timeout=self.timeout,
- auth=(self.username, self.password),
- )
-
- response.raise_for_status()
-
- return {"success": True}
- except Exception as e:
- self.logger.error(f"Delete triplet failed: {e}")
- raise ProcessingError(f"Delete triplet failed: {e}")