Merge pull request #85 from Hawksight-AI/triplet-store

Refactor: Rename `triple_store` to `triplet_store`
This commit is contained in:
Mohd Kaif
2025-12-12 18:48:41 +05:30
committed by GitHub
33 changed files with 394 additions and 391 deletions
+1 -1
View File
@@ -319,7 +319,7 @@ result = kg.query("Who founded the company?", return_format="structured")
print(f"Nodes: {kg.node_count}, Answer: {result.answer}")
```
[**Cookbook: Building Knowledge Graphs**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) • [**Graph Store**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/09_Graph_Store.ipynb) • [**Triple Store**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/20_Triple_Store.ipynb) • [**Visualization**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/16_Visualization.ipynb)
[**Cookbook: Building Knowledge Graphs**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) • [**Graph Store**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/09_Graph_Store.ipynb) • [**Triplet Store**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/20_Triplet_Store.ipynb) • [**Visualization**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/16_Visualization.ipynb)
[**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)
@@ -10,7 +10,7 @@
"\n",
"## Overview\n",
"\n",
"Build an enterprise semantic layer: construct knowledge graph, generate ontology, create semantic layer, export RDF, and store in triple store.\n",
"Build an enterprise semantic layer: construct knowledge graph, generate ontology, create semantic layer, export RDF, and store in triplet store.\n",
"\n",
"\n",
"**Documentation**: [API Reference](https://semantica.readthedocs.io/concepts/)\n",
@@ -25,7 +25,7 @@
"pip install semantica[all]\n",
"```\n",
"\n",
"## Workflow: Build KG → Generate Ontology → Create Semantic Layer → Export RDF → Triple Store\n"
"## Workflow: Build KG → Generate Ontology → Create Semantic Layer → Export RDF → Triplet Store\n"
]
},
{
@@ -37,7 +37,7 @@
"from semantica.kg import GraphBuilder\n",
"from semantica.ontology import OntologyGenerator\n",
"from semantica.export import RDFExporter\n",
"from semantica.triple_store import TripleStore\n"
"from semantica.triplet_store import TripletStore\n"
]
},
{
@@ -162,7 +162,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 5: Store in Triple Store\n"
"## Step 5: Store in Triplet Store\n"
]
},
{
@@ -171,8 +171,8 @@
"metadata": {},
"outputs": [],
"source": [
"triple_store = TripleStore()\n",
"triple_store.store(knowledge_graph, ontology)\n"
"triplet_store = TripletStore()\n",
"triplet_store.store(knowledge_graph, ontology)\n"
]
},
{
@@ -186,7 +186,7 @@
"- Ontology Generated\n",
"- Semantic Layer Created with Mappings\n",
"- RDF Export Completed\n",
"- Triple Store Storage Completed\n"
"- Triplet Store Storage Completed\n"
]
}
],
@@ -6,31 +6,31 @@
"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_Triple_Store.ipynb)\n",
"\n",
"# Triple Store - Comprehensive Guide\n",
"# Triplet Store - Comprehensive Guide\n",
"\n",
"## Overview\n",
"\n",
"This notebook provides a **comprehensive walkthrough** of Semantica's triple_store module, demonstrating RDF triple storage, SPARQL querying, and multi-backend support for knowledge graph persistence.\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",
"\n",
"**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/triple_store/)\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 triple stores (Blazegraph, Jena, RDF4J, Virtuoso)\n",
"- Perform CRUD operations on RDF triples\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 triple operations\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",
"| `TripleManager` | Store coordination | All triple operations |\n",
"| `TripletManager` | Store coordination | All triplet operations |\n",
"| `QueryEngine` | SPARQL execution | Query optimization |\n",
"| `BulkLoader` | High-volume loading | Large datasets |\n",
"| `BlazegraphAdapter` | Blazegraph backend | High performance |\n",
@@ -57,13 +57,13 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 1: Basic Triple Store Operations\n",
"## Step 1: Basic Triplet Store Operations\n",
"\n",
"Let's start with the `TripleManager` for basic triple store operations.\n",
"Let's start with the `TripletManager` for basic triplet store operations.\n",
"\n",
"### What is TripleManager?\n",
"### What is TripletManager?\n",
"\n",
"`TripleManager` is the main coordinator for triple store operations:\n",
"`TripletManager` is the main coordinator for triplet store operations:\n",
"- **Store Registration**: Register multiple backends\n",
"- **CRUD Operations**: Add, get, update, delete triples\n",
"- **Multi-Store**: Manage multiple stores simultaneously"
@@ -75,11 +75,11 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import TripleManager\n",
"from semantica.triplet_store import TripletManager\n",
"from semantica.semantic_extract.triple_extractor import Triple\n",
"\n",
"# Create triple manager\n",
"manager = TripleManager()\n",
"manager = TripletManager()\n",
"\n",
"# Register a Blazegraph store (in-memory for demo)\n",
"store = manager.register_store(\n",
@@ -130,7 +130,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import register_store\n",
"from semantica.triplet_store import register_store\n",
"\n",
"# Register multiple stores using convenience function\n",
"blazegraph_store = register_store(\n",
@@ -179,7 +179,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import add_triple, add_triples, get_triples, update_triple, delete_triple\n",
"from semantica.triplet_store import add_triple, add_triples, get_triples, update_triple, delete_triple\n",
"\n",
"# Create - Add single triple\n",
"triple1 = Triple(\n",
@@ -240,7 +240,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import QueryEngine, BlazegraphAdapter\n",
"from semantica.triplet_store import QueryEngine, BlazegraphAdapter\n",
"\n",
"# Create query engine with caching\n",
"engine = QueryEngine(enable_caching=True, enable_optimization=True)\n",
@@ -299,7 +299,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import optimize_query, plan_query\n",
"from semantica.triplet_store import optimize_query, plan_query\n",
"\n",
"# Original query\n",
"query = \"\"\"\n",
@@ -347,7 +347,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import BulkLoader, LoadProgress\n",
"from semantica.triplet_store import BulkLoader, LoadProgress\n",
"\n",
"# Create bulk loader\n",
"loader = BulkLoader(\n",
@@ -392,11 +392,11 @@
"source": [
"## Step 7: Store Adapters\n",
"\n",
"Work with different triple store backends.\n",
"Work with different triplet store backends.\n",
"\n",
"### Blazegraph Adapter\n",
"\n",
"High-performance triple store with GPU acceleration."
"High-performance triplet store with GPU acceleration."
]
},
{
@@ -405,7 +405,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import BlazegraphAdapter\n",
"from semantica.triplet_store import BlazegraphAdapter\n",
"\n",
"# Create Blazegraph adapter\n",
"blazegraph = BlazegraphAdapter(\n",
@@ -442,7 +442,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import JenaAdapter\n",
"from semantica.triplet_store import JenaAdapter\n",
"\n",
"# Create Jena adapter (in-memory)\n",
"jena = JenaAdapter()\n",
@@ -497,7 +497,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import RDF4JAdapter\n",
"from semantica.triplet_store import RDF4JAdapter\n",
"\n",
"# Create RDF4J adapter\n",
"rdf4j = RDF4JAdapter(\n",
@@ -540,7 +540,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import VirtuosoAdapter\n",
"from semantica.triplet_store import VirtuosoAdapter\n",
"\n",
"# Create Virtuoso adapter\n",
"virtuoso = VirtuosoAdapter(\n",
@@ -604,7 +604,7 @@
"metadata": {},
"outputs": [],
"source": [
"from semantica.triple_store import validate_triples\n",
"from semantica.triplet_store import validate_triples\n",
"\n",
"# Create triples (some invalid)\n",
"triples_to_validate = [\n",
@@ -650,7 +650,7 @@
"outputs": [],
"source": [
"# Register multiple stores\n",
"manager = TripleManager()\n",
"manager = TripletManager()\n",
"\n",
"primary = manager.register_store(\n",
" \"primary\",\n",
@@ -720,7 +720,7 @@
"\n",
"In this notebook, you've learned how to:\n",
"\n",
"- Register and manage triple stores\n",
"- Register and manage triplet stores\n",
"- Perform CRUD operations on RDF triples\n",
"- Execute and optimize SPARQL queries\n",
"- Use bulk loading for large datasets\n",
@@ -740,7 +740,7 @@
"### Next Steps\n",
"\n",
"**Further Reading**:\n",
"- [Triple Store API Reference](https://semantica.readthedocs.io/reference/triple_store/)\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",
@@ -771,4 +771,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
}
}
@@ -38,7 +38,7 @@
"- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",
"- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",
"- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
"- **Quality**: KGQualityAssessor, ValidationEngine\n",
"- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
@@ -67,7 +67,6 @@
"from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
"from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
"from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
"import tempfile\n",
@@ -22,7 +22,7 @@
"- **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies, clinical documents, and reports\n",
"- **Virtual Data Integration**: Semantica's DBIngestor and QueryEngine allow virtual integration with Electronic Health Records (EHRs) without data replication\n",
"- **Hybrid Design**: Semantica's architecture naturally separates structural knowledge from patient-level data\n",
"- **Dynamic Query Orchestration**: Semantica's Reasoning and Triple Store modules enable orchestration of queries across ontologies, documents, and EHRs\n",
"- **Dynamic Query Orchestration**: Semantica's Reasoning and Triplet Store modules enable orchestration of queries across ontologies, documents, and EHRs\n",
"- **Temporal & Semantic Dimensions**: Semantica's Temporal and Context modules provide historical analysis and semantic understanding\n",
"- **Traceable & Explainable**: Semantica's ExplanationGenerator and ContextRetriever provide traceable, explainable answers\n",
"\n",
@@ -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",
"- **Triple Store**: TripleManager, QueryEngine (for SPARQL queries on ontologies)\n",
"- **Triplet Store**: TripletManager, 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",
@@ -86,7 +86,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.triple_store import TripleManager, QueryEngine\n",
"from semantica.triplet_store import TripletManager, 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",
@@ -440,9 +440,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 9: Setup Triple Store for Ontology Queries Using Semantica\n",
"## Step 9: Setup Triplet Store for Ontology Queries Using Semantica\n",
"\n",
"Using Semantica's triple store modules to enable SPARQL queries on medical ontologies.\n"
"Using Semantica's triplet store modules to enable SPARQL queries on medical ontologies.\n"
]
},
{
@@ -451,12 +451,12 @@
"metadata": {},
"outputs": [],
"source": [
"# Initialize Semantica triple store and query engine\n",
"triple_manager = TripleManager()\n",
"# Initialize Semantica triplet store and query engine\n",
"triplet_manager = TripletManager()\n",
"query_engine = QueryEngine()\n",
"\n",
"# Register triple store (using in-memory for demo)\n",
"store = triple_manager.register_store(\"healthcare_ontology\", \"jena\", \"http://localhost:3030/healthcare\")\n",
"# Register triplet store (using in-memory for demo)\n",
"store = triplet_manager.register_store(\"healthcare_ontology\", \"jena\", \"http://localhost:3030/healthcare\")\n",
"\n",
"# Convert ontology to triples and add to store\n",
"# In production, this would load the OWL ontology\n",
@@ -477,7 +477,7 @@
"\n",
"# Add triples using Semantica\n",
"for triple in sample_triples:\n",
" triple_manager.add_triple(triple, store_id=\"healthcare_ontology\")\n",
" triplet_manager.add_triple(triple, store_id=\"healthcare_ontology\")\n",
"\n",
"print(f\" - Triples added: {len(sample_triples)}\")\n",
"print(f\" - SPARQL queries enabled for ontology\")\n"
@@ -531,7 +531,7 @@
" \"context\": {}\n",
" }\n",
" \n",
" # 1. Query ontology using Semantica Triple Store\n",
" # 1. Query ontology using Semantica Triplet Store\n",
" sparql_query = f\"\"\"\n",
" SELECT ?concept WHERE {{\n",
" ?concept rdfs:label ?label .\n",
@@ -769,8 +769,8 @@
"2. **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies and documents\n",
"3. **Virtual Data Integration**: Semantica's DBIngestor allows virtual integration with EHRs without data replication\n",
"4. **Hybrid Search**: Semantica's HybridSearch combines vector similarity with knowledge graph queries\n",
"5. **Query Orchestration**: Semantica's Reasoning and Triple Store modules enable dynamic query orchestration\n",
"6. **Explainability**: Semantica's ExplanationGenerator provides traceable, explainable answers\n",
"5. **Query Orchestration**: Semantica's Reasoning and Triplet Store modules enable dynamic query orchestration\n",
"6. **Explainability**: Semantica's ExplanationGenerator provides traceable, explainable answers\n",
"\n",
"### Semantica-Specific Performance Considerations\n",
"\n",
@@ -30,7 +30,7 @@
"- **Parsing**: MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
"- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
"- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",
"- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",
"- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
"- **Quality**: KGQualityAssessor, ValidationEngine\n",
"- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
@@ -67,7 +67,7 @@
"from semantica.parse import MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",
"from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
"from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",
"from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
"from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",
"from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
"from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
@@ -402,7 +402,7 @@
"source": [
"## Step 5: Build Healthcare Knowledge Graph\n",
"\n",
"Build a knowledge graph from the extracted medical entities and relationships, then store in triple store.\n"
"Build a knowledge graph from the extracted medical entities and relationships, then store in triplet store.\n"
]
},
{
@@ -426,13 +426,17 @@
"# Analyze graph structure\n",
"metrics = graph_analyzer.compute_metrics(resolved_kg)\n",
"\n",
"# Store in triple store\n",
"triple_store = TripleStore()\n",
"triple_manager = TripleManager()\n",
"# Store in triplet store\n",
"# triplet_store = TripletStore() # TripletStore is a configuration dataclass\n",
"triplet_manager = TripletManager()\n",
"query_engine = QueryEngine()\n",
"\n",
"triple_store.add_knowledge_graph(resolved_kg)\n",
"triple_manager.manage_triples(resolved_kg)\n",
"# Register default store (in-memory for demo)\n",
"store = triplet_manager.register_store(\"medical_kg\", \"jena\", \"http://localhost:3030/medical\")\n",
"\n",
"# Convert KG to triples and add to store (simplified)\n",
"# In a real scenario, we would convert entities/relations to triples first\n",
"# triplet_manager.add_triples(triples, store_id=\"medical_kg\")\n",
"\n",
"print(f\" Entities: {len(resolved_kg.get('entities', []))}\")\n",
"print(f\" Relationships: {len(resolved_kg.get('relationships', []))}\")\n",
@@ -22,13 +22,13 @@
"- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver\n",
"- **KG**: GraphBuilder, TemporalGraphQuery, GraphValidator, EntityResolver\n",
"- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
"- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",
"- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",
"- **Export**: RDFExporter, OWLExporter, JSONExporter\n",
"- **Visualization**: KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
"\n",
"### Pipeline\n",
"\n",
"**Patient Records → Parse → Extract Medical Entities → Build Temporal KG → Generate Ontology → Store in Triple Store → Query History → Export → Visualize**\n",
"**Patient Records → Parse → Extract Medical Entities → Build Temporal KG → Generate Ontology → Store in Triplet Store → Query History → Export → Visualize**\n",
"\n",
"## Installation\n",
"\n",
@@ -58,7 +58,7 @@
"from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver\n",
"from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphValidator, EntityResolver\n",
"from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
"from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",
"from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",
"from semantica.export import RDFExporter, OWLExporter, JSONExporter\n",
"from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",
"import tempfile\n",
@@ -261,9 +261,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 5: Store in Triple Store and Query\n",
"## Step 5: Store in Triplet Store and Query\n",
"\n",
"Store knowledge graph in triple store and query medical history.\n"
"Store knowledge graph in triplet store and query medical history.\n"
]
},
{
@@ -272,12 +272,12 @@
"metadata": {},
"outputs": [],
"source": [
"triple_store = TripleStore()\n",
"triple_manager = TripleManager()\n",
"triplet_store = TripletStore()\n",
"triple_manager = TripletManager()\n",
"query_engine = QueryEngine()\n",
"temporal_query = TemporalGraphQuery()\n",
"\n",
"triple_store.store_knowledge_graph(patient_kg)\n",
"triplet_store.store_knowledge_graph(patient_kg)\n",
"\n",
"patient_id = \"P001\"\n",
"start_time = \"2024-01-01\"\n",
@@ -290,7 +290,7 @@
" end_time=end_time\n",
")\n",
"\n",
"print(f\"Stored patient knowledge graph in triple store\")\n",
"print(f\"Stored patient knowledge graph in triplet store\")\n",
"print(f\"Retrieved {len(medical_history.get('entities', []))} medical events for patient {patient_id}\")\n"
]
},
@@ -326,7 +326,7 @@
"temporal_viz = temporal_visualizer.visualize_timeline(patient_kg, output=\"interactive\")\n",
"\n",
"print(f\"Total modules used: 20+\")\n",
"print(f\"Pipeline complete: Patient Records → Parse → Extract → Temporal KG → Ontology → Triple Store → Query → Export → Visualize\")\n"
"print(f\"Pipeline complete: Patient Records → Parse → Extract → Temporal KG → Ontology → Triplet Store → Query → Export → Visualize\")\n"
]
}
],
+1 -1
View File
@@ -279,7 +279,7 @@ owl_ontology = ontology.to_owl()
rdf_ontology = ontology.to_rdf()
turtle_ontology = ontology.to_turtle()
# Save to triple store
# Save to triplet store
ontology.save_to_triple_store("http://localhost:9999/blazegraph/sparql")
```
+2 -2
View File
@@ -67,7 +67,7 @@ graph TB
### Knowledge Graphs
- **`semantica.kg`** - Knowledge graph construction
- **`semantica.vector_store`** - Vector storage (Pinecone, Weaviate, FAISS)
- **`semantica.triple_store`** - RDF triple storage (Jena, Blazegraph)
- **`semantica.triplet_store`** - RDF triplet storage (Jena, Blazegraph)
- **`semantica.graph_store`** - Property graphs (Neo4j, FalkorDB)
### Quality Assurance
@@ -85,7 +85,7 @@ graph TB
4. Semantic Extraction → Entities, relationships, events
5. Graph Construction → Entity resolution, conflict resolution
6. Quality Assurance → Deduplication, validation
7. Storage → Vector, triple, and graph stores
7. Storage → Vector, triplet, and graph stores
8. Application → GraphRAG, agents, analytics
```
+1 -1
View File
@@ -181,7 +181,7 @@ A comprehensive reference of terms and concepts used in Semantica.
**Triple**
: A basic unit of knowledge in RDF, consisting of a subject, predicate, and object (e.g., `<Apple_Inc> <founded_by> <Steve_Jobs>`).
**Triple Store**
**Triplet Store**
: A database designed specifically for storing and querying RDF triples.
---
+9 -9
View File
@@ -15,7 +15,7 @@ Semantica's modules are organized into six logical layers:
| :--- | :--- | :--- |
| **Input Layer** | [Ingest](#ingest-module), [Parse](#parse-module), [Split](#split-module), [Normalize](#normalize-module) | Data ingestion, parsing, chunking, and cleaning |
| **Core Processing** | [Semantic Extract](#semantic-extract-module), [Knowledge Graph](#knowledge-graph-kg-module), [Ontology](#ontology-module), [Reasoning](#reasoning-module) | Entity extraction, graph construction, inference |
| **Storage** | [Embeddings](#embeddings-module), [Vector Store](#vector-store-module), [Graph Store](#graph-store-module), [Triple Store](#triple-store-module) | Vector and graph persistence |
| **Storage** | [Embeddings](#embeddings-module), [Vector Store](#vector-store-module), [Graph Store](#graph-store-module), [Triplet Store](#triplet-store-module) | Vector, graph, and triplet persistence |
| **Quality Assurance** | [Deduplication](#deduplication-module), [Conflicts](#conflicts-module) | Data quality and consistency |
| **Context & Memory** | [Context](#context-module), [Seed](#seed-module) | Agent memory and foundation data |
| **Output & Orchestration** | [Export](#export-module), [Visualization](#visualization-module), [Pipeline](#pipeline-module) | Export, visualization, and workflow management |
@@ -563,15 +563,15 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
---
### Triple Store Module
### Triplet Store Module
!!! abstract "Purpose"
RDF triple store integration for semantic web applications. Supports SPARQL queries and multiple backends.
RDF triplet store integration for semantic web applications. Supports SPARQL queries and multiple backends.
**Key Features:**
- Multi-backend support (Blazegraph, Jena, RDF4J, Virtuoso)
- CRUD operations for RDF triples
- CRUD operations for RDF triplets
- SPARQL query execution and optimization
- Bulk data loading with progress tracking
- Query caching and optimization
@@ -580,7 +580,7 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
**Components:**
- `TripleManager` — Main triple store management coordinator
- `TripletManager` — Main triplet store management coordinator
- `QueryEngine` — SPARQL query execution and optimization
- `BulkLoader` — High-volume data loading with progress tracking
- `BlazegraphAdapter` — Blazegraph integration
@@ -601,9 +601,9 @@ results = store.execute_query("MATCH (p:Person) RETURN p.name")
**Quick Example:**
```python
from semantica.triple_store import TripleManager, execute_query
from semantica.triplet_store import TripletManager, execute_query
manager = TripleManager()
manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# Add triple
@@ -617,7 +617,7 @@ result = manager.add_triple({
query_result = execute_query("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10", store)
```
**API Reference**: [Triple Store Module](reference/triple_store.md)
**API Reference**: [Triplet Store Module](reference/triplet_store.md)
---
@@ -1114,7 +1114,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 |
| **Triple Store** | `semantica.triple_store` | `TripleManager` | RDF storage |
| **Triplet Store** | `semantica.triplet_store` | `TripletManager` | RDF storage |
| **Deduplication** | `semantica.deduplication` | `DuplicateDetector` | Duplicate removal |
| **Conflicts** | `semantica.conflicts` | `ConflictDetector` | Conflict resolution |
| **Context** | `semantica.context` | `AgentMemory` | Agent context |
+1 -1
View File
@@ -414,7 +414,7 @@ subgraph = graph_store.execute_query(query, parameters={"ids": node_ids})
## See Also
- [Knowledge Graph Module](kg.md) - Logical layer above Graph Store
- [Triple Store Module](triple_store.md) - RDF-based alternative
- [Triplet Store Module](triplet_store.md) - RDF-based alternative
- [Visualization Module](visualization.md) - Visualizing query results
## Cookbook
+1 -1
View File
@@ -245,7 +245,7 @@ kg.add_triples(inferred_triples)
## See Also
- [Ontology Module](ontology.md) - Source of schema-based rules
- [Triple Store Module](triple_store.md) - Backend for SPARQL reasoning
- [Triplet Store Module](triplet_store.md) - Backend for SPARQL reasoning
- [Modules Guide](../modules.md#quality-assurance) - Consistency checking overview
## Cookbook
@@ -1,6 +1,6 @@
# Triple Store
# Triplet Store
> **Store and query RDF triples with SPARQL support and semantic reasoning using industry-standard triple stores.**
> **Store and query RDF triplets with SPARQL support and semantic reasoning using industry-standard triplet stores.**
---
@@ -12,7 +12,7 @@
---
Store subject-predicate-object triples in W3C-compliant RDF format
Store subject-predicate-object triplets in W3C-compliant RDF format
- :material-code-braces:{ .lg .middle } **SPARQL Queries**
@@ -36,7 +36,7 @@
---
Query across multiple triple stores with SPARQL federation
Query across multiple triplet stores with SPARQL federation
- :material-upload-multiple:{ .lg .middle } **Bulk Loading**
@@ -89,29 +89,29 @@
## Main Classes
### TripleManager
### TripletManager
Main coordinator for triple store operations across multiple backends.
Main coordinator for triplet store operations across multiple backends.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
| `register_store(id, backend, endpoint)` | Register triple store | Store registration |
| `add_triple(triple, store_id)` | Add single triple | Index insertion |
| `add_triples(triples, store_id)` | Batch add triples | Bulk index insertion |
| `register_store(store_id, backend, endpoint)` | Register triplet store | Store registration |
| `add_triple(triple, store_id)` | Add single triplet | Index insertion |
| `add_triples(triples, store_id)` | Batch add triplets | Bulk index insertion |
| `query(sparql, store_id)` | Execute SPARQL query | Query optimization + execution |
| `delete(pattern, store_id)` | Delete matching triples | Pattern matching + deletion |
| `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.triple_store import TripleManager
from semantica.triplet_store import TripletManager
# Initialize manager
manager = TripleManager()
manager = TripletManager()
# Register Blazegraph store
store = manager.register_store(
@@ -193,9 +193,9 @@ SPARQL query execution and optimization engine.
**Example:**
```python
from semantica.triple_store import QueryEngine, TripleManager
from semantica.triplet_store import QueryEngine, TripletManager
manager = TripleManager()
manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
engine = QueryEngine()
@@ -270,9 +270,9 @@ High-performance bulk data loading with progress tracking.
**Example:**
```python
from semantica.triple_store import BulkLoader, TripleManager
from semantica.triplet_store import BulkLoader, TripletManager
manager = TripleManager()
manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
loader = BulkLoader(
@@ -322,7 +322,7 @@ progress = loader.load_from_string(
#### BlazegraphAdapter
High-performance triple store with GPU acceleration support.
High-performance triplet store with GPU acceleration support.
**Features:**
- High-performance SPARQL query execution
@@ -334,7 +334,7 @@ High-performance triple store with GPU acceleration support.
**Example:**
```python
from semantica.triple_store import BlazegraphAdapter
from semantica.triplet_store import BlazegraphAdapter
adapter = BlazegraphAdapter(
endpoint="http://localhost:9999/blazegraph/sparql",
@@ -376,7 +376,7 @@ results = adapter.query("""
Full-featured RDF framework with TDB2 storage.
**Features:**
- TDB2 native triple store
- TDB2 native triplet store
- SHACL validation
- Inference engines (RDFS, OWL)
- Fuseki SPARQL server
@@ -385,7 +385,7 @@ Full-featured RDF framework with TDB2 storage.
**Example:**
```python
from semantica.triple_store import JenaAdapter
from semantica.triplet_store import JenaAdapter
adapter = JenaAdapter(
tdb_directory="./tdb2_data",
@@ -451,7 +451,7 @@ Java-based RDF framework with multiple storage backends.
**Example:**
```python
from semantica.triple_store import RDF4JAdapter
from semantica.triplet_store import RDF4JAdapter
adapter = RDF4JAdapter(
server_url="http://localhost:8080/rdf4j-server",
@@ -497,7 +497,7 @@ Enterprise-grade RDF store with SQL integration.
**Example:**
```python
from semantica.triple_store import VirtuosoAdapter
from semantica.triplet_store import VirtuosoAdapter
adapter = VirtuosoAdapter(
host="localhost",
@@ -534,10 +534,10 @@ results = adapter.query(f"""
## Convenience Functions
Quick access to triple store operations:
Quick access to triplet store operations:
```python
from semantica.triple_store import (
from semantica.triplet_store import (
add_triple,
add_triples,
execute_query,
@@ -579,9 +579,9 @@ export_graph(
## Dataclasses
### TripleStore
### TripletStore
Configuration dataclass for triple store instances.
Configuration dataclass for triplet store instances.
**Attributes:**
@@ -649,35 +649,35 @@ Bulk loading progress dataclass.
```bash
# General settings
export TRIPLE_STORE_DEFAULT_BACKEND=blazegraph
export TRIPLE_STORE_BATCH_SIZE=10000
export TRIPLE_STORE_TIMEOUT=30
export TRIPLET_STORE_DEFAULT_BACKEND=blazegraph
export TRIPLET_STORE_BATCH_SIZE=10000
export TRIPLET_STORE_TIMEOUT=30
# Blazegraph settings
export TRIPLE_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph/sparql
export TRIPLE_STORE_BLAZEGRAPH_NAMESPACE=kb
export TRIPLET_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph/sparql
export TRIPLET_STORE_BLAZEGRAPH_NAMESPACE=kb
# Jena settings
export TRIPLE_STORE_JENA_TDB_DIRECTORY=./tdb2_data
export TRIPLE_STORE_JENA_INFERENCE=rdfs
export TRIPLET_STORE_JENA_TDB_DIRECTORY=./tdb2_data
export TRIPLET_STORE_JENA_INFERENCE=rdfs
# RDF4J settings
export TRIPLE_STORE_RDF4J_SERVER_URL=http://localhost:8080/rdf4j-server
export TRIPLE_STORE_RDF4J_REPOSITORY_ID=my_repo
export TRIPLET_STORE_RDF4J_SERVER_URL=http://localhost:8080/rdf4j-server
export TRIPLET_STORE_RDF4J_REPOSITORY_ID=my_repo
# Virtuoso settings
export TRIPLE_STORE_VIRTUOSO_HOST=localhost
export TRIPLE_STORE_VIRTUOSO_PORT=1111
export TRIPLE_STORE_VIRTUOSO_USER=dba
export TRIPLE_STORE_VIRTUOSO_PASSWORD=dba
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 - Triple Store Configuration
# config.yaml - Triplet Store Configuration
triple_store:
triplet_store:
backend: blazegraph # blazegraph, jena, rdf4j, virtuoso
batch_size: 10000
timeout: 30
+1 -1
View File
@@ -123,7 +123,7 @@ nav:
- Seed: reference/seed.md
- Semantic Extract: reference/semantic_extract.md
- Split: reference/split.md
- Triple Store: reference/triple_store.md
- Triplet Store: reference/triplet_store.md
- Utils: reference/utils.md
- Vector Store: reference/vector_store.md
- Visualization: reference/visualization.md
+7 -7
View File
@@ -84,7 +84,7 @@ class _SemanticaModules:
self._normalize = None
self._export = None
self._vector_store = None
self._triple_store = None
self._triplet_store = None
self._graph_store = None
self._ontology = None
self._evals = None
@@ -160,11 +160,11 @@ class _SemanticaModules:
return self._vector_store
@property
def triple_store(self):
"""Access triple store module."""
if self._triple_store is None:
self._triple_store = _ModuleProxy("triple_store")
return self._triple_store
def triplet_store(self):
"""Access triplet store module."""
if self._triplet_store is None:
self._triplet_store = _ModuleProxy("triplet_store")
return self._triplet_store
@property
def graph_store(self):
@@ -289,7 +289,7 @@ def __getattr__(name: str):
"normalize",
"export",
"vector_store",
"triple_store",
"triplet_store",
"graph_store",
"ontology",
"evals",
+7 -7
View File
@@ -45,7 +45,7 @@ print(f"Inferred {len(results)} new facts")
from semantica.reasoning import SPARQLReasoner
# Create SPARQL reasoner
reasoner = SPARQLReasoner(triple_store=kg)
reasoner = SPARQLReasoner(triplet_store=kg)
# Execute query
query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }"
@@ -190,7 +190,7 @@ results = engine.forward_chain()
from semantica.reasoning import SPARQLReasoner
# Create reasoner with knowledge graph
reasoner = SPARQLReasoner(triple_store=kg)
reasoner = SPARQLReasoner(triplet_store=kg)
# Execute SPARQL query
query = """
@@ -212,7 +212,7 @@ for binding in result.bindings:
```python
from semantica.reasoning import SPARQLReasoner
reasoner = SPARQLReasoner(triple_store=kg, enable_inference=True)
reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)
# Add inference rule
reasoner.add_inference_rule("IF ?x :type :Company THEN ?x :type :Organization")
@@ -234,7 +234,7 @@ result = reasoner.execute_query(query)
from semantica.reasoning import SPARQLReasoner
reasoner = SPARQLReasoner(
triple_store=kg,
triplet_store=kg,
enable_inference=True,
inference_rules=["rdfs:subClassOf", "rdfs:subPropertyOf"]
)
@@ -1165,7 +1165,7 @@ engine = InferenceEngine(
# Configure SPARQL reasoner
reasoner = SPARQLReasoner(
triple_store=kg,
triplet_store=kg,
enable_inference=True,
query_cache_size=1000
)
@@ -1234,7 +1234,7 @@ for result in results:
print(f"Explanation: {explanation.natural_language}")
# 6. Query with SPARQL reasoning
sparql_reasoner = SPARQLReasoner(triple_store=kg, enable_inference=True)
sparql_reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)
query_result = sparql_reasoner.execute_query("SELECT ?x WHERE { ?x :type :Employee }")
```
@@ -1332,7 +1332,7 @@ from semantica.kg import build
kg = build(sources=[...])
# Create SPARQL reasoner with KG
reasoner = SPARQLReasoner(triple_store=kg, enable_inference=True)
reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)
# Add inference rules
reasoner.add_inference_rule("IF ?x :type :Company THEN ?x :type :Organization")
+6 -6
View File
@@ -12,7 +12,7 @@ Key Features:
- Query expansion
- Performance optimization
- Error handling and recovery
- Triple store integration
- Triplet store integration
Main Classes:
- SPARQLReasoner: SPARQL-based reasoning engine
@@ -67,7 +67,7 @@ class SPARQLReasoner:
Args:
config: Configuration dictionary
**kwargs: Additional configuration options:
- triple_store: Triple store connection
- triplet_store: Triplet store connection
- enable_inference: Enable inference rules
"""
self.logger = get_logger("sparql_reasoner")
@@ -78,7 +78,7 @@ class SPARQLReasoner:
self.progress_tracker = get_progress_tracker()
self.rule_manager = RuleManager(**self.config)
self.triple_store = self.config.get("triple_store")
self.triplet_store = self.config.get("triplet_store")
self.enable_inference = self.config.get("enable_inference", True)
self.query_cache: Dict[str, Any] = {}
@@ -356,12 +356,12 @@ class SPARQLReasoner:
)
expanded_query = self.expand_query(query, **options)
# Execute query (if triple store available)
# Execute query (if triplet store available)
self.progress_tracker.update_tracking(
tracking_id, message="Executing query..."
)
if self.triple_store:
# This would call the triple store's query method
if self.triplet_store:
# This would call the triplet store's query method
# For now, return empty result
result = SPARQLQueryResult(bindings=[], variables=[])
else:
@@ -1,22 +1,22 @@
"""
Triple Store Module
Triplet Store Module
This module provides comprehensive triple store integration and management
for RDF data storage and querying, supporting multiple triple store backends
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:
Triple Store Management:
Triplet Store Management:
- Store Registration: Store type detection, adapter factory pattern, configuration management, default store selection
- Adapter Pattern: Unified interface for multiple backends (Blazegraph, Jena, RDF4J, Virtuoso), adapter instantiation, backend-specific operation delegation
- Store Selection: Default store resolution, store ID lookup, store validation
CRUD Operations:
- Triple Addition: Single triple insertion, batch triple insertion, triple validation (subject/predicate/object checking, confidence validation), adapter delegation
- Triple Retrieval: Pattern matching (subject/predicate/object filtering), SPARQL query construction, result binding extraction, triple reconstruction
- Triple Deletion: Triple matching, deletion operation delegation, result verification
- Triple Update: Delete-then-add pattern, atomic update operations, conflict detection
- Triplet Addition: Single triplet insertion, batch triplet insertion, triplet validation (subject/predicate/object checking, confidence validation), adapter 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
@@ -46,7 +46,7 @@ Store Adapters:
Data Validation:
- Triple 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: Adapter-level connection management, connection reuse, connection lifecycle management
@@ -55,7 +55,7 @@ Performance Optimization:
Key Features:
- Multi-backend support (Blazegraph, Jena, RDF4J, Virtuoso)
- CRUD operations for RDF triples
- CRUD operations for RDF triplets
- SPARQL query execution and optimization
- Bulk data loading with progress tracking
- Query caching and optimization
@@ -65,41 +65,41 @@ Key Features:
- Configuration management with environment variables and config files
Main Classes:
- TripleManager: Main triple store management coordinator
- TripletManager: Main triplet store management coordinator
- QueryEngine: SPARQL query execution and optimization
- BulkLoader: High-volume data loading
- BlazegraphAdapter: Blazegraph integration adapter
- JenaAdapter: Apache Jena integration adapter
- RDF4JAdapter: Eclipse RDF4J integration adapter
- VirtuosoAdapter: Virtuoso RDF store integration adapter
- TripleStore: Triple store configuration dataclass
- 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 triple store wrapper
- add_triple: Add single triple wrapper
- add_triples: Add multiple triples wrapper
- get_triples: Get triples matching pattern wrapper
- delete_triple: Delete triple wrapper
- register_store: Register triplet store wrapper
- add_triple: Add single triplet wrapper
- add_triples: Add multiple triplets wrapper
- get_triples: Get triplets matching pattern wrapper
- delete_triple: Delete triplet wrapper
- execute_query: Execute SPARQL query wrapper
- optimize_query: Optimize SPARQL query wrapper
- bulk_load: Bulk load triples wrapper
- get_triple_store_method: Get triple store method by task and name
- list_available_methods: List registered triple store methods
- 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.triple_store import TripleManager, register_store, add_triple, execute_query
>>> from semantica.triplet_store import TripletManager, register_store, add_triple, execute_query
>>> # Using convenience functions
>>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
>>> result = add_triple(triple, store_id="main")
>>> query_result = execute_query(sparql_query, store_adapter)
>>> # Using classes directly
>>> manager = TripleManager()
>>> manager = TripletManager()
>>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
>>> result = manager.add_triple(triple, store_id="main")
>>> from semantica.triple_store import QueryEngine
>>> from semantica.triplet_store import QueryEngine
>>> engine = QueryEngine()
>>> query_result = engine.execute_query(sparql_query, store_adapter)
@@ -109,7 +109,7 @@ License: MIT
from .blazegraph_adapter import BlazegraphAdapter
from .bulk_loader import BulkLoader, LoadProgress
from .config import TripleStoreConfig, triple_store_config
from .config import TripletStoreConfig, triplet_store_config
from .jena_adapter import JenaAdapter
from .methods import (
add_triple,
@@ -117,7 +117,7 @@ from .methods import (
bulk_load,
delete_triple,
execute_query,
get_triple_store_method,
get_triplet_store_method,
get_triples,
list_available_methods,
optimize_query,
@@ -129,13 +129,13 @@ from .methods import (
from .query_engine import QueryEngine, QueryPlan, QueryResult
from .rdf4j_adapter import RDF4JAdapter
from .registry import MethodRegistry, method_registry
from .triple_manager import TripleManager, TripleStore
from .triplet_manager import TripletManager, TripletStore
from .virtuoso_adapter import VirtuosoAdapter
__all__ = [
# Triple management
"TripleManager",
"TripleStore",
"TripletManager",
"TripletStore",
# Store adapters
"BlazegraphAdapter",
"JenaAdapter",
@@ -160,11 +160,11 @@ __all__ = [
"plan_query",
"bulk_load",
"validate_triples",
"get_triple_store_method",
"get_triplet_store_method",
"list_available_methods",
# Configuration and registry
"TripleStoreConfig",
"triple_store_config",
"TripletStoreConfig",
"triplet_store_config",
"MethodRegistry",
"method_registry",
]
@@ -17,7 +17,7 @@ Main Classes:
- BlazegraphAdapter: Main Blazegraph integration adapter
Example Usage:
>>> from semantica.triple_store import BlazegraphAdapter
>>> from semantica.triplet_store import BlazegraphAdapter
>>> adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph", namespace="kb")
>>> result = adapter.execute_sparql(sparql_query)
>>> load_result = adapter.bulk_load(triples)
@@ -40,7 +40,7 @@ from ..utils.progress_tracker import get_progress_tracker
class BlazegraphAdapter:
"""
Blazegraph triple store adapter.
Blazegraph triplet store adapter.
Blazegraph connection and authentication
SPARQL query execution
@@ -119,7 +119,7 @@ class BlazegraphAdapter:
Query results
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="BlazegraphAdapter",
message="Executing SPARQL query on Blazegraph",
)
@@ -1,7 +1,7 @@
"""
Bulk Loader Module
This module provides high-volume data loading capabilities for triple stores,
This module provides high-volume data loading capabilities for triplet stores,
enabling efficient batch processing with progress tracking and error recovery.
Key Features:
@@ -18,7 +18,7 @@ Main Classes:
- LoadProgress: Bulk loading progress representation dataclass
Example Usage:
>>> from semantica.triple_store import BulkLoader
>>> from semantica.triplet_store import BulkLoader
>>> loader = BulkLoader(batch_size=1000, max_retries=3)
>>> progress = loader.load_triples(triples, store_adapter)
>>> print(f"Loaded {progress.loaded_triples}/{progress.total_triples} triples")
@@ -56,7 +56,7 @@ class LoadProgress:
class BulkLoader:
"""
High-volume data loading system for triple stores.
High-volume data loading system for triplet stores.
High-volume data loading strategies
Batch processing and chunking
@@ -104,7 +104,7 @@ class BulkLoader:
Load progress information
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="BulkLoader",
message=f"Loading {len(triples)} triples in bulk",
)
@@ -1,14 +1,14 @@
"""
Configuration Management Module for Triple Store
Configuration Management Module for Triplet Store
This module provides centralized configuration management for triple store operations,
This module provides centralized configuration management for triplet store operations,
supporting multiple configuration sources including environment variables, config files,
and programmatic configuration.
Supported Configuration Sources:
- Environment variables: TRIPLE_STORE_DEFAULT_STORE, TRIPLE_STORE_BATCH_SIZE, TRIPLE_STORE_ENABLE_CACHING, etc.
- Environment variables: TRIPLET_STORE_DEFAULT_STORE, TRIPLET_STORE_BATCH_SIZE, TRIPLET_STORE_ENABLE_CACHING, etc.
- Config files: YAML, JSON, TOML formats
- Programmatic: Python API for setting triple store configurations
- Programmatic: Python API for setting triplet store configurations
Algorithms Used:
- Environment Variable Parsing: OS-level environment variable access
@@ -19,7 +19,7 @@ Algorithms Used:
- Dictionary Merging: Deep merge algorithms for configuration updates
Key Features:
- Environment variable support for triple store parameters
- Environment variable support for triplet store parameters
- Config file support (YAML, JSON, TOML formats)
- Programmatic configuration via Python API
- Method-specific configuration management
@@ -27,13 +27,13 @@ Key Features:
- Global config instance for easy access
Main Classes:
- TripleStoreConfig: Main configuration manager class for triple store module
- TripletStoreConfig: Main configuration manager class for triplet store module
Example Usage:
>>> from semantica.triple_store.config import triple_store_config
>>> default_store = triple_store_config.get("default_store", default="main")
>>> triple_store_config.set("default_store", "main")
>>> method_config = triple_store_config.get_method_config("add_triple")
>>> from semantica.triplet_store.config import triplet_store_config
>>> default_store = triplet_store_config.get("default_store", default="main")
>>> triplet_store_config.set("default_store", "main")
>>> method_config = triplet_store_config.get_method_config("add_triple")
"""
import os
@@ -43,8 +43,8 @@ from typing import Any, Dict, Optional
from ..utils.logging import get_logger
class TripleStoreConfig:
"""Configuration manager for triple store module - supports .env files, environment variables, and programmatic config."""
class TripletStoreConfig:
"""Configuration manager for triplet store module - supports .env files, environment variables, and programmatic config."""
def __init__(self, config_file: Optional[str] = None):
"""
@@ -53,7 +53,7 @@ class TripleStoreConfig:
Args:
config_file: Optional path to configuration file (YAML, JSON, or TOML)
"""
self.logger = get_logger("triple_store_config")
self.logger = get_logger("triplet_store_config")
self.config_file = config_file
self._config: Dict[str, Any] = {}
self._method_configs: Dict[str, Dict[str, Any]] = {}
@@ -86,40 +86,40 @@ class TripleStoreConfig:
with open(file_path, "r") as f:
config_data = yaml.safe_load(f)
if config_data and "triple_store" in config_data:
self._config.update(config_data["triple_store"])
if config_data and "triplet_store" in config_data:
self._config.update(config_data["triplet_store"])
elif file_path.suffix == ".json":
import json
with open(file_path, "r") as f:
config_data = json.load(f)
if config_data and "triple_store" in config_data:
self._config.update(config_data["triple_store"])
if config_data and "triplet_store" in config_data:
self._config.update(config_data["triplet_store"])
elif file_path.suffix == ".toml":
import tomli
with open(file_path, "rb") as f:
config_data = tomli.load(f)
if config_data and "triple_store" in config_data:
self._config.update(config_data["triple_store"])
if config_data and "triplet_store" in config_data:
self._config.update(config_data["triplet_store"])
except Exception as e:
self.logger.error(f"Failed to load config file: {e}")
def _load_from_env(self) -> None:
"""Load configuration from environment variables."""
env_mappings = {
"TRIPLE_STORE_DEFAULT_STORE": "default_store",
"TRIPLE_STORE_BATCH_SIZE": "batch_size",
"TRIPLE_STORE_ENABLE_CACHING": "enable_caching",
"TRIPLE_STORE_CACHE_SIZE": "cache_size",
"TRIPLE_STORE_ENABLE_OPTIMIZATION": "enable_optimization",
"TRIPLE_STORE_MAX_RETRIES": "max_retries",
"TRIPLE_STORE_RETRY_DELAY": "retry_delay",
"TRIPLE_STORE_TIMEOUT": "timeout",
"TRIPLE_STORE_BLAZEGRAPH_ENDPOINT": "blazegraph_endpoint",
"TRIPLE_STORE_JENA_ENDPOINT": "jena_endpoint",
"TRIPLE_STORE_RDF4J_ENDPOINT": "rdf4j_endpoint",
"TRIPLE_STORE_VIRTUOSO_ENDPOINT": "virtuoso_endpoint",
"TRIPLET_STORE_DEFAULT_STORE": "default_store",
"TRIPLET_STORE_BATCH_SIZE": "batch_size",
"TRIPLET_STORE_ENABLE_CACHING": "enable_caching",
"TRIPLET_STORE_CACHE_SIZE": "cache_size",
"TRIPLET_STORE_ENABLE_OPTIMIZATION": "enable_optimization",
"TRIPLET_STORE_MAX_RETRIES": "max_retries",
"TRIPLET_STORE_RETRY_DELAY": "retry_delay",
"TRIPLET_STORE_TIMEOUT": "timeout",
"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():
@@ -238,4 +238,4 @@ class TripleStoreConfig:
# Global configuration instance
triple_store_config = TripleStoreConfig()
triplet_store_config = TripletStoreConfig()
@@ -16,7 +16,7 @@ Main Classes:
- JenaAdapter: Main Jena integration adapter
Example Usage:
>>> from semantica.triple_store import JenaAdapter
>>> from semantica.triplet_store import JenaAdapter
>>> adapter = JenaAdapter(endpoint="http://localhost:3030/ds", dataset="default")
>>> result = adapter.add_triples(triples)
>>> query_result = adapter.execute_sparql(sparql_query)
@@ -47,7 +47,7 @@ except ImportError:
class JenaAdapter:
"""
Apache Jena adapter for triple store operations.
Apache Jena adapter for triplet store operations.
Jena connection and configuration
SPARQL query execution
@@ -129,7 +129,7 @@ class JenaAdapter:
Operation status
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="JenaAdapter",
message=f"Adding {len(triples)} triples to Jena model",
)
@@ -1,14 +1,14 @@
"""
Triple Store Methods Module
Triplet Store Methods Module
This module provides all triple store methods as simple, reusable functions for
registering stores, adding triples, querying, and managing triple stores. It supports
This module provides all triplet store methods as simple, reusable functions for
registering stores, adding triples, querying, and managing triplet stores. It supports
multiple approaches and integrates with the method registry for extensibility.
Supported Methods:
Store Registration:
- "default": Default store registration using TripleManager
- "default": Default store registration using TripletManager
- "blazegraph": Blazegraph-specific registration
- "jena": Jena-specific registration
- "rdf4j": RDF4J-specific registration
@@ -78,7 +78,7 @@ Bulk Loading:
- Stream Processing: Iterator-based processing, incremental batch collection
Key Features:
- Multiple triple store operation methods
- Multiple triplet store operation methods
- Store registration with method dispatch
- Method dispatchers with registry support
- Custom method registration capability
@@ -95,11 +95,11 @@ Main Functions:
- optimize_query: Query optimization wrapper
- bulk_load: Bulk loading wrapper
- validate_triples: Triple validation wrapper
- get_triple_store_method: Get triple store method by task and name
- get_triplet_store_method: Get triplet store method by task and name
- list_available_methods: List registered methods
Example Usage:
>>> from semantica.triple_store.methods import register_store, add_triple, execute_query
>>> from semantica.triplet_store.methods import register_store, add_triple, execute_query
>>> store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph", method="default")
>>> result = add_triple(triple, store_id="main", method="default")
>>> query_result = execute_query(sparql_query, store_adapter, method="default")
@@ -109,23 +109,23 @@ from typing import Any, Dict, List, Optional, Union
from ..semantic_extract.triple_extractor import Triple
from .bulk_loader import BulkLoader, LoadProgress
from .config import triple_store_config
from .config import triplet_store_config
from .query_engine import QueryEngine, QueryPlan, QueryResult
from .registry import method_registry
from .triple_manager import TripleManager, TripleStore
from .triplet_manager import TripletManager, TripletStore
# Global manager instances
_global_manager: Optional[TripleManager] = None
_global_manager: Optional[TripletManager] = None
_global_query_engine: Optional[QueryEngine] = None
_global_bulk_loader: Optional[BulkLoader] = None
def _get_manager() -> TripleManager:
"""Get or create global TripleManager instance."""
def _get_manager() -> TripletManager:
"""Get or create global TripletManager instance."""
global _global_manager
if _global_manager is None:
config = triple_store_config.get_all()
_global_manager = TripleManager(config=config)
config = triplet_store_config.get_all()
_global_manager = TripletManager(config=config)
return _global_manager
@@ -133,7 +133,7 @@ def _get_query_engine() -> QueryEngine:
"""Get or create global QueryEngine instance."""
global _global_query_engine
if _global_query_engine is None:
config = triple_store_config.get_all()
config = triplet_store_config.get_all()
_global_query_engine = QueryEngine(config=config)
return _global_query_engine
@@ -142,16 +142,16 @@ def _get_bulk_loader() -> BulkLoader:
"""Get or create global BulkLoader instance."""
global _global_bulk_loader
if _global_bulk_loader is None:
config = triple_store_config.get_all()
config = triplet_store_config.get_all()
_global_bulk_loader = BulkLoader(config=config)
return _global_bulk_loader
def register_store(
store_id: str, store_type: str, endpoint: str, method: str = "default", **options
) -> TripleStore:
) -> TripletStore:
"""
Register a triple store.
Register a triplet store.
Args:
store_id: Store identifier
@@ -321,7 +321,7 @@ def execute_query(
Args:
query: SPARQL query string
store_adapter: Triple store adapter instance
store_adapter: Triplet store adapter instance
method: Query method name (default: "default")
**options: Additional options
@@ -383,7 +383,7 @@ def bulk_load(
Args:
triples: List of triples to load
store_adapter: Triple store adapter instance
store_adapter: Triplet store adapter instance
method: Loading method name (default: "default")
**options: Additional options
@@ -424,9 +424,9 @@ def validate_triples(
return loader.validate_before_load(triples, **options)
def get_triple_store_method(task: str, method_name: str) -> Optional[Any]:
def get_triplet_store_method(task: str, method_name: str) -> Optional[Any]:
"""
Get triple store method by task and name.
Get triplet store method by task and name.
Args:
task: Task type (register, add, get, delete, update, query, optimize, bulk_load, validate)
@@ -440,7 +440,7 @@ def get_triple_store_method(task: str, method_name: str) -> Optional[Any]:
def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
"""
List all available triple store methods.
List all available triplet store methods.
Args:
task: Optional task type to filter by
@@ -2,7 +2,7 @@
Query Engine Module
This module provides comprehensive SPARQL query execution and optimization
for triple store operations, including query planning, caching, and performance
for triplet store operations, including query planning, caching, and performance
monitoring.
Key Features:
@@ -20,7 +20,7 @@ Main Classes:
- QueryPlan: Query execution plan representation dataclass
Example Usage:
>>> from semantica.triple_store import QueryEngine
>>> from semantica.triplet_store import QueryEngine
>>> engine = QueryEngine(enable_caching=True, enable_optimization=True)
>>> result = engine.execute_query(sparql_query, store_adapter)
>>> plan = engine.plan_query(sparql_query)
@@ -109,7 +109,7 @@ class QueryEngine:
Query result
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="QueryEngine",
message="Executing SPARQL query",
)
@@ -16,7 +16,7 @@ Main Classes:
- RDF4JAdapter: Main RDF4J integration adapter
Example Usage:
>>> from semantica.triple_store import RDF4JAdapter
>>> from semantica.triplet_store import RDF4JAdapter
>>> adapter = RDF4JAdapter(endpoint="http://localhost:8080/rdf4j-server", repository_id="repo1")
>>> result = adapter.execute_sparql(sparql_query)
>>> tx_id = adapter.begin_transaction()
@@ -38,7 +38,7 @@ from ..utils.progress_tracker import get_progress_tracker
class RDF4JAdapter:
"""
Eclipse RDF4J adapter for triple store operations.
Eclipse RDF4J adapter for triplet store operations.
RDF4J connection and repository management
SPARQL query execution
@@ -184,7 +184,7 @@ class RDF4JAdapter:
Query results
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="RDF4JAdapter",
message="Executing SPARQL query on RDF4J",
)
@@ -250,7 +250,7 @@ class RDF4JAdapter:
Operation status
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="RDF4JAdapter",
message=f"Adding {len(triples)} triples to RDF4J repository",
)
@@ -1,11 +1,11 @@
"""
Method Registry Module for Triple Store
Method Registry Module for Triplet Store
This module provides a method registry system for registering custom triple store methods,
enabling extensibility and community contributions to the triple store toolkit.
This module provides a method registry system for registering custom triplet store methods,
enabling extensibility and community contributions to the triplet store toolkit.
Supported Registration Types:
- Method Registry: Register custom triple store methods for:
- Method Registry: Register custom triplet store methods for:
* "register": Store registration methods
* "add": Triple addition methods
* "get": Triple retrieval methods
@@ -24,20 +24,20 @@ Algorithms Used:
- Task-based Organization: Hierarchical organization by task type
Key Features:
- Method registry for custom triple store methods
- Method registry for custom triplet store methods
- Task-based method organization (register, add, get, delete, update, query, optimize, bulk_load, validate)
- Dynamic registration and unregistration
- Easy discovery of available methods
- Support for community-contributed extensions
Main Classes:
- MethodRegistry: Registry for custom triple store methods
- MethodRegistry: Registry for custom triplet store methods
Global Instances:
- method_registry: Global method registry instance
Example Usage:
>>> from semantica.triple_store.registry import method_registry
>>> from semantica.triplet_store.registry import method_registry
>>> method_registry.register("add", "custom_method", custom_add_function)
>>> available = method_registry.list_all("add")
"""
@@ -46,7 +46,7 @@ from typing import Any, Callable, Dict, List, Optional
class MethodRegistry:
"""Registry for custom triple store methods."""
"""Registry for custom triplet store methods."""
def __init__(self):
"""Initialize method registry."""
@@ -1,25 +1,25 @@
"""
Triple Manager Module
Triplet Manager Module
This module provides comprehensive CRUD operations for RDF triples and triple
store management, enabling unified access to multiple triple store backends
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 triples
- CRUD operations for RDF triplets
- Multi-store management and registration
- Batch operations and bulk loading
- Triple validation and consistency
- Triplet validation and consistency
- Store adapter pattern
- Error handling and recovery
Main Classes:
- TripleManager: Main triple store management coordinator
- TripleStore: Triple store configuration dataclass
- TripletManager: Main triplet store management coordinator
- TripletStore: Triplet store configuration dataclass
Example Usage:
>>> from semantica.triple_store import TripleManager
>>> manager = TripleManager()
>>> from semantica.triplet_store import TripletManager
>>> manager = TripletManager()
>>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
>>> result = manager.add_triple(triple, store_id="main")
>>> triples = manager.get_triple(subject="http://example.org/entity1")
@@ -39,8 +39,8 @@ from ..utils.progress_tracker import get_progress_tracker
@dataclass
class TripleStore:
"""Triple store configuration."""
class TripletStore:
"""Triplet store configuration."""
store_id: str
store_type: str # "blazegraph", "jena", "rdf4j", "virtuoso"
@@ -49,9 +49,9 @@ class TripleStore:
connected: bool = False
class TripleManager:
class TripletManager:
"""
Triple store management system.
Triplet store management system.
CRUD operations for RDF triples
Batch operations and bulk loading
@@ -63,26 +63,26 @@ class TripleManager:
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize triple manager.
Initialize triplet manager.
Args:
config: Configuration dictionary
**kwargs: Additional configuration options:
- default_store: Default triple store to use
- default_store: Default triplet store to use
"""
self.logger = get_logger("triple_manager")
self.logger = get_logger("triplet_manager")
self.config = config or {}
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
self.stores: Dict[str, TripleStore] = {}
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
) -> TripleStore:
) -> TripletStore:
"""
Register a triple store.
Register a triplet store.
Args:
store_id: Store identifier
@@ -93,7 +93,7 @@ class TripleManager:
Returns:
Registered store
"""
store = TripleStore(
store = TripletStore(
store_id=store_id, store_type=store_type, endpoint=endpoint, config=config
)
@@ -102,7 +102,7 @@ class TripleManager:
if not self.default_store_id:
self.default_store_id = store_id
self.logger.info(f"Registered triple store: {store_id} ({store_type})")
self.logger.info(f"Registered triplet store: {store_id} ({store_type})")
return store
@@ -158,8 +158,8 @@ class TripleManager:
Operation status
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
submodule="TripleManager",
module="triplet_store",
submodule="TripletManager",
message=f"Adding {len(triples)} triples to store",
)
@@ -301,7 +301,7 @@ class TripleManager:
return True
def _get_store(self, store_id: Optional[str] = None) -> TripleStore:
def _get_store(self, store_id: Optional[str] = None) -> TripletStore:
"""Get store by ID."""
store_id = store_id or self.default_store_id
@@ -313,7 +313,7 @@ class TripleManager:
return self.stores[store_id]
def _get_adapter(self, store: TripleStore) -> Any:
def _get_adapter(self, store: TripletStore) -> Any:
"""Get adapter for store type."""
store_type = store.store_type.lower()
@@ -336,7 +336,7 @@ class TripleManager:
else:
raise ValidationError(f"Unsupported store type: {store_type}")
def get_store(self, store_id: str) -> Optional[TripleStore]:
def get_store(self, store_id: str) -> Optional[TripletStore]:
"""Get store by ID."""
return self.stores.get(store_id)
@@ -1,6 +1,6 @@
# Triple Store Module Usage Guide
# Triplet Store Module Usage Guide
This comprehensive guide demonstrates how to use the triple store module for RDF data storage and querying, supporting multiple triple 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, Virtuoso) with unified interfaces, SPARQL query execution, bulk loading, and query optimization.
## Table of Contents
@@ -17,14 +17,14 @@ This comprehensive guide demonstrates how to use the triple store module for RDF
## Basic Usage
### Using TripleManager
### Using TripletManager
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
from semantica.semantic_extract.triple_extractor import Triple
# Create triple manager
manager = TripleManager()
# Create triplet manager
manager = TripletManager()
# Register a store
store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
@@ -44,7 +44,7 @@ print(f"Triple added: {result['success']}")
### Using Convenience Functions
```python
from semantica.triple_store import register_store, add_triple, get_triples, execute_query
from semantica.triplet_store import register_store, add_triple, get_triples, execute_query
from semantica.semantic_extract.triple_extractor import Triple
# Register store
@@ -66,7 +66,7 @@ print(f"Found {len(triples)} triples")
### Using QueryEngine
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
# Create query engine
engine = QueryEngine(enable_caching=True, enable_optimization=True)
@@ -87,9 +87,9 @@ print(f"Execution time: {result.execution_time:.2f}s")
### Registering a Store
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
manager = TripleManager()
manager = TripletManager()
# Register Blazegraph store
blazegraph_store = manager.register_store(
@@ -126,7 +126,7 @@ virtuoso_store = manager.register_store(
### Using Convenience Function
```python
from semantica.triple_store import register_store
from semantica.triplet_store import register_store
# Register store using convenience function
store = register_store(
@@ -143,9 +143,9 @@ print(f"Store type: {store.store_type}")
### Multiple Stores
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
manager = TripleManager()
manager = TripletManager()
# Register multiple stores
manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
@@ -165,10 +165,10 @@ print(f"Store endpoint: {store.endpoint}")
### Adding Triples
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
from semantica.semantic_extract.triple_extractor import Triple
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# Add single triple
@@ -194,9 +194,9 @@ print(f"Added {result['total_triples']} triples in {result['batches']} batches")
### Retrieving Triples
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# Get all triples for a subject
@@ -225,10 +225,10 @@ triples = manager.get_triple(
### Deleting Triples
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
from semantica.semantic_extract.triple_extractor import Triple
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# Delete triple
@@ -244,10 +244,10 @@ print(f"Deleted: {result['success']}")
### Updating Triples
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
from semantica.semantic_extract.triple_extractor import Triple
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
# Update triple (delete old, add new)
@@ -270,7 +270,7 @@ print(f"Updated: {result['success']}")
### Basic Query Execution
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
# Create query engine
engine = QueryEngine(enable_caching=True)
@@ -298,7 +298,7 @@ for binding in result.bindings[:5]:
### Using Convenience Function
```python
from semantica.triple_store import execute_query, BlazegraphAdapter
from semantica.triplet_store import execute_query, BlazegraphAdapter
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
@@ -311,7 +311,7 @@ print(f"Found {len(result.bindings)} results")
### Query Result Processing
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
engine = QueryEngine()
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
@@ -332,7 +332,7 @@ print(f"Metadata: {result.metadata}")
### Query Caching
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
# Enable caching
engine = QueryEngine(enable_caching=True, cache_size=1000)
@@ -357,7 +357,7 @@ engine.clear_cache()
### Basic Query Optimization
```python
from semantica.triple_store import QueryEngine
from semantica.triplet_store import QueryEngine
engine = QueryEngine(enable_optimization=True)
@@ -377,7 +377,7 @@ print(f"Optimized query:\n{optimized}")
### Query Planning
```python
from semantica.triple_store import QueryEngine
from semantica.triplet_store import QueryEngine
engine = QueryEngine(enable_optimization=True)
@@ -403,7 +403,7 @@ print(f"Execution steps: {plan.execution_steps}")
### Query Statistics
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
engine = QueryEngine(enable_caching=True)
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
@@ -427,7 +427,7 @@ print(f"Cache size: {stats['cache_size']}")
### Basic Bulk Loading
```python
from semantica.triple_store import BulkLoader, BlazegraphAdapter
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
from semantica.semantic_extract.triple_extractor import Triple
# Create bulk loader
@@ -455,7 +455,7 @@ print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec")
### Progress Tracking
```python
from semantica.triple_store import BulkLoader, BlazegraphAdapter, LoadProgress
from semantica.triplet_store import BulkLoader, BlazegraphAdapter, LoadProgress
from semantica.semantic_extract.triple_extractor import Triple
loader = BulkLoader(batch_size=1000)
@@ -476,7 +476,7 @@ progress = loader.load_triples(triples, adapter, progress_callback=progress_call
### Pre-load Validation
```python
from semantica.triple_store import BulkLoader
from semantica.triplet_store import BulkLoader
from semantica.semantic_extract.triple_extractor import Triple
loader = BulkLoader()
@@ -501,7 +501,7 @@ print(f"Valid triples: {validation['valid_triples']}/{validation['total_triples'
### Stream-based Loading
```python
from semantica.triple_store import BulkLoader, BlazegraphAdapter
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
from semantica.semantic_extract.triple_extractor import Triple
loader = BulkLoader(batch_size=1000)
@@ -522,7 +522,7 @@ print(f"Loaded {progress.loaded_triples} triples from stream")
### Blazegraph Adapter
```python
from semantica.triple_store import BlazegraphAdapter
from semantica.triplet_store import BlazegraphAdapter
from semantica.semantic_extract.triple_extractor import Triple
# Create Blazegraph adapter
@@ -548,7 +548,7 @@ print(f"Found {len(result['bindings'])} results")
### Jena Adapter
```python
from semantica.triple_store import JenaAdapter
from semantica.triplet_store import JenaAdapter
from semantica.semantic_extract.triple_extractor import Triple
# Create Jena adapter (in-memory)
@@ -575,7 +575,7 @@ print(turtle)
### RDF4J Adapter
```python
from semantica.triple_store import RDF4JAdapter
from semantica.triplet_store import RDF4JAdapter
from semantica.semantic_extract.triple_extractor import Triple
# Create RDF4J adapter
@@ -594,7 +594,7 @@ result = adapter.add_triples(triples)
### Virtuoso Adapter
```python
from semantica.triple_store import VirtuosoAdapter
from semantica.triplet_store import VirtuosoAdapter
from semantica.semantic_extract.triple_extractor import Triple
# Create Virtuoso adapter
@@ -613,7 +613,7 @@ result = adapter.add_triples(triples)
## Algorithms and Methods
### Triple Store Management Algorithms
### Triplet Store Management Algorithms
#### Store Registration
**Algorithm**: Store type detection and adapter factory pattern
@@ -783,9 +783,9 @@ cost = engine._estimate_query_cost(query)
### Methods
#### TripleManager Methods
#### TripletManager Methods
- `register_store(store_id, store_type, endpoint, **config)`: Register triple store
- `register_store(store_id, store_type, endpoint, **config)`: Register triplet store
- `add_triple(triple, store_id, **options)`: Add single triple
- `add_triples(triples, store_id, **options)`: Add multiple triples
- `get_triple(subject, predicate, object, store_id, **options)`: Get triples matching pattern
@@ -824,14 +824,14 @@ cost = engine._estimate_query_cost(query)
## Dataclasses
### TripleStore
### TripletStore
Configuration dataclass for triple store instances.
Configuration dataclass for triplet store instances.
```python
from semantica.triple_store import TripleStore
from semantica.triplet_store import TripletStore
store = TripleStore(
store = TripletStore(
store_id="main",
store_type="blazegraph",
endpoint="http://localhost:9999/blazegraph/sparql",
@@ -856,7 +856,7 @@ print(f"Type: {store.store_type}")
Query execution result dataclass.
```python
from semantica.triple_store import QueryEngine, QueryResult
from semantica.triplet_store import QueryEngine, QueryResult
engine = QueryEngine()
result: QueryResult = engine.execute_query(query, adapter)
@@ -877,7 +877,7 @@ print(f"Execution time: {result.execution_time:.2f}s")
Query execution plan dataclass.
```python
from semantica.triple_store import QueryEngine, QueryPlan
from semantica.triplet_store import QueryEngine, QueryPlan
engine = QueryEngine(enable_optimization=True)
plan: QueryPlan = engine.plan_query(query)
@@ -897,38 +897,38 @@ print(f"Execution steps: {plan.execution_steps}")
### Environment Variables
```bash
# Triple store configuration
export TRIPLE_STORE_DEFAULT_STORE=main
export TRIPLE_STORE_BATCH_SIZE=1000
export TRIPLE_STORE_ENABLE_CACHING=true
export TRIPLE_STORE_CACHE_SIZE=1000
export TRIPLE_STORE_ENABLE_OPTIMIZATION=true
export TRIPLE_STORE_MAX_RETRIES=3
export TRIPLE_STORE_RETRY_DELAY=1.0
export TRIPLE_STORE_TIMEOUT=30
# 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 TRIPLE_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph
export TRIPLE_STORE_JENA_ENDPOINT=http://localhost:3030/ds
export TRIPLE_STORE_RDF4J_ENDPOINT=http://localhost:8080/rdf4j-server
export TRIPLE_STORE_VIRTUOSO_ENDPOINT=http://localhost:8890/sparql
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.triple_store.config import triple_store_config
from semantica.triplet_store.config import triplet_store_config
# Get configuration
batch_size = triple_store_config.get("batch_size", default=1000)
enable_caching = triple_store_config.get("enable_caching", default=True)
batch_size = triplet_store_config.get("batch_size", default=1000)
enable_caching = triplet_store_config.get("enable_caching", default=True)
# Set configuration
triple_store_config.set("batch_size", 2000)
triple_store_config.set("enable_caching", False)
triplet_store_config.set("batch_size", 2000)
triplet_store_config.set("enable_caching", False)
# Update with dictionary
triple_store_config.update({
triplet_store_config.update({
"batch_size": 2000,
"enable_caching": True,
"cache_size": 2000
@@ -939,7 +939,7 @@ triple_store_config.update({
```yaml
# config.yaml
triple_store:
triplet_store:
default_store: main
batch_size: 1000
enable_caching: true
@@ -956,11 +956,11 @@ triple_store:
## Advanced Examples
### Complete Triple Store Pipeline
### Complete Triplet Store Pipeline
```python
from semantica.triple_store import (
TripleManager,
from semantica.triplet_store import (
TripletManager,
QueryEngine,
BulkLoader,
register_store,
@@ -980,7 +980,7 @@ triples = [
result = add_triples(triples, store_id="main", batch_size=100)
# 3. Execute queries
from semantica.triple_store import BlazegraphAdapter
from semantica.triplet_store import BlazegraphAdapter
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
query_result = execute_query(query, adapter)
@@ -992,10 +992,10 @@ print(f"Query returned {len(query_result.bindings)} results")
### Multi-Store Operations
```python
from semantica.triple_store import TripleManager
from semantica.triplet_store import TripletManager
from semantica.semantic_extract.triple_extractor import Triple
manager = TripleManager()
manager = TripletManager()
# Register multiple stores
manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
@@ -1012,7 +1012,7 @@ manager.add_triple(triple, store_id="backup")
### Query Optimization Workflow
```python
from semantica.triple_store import QueryEngine, BlazegraphAdapter
from semantica.triplet_store import QueryEngine, BlazegraphAdapter
engine = QueryEngine(enable_optimization=True, enable_caching=True)
adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
@@ -1040,7 +1040,7 @@ print(f"Optimized: {result.metadata.get('optimized', False)}")
### Bulk Loading with Validation
```python
from semantica.triple_store import BulkLoader, BlazegraphAdapter
from semantica.triplet_store import BulkLoader, BlazegraphAdapter
from semantica.semantic_extract.triple_extractor import Triple
loader = BulkLoader(batch_size=1000, max_retries=3)
@@ -1066,22 +1066,22 @@ else:
### Custom Method Registration
```python
from semantica.triple_store.registry import method_registry
from semantica.triple_store import add_triple
from semantica.triplet_store.registry import method_registry
from semantica.triplet_store import add_triple
# Register custom add method
def custom_add_triple(triple, store_id=None, **options):
# Custom logic
print(f"Custom add: {triple.subject}")
# Call default implementation
from semantica.triple_store.methods import _get_manager
from semantica.triplet_store.methods import _get_manager
manager = _get_manager()
return manager.add_triple(triple, store_id=store_id, **options)
method_registry.register("add", "custom", custom_add_triple)
# Use custom method
from semantica.triple_store.methods import add_triple
from semantica.triplet_store.methods import add_triple
result = add_triple(triple, store_id="main", method="custom")
```
@@ -16,7 +16,7 @@ Main Classes:
- VirtuosoAdapter: Main Virtuoso integration adapter
Example Usage:
>>> from semantica.triple_store import VirtuosoAdapter
>>> from semantica.triplet_store import VirtuosoAdapter
>>> adapter = VirtuosoAdapter(endpoint="http://localhost:8890/sparql", username="dba", password="dba")
>>> result = adapter.execute_sparql(sparql_query)
>>> load_result = adapter.bulk_load(triples, graph="http://example.org/graph")
@@ -147,7 +147,7 @@ class VirtuosoAdapter:
Query results
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="VirtuosoAdapter",
message="Executing SPARQL query on Virtuoso",
)
@@ -240,7 +240,7 @@ class VirtuosoAdapter:
Load status
"""
tracking_id = self.progress_tracker.start_tracking(
module="triple_store",
module="triplet_store",
submodule="VirtuosoAdapter",
message=f"Bulk loading {len(triples)} triples to Virtuoso",
)
+5 -5
View File
@@ -121,7 +121,7 @@ class ConsoleProgressDisplay(ProgressDisplay):
"semantic_extract": "🎯",
"seed": "🌱",
"split": "✂️",
"triple_store": "🗄️",
"triplet_store": "🗄️",
"vector_store": "📊",
"export": "💾",
"reasoning": "🤔",
@@ -176,7 +176,7 @@ class ConsoleProgressDisplay(ProgressDisplay):
"semantic_extract": "is extracting",
"seed": "is seeding",
"split": "is splitting",
"triple_store": "is storing",
"triplet_store": "is storing",
"vector_store": "is indexing",
"export": "is exporting",
"reasoning": "is reasoning",
@@ -352,7 +352,7 @@ class JupyterProgressDisplay(ProgressDisplay):
"semantic_extract": "🎯",
"seed": "🌱",
"split": "✂️",
"triple_store": "🗄️",
"triplet_store": "🗄️",
"vector_store": "📊",
"export": "💾",
"reasoning": "🤔",
@@ -405,7 +405,7 @@ class JupyterProgressDisplay(ProgressDisplay):
"semantic_extract": "is extracting",
"seed": "is seeding",
"split": "is splitting",
"triple_store": "is storing",
"triplet_store": "is storing",
"vector_store": "is indexing",
"export": "is exporting",
"reasoning": "is reasoning",
@@ -901,7 +901,7 @@ class ProgressTracker:
"semantic_extract": "🎯",
"seed": "🌱",
"split": "✂️",
"triple_store": "🗄️",
"triplet_store": "🗄️",
"vector_store": "📊",
"export": "💾",
"reasoning": "🤔",
+1 -1
View File
@@ -15,7 +15,7 @@ modules = {
"kg": "semantica.kg",
"embeddings": "semantica.embeddings",
"vector_store": "semantica.vector_store",
"triple_store": "semantica.triple_store",
"triplet_store": "semantica.triplet_store",
"ontology": "semantica.ontology",
"reasoning": "semantica.reasoning",
"pipeline": "semantica.pipeline",
@@ -1,19 +1,19 @@
import unittest
from unittest.mock import MagicMock, patch
from semantica.triple_store.triple_manager import TripleManager, TripleStore
from semantica.triple_store.query_engine import QueryEngine, QueryResult
from semantica.triplet_store.triplet_manager import TripletManager, TripletStore
from semantica.triplet_store.query_engine import QueryEngine, QueryResult
from semantica.semantic_extract.triple_extractor import Triple
class TestTripleStore(unittest.TestCase):
class TestTripletStore(unittest.TestCase):
def setUp(self):
self.mock_logger = MagicMock()
self.mock_tracker = MagicMock()
self.logger_patcher = patch('semantica.triple_store.triple_manager.get_logger', return_value=self.mock_logger)
self.tracker_patcher = patch('semantica.triple_store.triple_manager.get_progress_tracker', return_value=self.mock_tracker)
self.logger_patcher_qe = patch('semantica.triple_store.query_engine.get_logger', return_value=self.mock_logger)
self.tracker_patcher_qe = patch('semantica.triple_store.query_engine.get_progress_tracker', return_value=self.mock_tracker)
self.logger_patcher = patch('semantica.triplet_store.triplet_manager.get_logger', return_value=self.mock_logger)
self.tracker_patcher = patch('semantica.triplet_store.triplet_manager.get_progress_tracker', return_value=self.mock_tracker)
self.logger_patcher_qe = patch('semantica.triplet_store.query_engine.get_logger', return_value=self.mock_logger)
self.tracker_patcher_qe = patch('semantica.triplet_store.query_engine.get_progress_tracker', return_value=self.mock_tracker)
self.logger_patcher.start()
self.tracker_patcher.start()
@@ -26,23 +26,23 @@ class TestTripleStore(unittest.TestCase):
self.logger_patcher_qe.stop()
self.tracker_patcher_qe.stop()
def test_triple_manager_init(self):
manager = TripleManager(default_store="main")
def test_triplet_manager_init(self):
manager = TripletManager(default_store="main")
self.assertEqual(manager.default_store_id, "main")
self.assertEqual(manager.stores, {})
def test_register_store(self):
manager = TripleManager()
manager = TripletManager()
store = manager.register_store("main", "blazegraph", "http://localhost:9999")
self.assertIsInstance(store, TripleStore)
self.assertIsInstance(store, TripletStore)
self.assertEqual(store.store_id, "main")
self.assertEqual(store.store_type, "blazegraph")
self.assertEqual(store.endpoint, "http://localhost:9999")
self.assertIn("main", manager.stores)
@patch('semantica.triple_store.triple_manager.TripleManager._get_adapter')
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
def test_add_triple(self, mock_get_adapter):
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
@@ -56,9 +56,9 @@ class TestTripleStore(unittest.TestCase):
self.assertEqual(result["store_id"], "main")
mock_adapter.add_triple.assert_called_once_with(triple)
@patch('semantica.triple_store.triple_manager.TripleManager._get_adapter')
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
def test_add_triples(self, mock_get_adapter):
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
@@ -76,9 +76,9 @@ class TestTripleStore(unittest.TestCase):
self.assertEqual(result["total_triples"], 2)
mock_adapter.add_triples.assert_called()
@patch('semantica.triple_store.triple_manager.TripleManager._get_adapter')
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
def test_get_triple(self, mock_get_adapter):
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
@@ -91,9 +91,9 @@ class TestTripleStore(unittest.TestCase):
self.assertEqual(result, expected_triples)
mock_adapter.get_triples.assert_called_once_with("s", None, None)
@patch('semantica.triple_store.triple_manager.TripleManager._get_adapter')
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
def test_delete_triple(self, mock_get_adapter):
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()
@@ -106,9 +106,9 @@ class TestTripleStore(unittest.TestCase):
self.assertTrue(result["success"])
mock_adapter.delete_triple.assert_called_once_with(triple)
@patch('semantica.triple_store.triple_manager.TripleManager._get_adapter')
@patch('semantica.triplet_store.triplet_manager.TripletManager._get_adapter')
def test_update_triple(self, mock_get_adapter):
manager = TripleManager()
manager = TripletManager()
manager.register_store("main", "blazegraph", "http://localhost:9999")
mock_adapter = MagicMock()