Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
docs(triple_store): complete documentation and add comprehensive notebook
KaifAhmad19fcb1c5410ca
diff --git a/cookbook/introduction/20_Triple_Store.ipynb b/cookbook/introduction/20_Triple_Store.ipynbnew file mode 100644index 00000000..efdb7cd1--- /dev/null+++ b/cookbook/introduction/20_Triple_Store.ipynb@@ -0,0 +1,774 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/20_Triple_Store.ipynb)\n",+ "\n",+ "# Triple 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",+ "\n",+ "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/triple_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",+ "- 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",+ "- 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",+ "| `QueryEngine` | SPARQL execution | Query optimization |\n",+ "| `BulkLoader` | High-volume loading | Large datasets |\n",+ "| `BlazegraphAdapter` | Blazegraph backend | High performance |\n",+ "| `JenaAdapter` | Jena backend | Java integration |\n",+ "| `RDF4JAdapter` | RDF4J backend | Transaction support |\n",+ "| `VirtuosoAdapter` | 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",+ "---"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 1: Basic Triple Store Operations\n",+ "\n",+ "Let's start with the `TripleManager` for basic triple store operations.\n",+ "\n",+ "### What is TripleManager?\n",+ "\n",+ "`TripleManager` is the main coordinator for triple store operations:\n",+ "- **Store Registration**: Register multiple backends\n",+ "- **CRUD Operations**: Add, get, update, delete triples\n",+ "- **Multi-Store**: Manage multiple stores simultaneously"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import TripleManager\n",+ "from semantica.semantic_extract.triple_extractor import Triple\n",+ "\n",+ "# Create triple manager\n",+ "manager = TripleManager()\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",+ ")\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 triple\n",+ "triple = Triple(\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 triple to store\n",+ "result = manager.add_triple(triple, store_id=\"demo\")\n",+ "print(f\"\\nTriple added: {result['success']}\")\n",+ "print(f\"Triple: {triple.subject} -> {triple.predicate} -> {triple.object}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 2: Store Registration and Management\n",+ "\n",+ "Register multiple stores and manage them.\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 |"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_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 triples.\n",+ "\n",+ "### Operations Overview\n",+ "\n",+ "- **Create**: `add_triple()`, `add_triples()`\n",+ "- **Read**: `get_triple()`\n",+ "- **Update**: `update_triple()`\n",+ "- **Delete**: `delete_triple()`"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import add_triple, add_triples, get_triples, update_triple, delete_triple\n",+ "\n",+ "# Create - Add single triple\n",+ "triple1 = Triple(\n",+ " subject=\"http://example.org/Alice\",\n",+ " predicate=\"http://example.org/hasAge\",\n",+ " object=\"30\"\n",+ ")\n",+ "result = add_triple(triple1, store_id=\"demo\")\n",+ "print(f\"Added single triple: {result['success']}\")\n",+ "\n",+ "# Create - Add multiple triples\n",+ "triples = [\n",+ " Triple(\"http://example.org/Alice\", \"http://example.org/hasCity\", \"New York\"),\n",+ " Triple(\"http://example.org/Bob\", \"http://example.org/hasAge\", \"25\"),\n",+ " Triple(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",+ "]\n",+ "result = add_triples(triples, store_id=\"demo\")\n",+ "print(f\"\\nAdded {result['total_triples']} triples in {result['batches']} batches\")\n",+ "\n",+ "# Read - Get triples for a subject\n",+ "alice_triples = get_triples(\n",+ " subject=\"http://example.org/Alice\",\n",+ " store_id=\"demo\"\n",+ ")\n",+ "print(f\"\\nFound {len(alice_triples)} triples for Alice\")\n",+ "\n",+ "# Update - Change Alice's age\n",+ "old_triple = Triple(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"30\")\n",+ "new_triple = Triple(\"http://example.org/Alice\", \"http://example.org/hasAge\", \"31\")\n",+ "result = update_triple(old_triple, new_triple, store_id=\"demo\")\n",+ "print(f\"\\nUpdated triple: {result['success']}\")\n",+ "\n",+ "# Delete - Remove a triple\n",+ "triple_to_delete = Triple(\"http://example.org/Bob\", \"http://example.org/hasCity\", \"Boston\")\n",+ "result = delete_triple(triple_to_delete, store_id=\"demo\")\n",+ "print(f\"Deleted triple: {result['success']}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 4: SPARQL Query Execution\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"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import QueryEngine, BlazegraphAdapter\n",+ "\n",+ "# Create query engine with caching\n",+ "engine = QueryEngine(enable_caching=True, enable_optimization=True)\n",+ "\n",+ "# Create adapter\n",+ "adapter = BlazegraphAdapter(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, adapter)\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.triple_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.triple_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 triples\n",+ "large_dataset = [\n",+ " Triple(\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_triples}/{progress.total_triples}) \"\n",+ " f\"Batch {progress.current_batch}/{progress.total_batches}\")\n",+ "\n",+ "# Load triples with progress tracking\n",+ "adapter = BlazegraphAdapter(endpoint=\"http://localhost:9999/blazegraph/sparql\")\n",+ "progress = loader.load_triples(\n",+ " large_dataset,\n",+ " adapter,\n",+ " progress_callback=progress_callback\n",+ ")\n",+ "\n",+ "print(f\"\\nLoading Complete:\")\n",+ "print(f\" Loaded: {progress.loaded_triples}/{progress.total_triples}\")\n",+ "print(f\" Failed: {progress.failed_triples}\")\n",+ "print(f\" Elapsed time: {progress.elapsed_time:.2f}s\")\n",+ "print(f\" Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 7: Store Adapters\n",+ "\n",+ "Work with different triple store backends.\n",+ "\n",+ "### Blazegraph Adapter\n",+ "\n",+ "High-performance triple store with GPU acceleration."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import BlazegraphAdapter\n",+ "\n",+ "# Create Blazegraph adapter\n",+ "blazegraph = BlazegraphAdapter(\n",+ " endpoint=\"http://localhost:9999/blazegraph/sparql\",\n",+ " namespace=\"kb\",\n",+ " timeout=30\n",+ ")\n",+ "\n",+ "# Add triples\n",+ "triples = [\n",+ " Triple(\"http://example.org/Alice\", \"http://example.org/hasSkill\", \"Python\")\n",+ "]\n",+ "result = blazegraph.add_triples(triples)\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 Adapter\n",+ "\n",+ "Full-featured RDF framework with inference support."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import JenaAdapter\n",+ "\n",+ "# Create Jena adapter (in-memory)\n",+ "jena = JenaAdapter()\n",+ "\n",+ "# Or connect to Fuseki endpoint\n",+ "# jena = JenaAdapter(\n",+ "# endpoint=\"http://localhost:3030/ds\",\n",+ "# dataset=\"default\",\n",+ "# enable_inference=True\n",+ "# )\n",+ "\n",+ "# Add triples with inference\n",+ "triples = [\n",+ " Triple(\n",+ " \"http://example.org/Dog\",\n",+ " \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",+ " \"http://example.org/Animal\"\n",+ " ),\n",+ " Triple(\n",+ " \"http://example.org/Fido\",\n",+ " \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",\n",+ " \"http://example.org/Dog\"\n",+ " )\n",+ "]\n",+ "result = jena.add_triples(triples)\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 Adapter\n",+ "\n",+ "Java-based RDF framework with transaction support."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import RDF4JAdapter\n",+ "\n",+ "# Create RDF4J adapter\n",+ "rdf4j = RDF4JAdapter(\n",+ " server_url=\"http://localhost:8080/rdf4j-server\",\n",+ " repository_id=\"test\"\n",+ ")\n",+ "\n",+ "# Add triples with transaction\n",+ "rdf4j.begin_transaction()\n",+ "try:\n",+ " triple = Triple(\n",+ " \"http://example.org/Alice\",\n",+ " \"http://example.org/hasEmail\",\n",+ " \"[email protected]\"\n",+ " )\n",+ " rdf4j.add_triple(\n",+ " subject=triple.subject,\n",+ " predicate=triple.predicate,\n",+ " object_literal=triple.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}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Virtuoso Adapter\n",+ "\n",+ "Enterprise-grade RDF store with SQL integration."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triple_store import VirtuosoAdapter\n",+ "\n",+ "# Create Virtuoso adapter\n",+ "virtuoso = VirtuosoAdapter(\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 triples to named graph\n",+ "triple = Triple(\n",+ " \"http://example.org/Alice\",\n",+ " \"http://example.org/worksAt\",\n",+ " \"http://example.org/Company1\"\n",+ ")\n",+ "virtuoso.add_triple(\n",+ " subject=triple.subject,\n",+ " predicate=triple.predicate,\n",+ " object=triple.object,\n",+ " graph=graph_uri\n",+ ")\n",+ "\n",+ "print(f\"Virtuoso - Added triple 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",+ "\"\"\"\n",+ "result = virtuoso.query(query)\n",+ "print(f\"Virtuoso - Found {len(result)} results in graph\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 8: Triple Validation\n",+ "\n",+ "Validate triples 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.triple_store import validate_triples\n",+ "\n",+ "# Create triples (some invalid)\n",+ "triples_to_validate = [\n",+ " Triple(\"http://example.org/Alice\", \"http://example.org/knows\", \"http://example.org/Bob\"), # Valid\n",+ " Triple(\"\", \"http://example.org/knows\", \"http://example.org/Charlie\"), # Invalid (empty subject)\n",+ " Triple(\"http://example.org/Dave\", \"\", \"http://example.org/Eve\"), # Invalid (empty predicate)\n",+ " Triple(\"http://example.org/Frank\", \"http://example.org/knows\", \"http://example.org/Grace\", confidence=1.5), # Invalid (confidence > 1)\n",+ "]\n",+ "\n",+ "# Validate triples\n",+ "validation = validate_triples(triples_to_validate)\n",+ "\n",+ "print(\"Validation Results:\")\n",+ "print(f\" Valid: {validation['valid']}\")\n",+ "print(f\" Valid triples: {validation['valid_triples']}/{validation['total_triples']}\")\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}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 9: Multi-Store Operations\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"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Register multiple stores\n",+ "manager = TripleManager()\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",+ "triple = Triple(\n",+ " \"http://example.org/Document1\",\n",+ " \"http://example.org/hasAuthor\",\n",+ " \"http://example.org/Alice\"\n",+ ")\n",+ "manager.add_triple(triple, store_id=\"primary\")\n",+ "print(\"Added to primary store\")\n",+ "\n",+ "# Replicate to backup store\n",+ "manager.add_triple(triple, 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_triples()` for multiple triples\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"+ ]+ },+ {+ "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 triple stores\n",+ "- Perform CRUD operations on RDF triples\n",+ "- Execute and optimize SPARQL queries\n",+ "- Use bulk loading for large datasets\n",+ "- Work with multiple store backends\n",+ "- Validate triples 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",+ "- [Triple Store API Reference](https://semantica.readthedocs.io/reference/triple_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",+ "\n",+ "**Questions or Issues?** Check out our [GitHub repository](https://github.com/Hawksight-AI/semantica) or [documentation](https://semantica.readthedocs.io)."+ ]+ }+ ],+ "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.10.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}\ No newline at end of filediff --git a/docs/reference/triple_store.md b/docs/reference/triple_store.mdindex bf12f861..2f32b544 100644--- a/docs/reference/triple_store.md+++ b/docs/reference/triple_store.md@@ -437,6 +437,101 @@ print(f"Valid: {validation_report['conforms']}")---+#### RDF4JAdapter++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.triple_store import RDF4JAdapter++adapter = RDF4JAdapter(+ server_url="http://localhost:8080/rdf4j-server",+ repository_id="my_repo"+)++adapter.connect()++# Add triples with transaction+adapter.begin_transaction()+try:+ adapter.add_triple(+ subject="http://example.org/Alice",+ predicate="http://example.org/name",+ object_literal="Alice"+ )+ adapter.commit_transaction()+except Exception as e:+ adapter.rollback_transaction()++# Query with reasoning+results = adapter.query("""+ PREFIX ex: <http://example.org/>+ SELECT ?person WHERE {+ ?person ex:name ?name .+ }+""", enable_reasoning=True)+```++---++#### VirtuosoAdapter++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.triple_store import VirtuosoAdapter++adapter = VirtuosoAdapter(+ host="localhost",+ port=1111,+ user="dba",+ password="dba"+)++adapter.connect()++# Add triples to named graph+graph_uri = "http://example.org/graph1"+adapter.create_graph(graph_uri)++adapter.add_triple(+ subject="http://example.org/Alice",+ predicate="http://example.org/name",+ object_literal="Alice",+ graph=graph_uri+)++# Query specific graph+results = adapter.query(f"""+ PREFIX ex: <http://example.org/>+ SELECT ?person ?name+ FROM <{graph_uri}>+ WHERE {{+ ?person ex:name ?name .+ }}+""")+```++---+## Convenience FunctionsQuick access to triple store operations:@@ -482,6 +577,72 @@ export_graph(---+## Dataclasses++### TripleStore++Configuration dataclass for triple 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_triples` | int | Number of triples loaded |+| `total_triples` | int | Total triples to load |+| `failed_triples` | int | Number of failed triples |+| `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