Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs: Standardize triple_store module with comprehensive algorithms documentation, config, registry, methods, and usage guide

KaifAhmad14d3d58a12a78
diff --git a/semantica/triple_store/__init__.py b/semantica/triple_store/__init__.py
index 95399524..63272245 100644
--- a/semantica/triple_store/__init__.py
+++ b/semantica/triple_store/__init__.py
@@ -5,6 +5,54 @@ This module provides comprehensive triple store integration and management
for RDF data storage and querying, supporting multiple triple store backends
with unified interfaces.
+Algorithms Used:
+
+Triple 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
+
+Bulk Loading:
+ - Batch Processing: Chunking algorithm (fixed-size batch creation), batch size optimization, memory management for large datasets
+ - Progress Tracking: Load progress calculation (loaded/total percentage), elapsed time tracking, estimated remaining time calculation (linear projection), throughput calculation (triples/second)
+ - Retry Mechanism: Exponential backoff retry (delay = retry_delay * (attempt + 1)), max retry limit, error recovery, stop-on-error option
+ - Stream Processing: Iterator-based stream processing, incremental batch collection, memory-efficient loading
+ - Validation: Pre-load validation (empty component checking, URI validation, confidence checking), error/warning collection
+
+SPARQL Query Execution:
+ - Query Validation: Syntax validation (keyword checking, structure validation), query type detection (SELECT, ASK, CONSTRUCT, DESCRIBE, INSERT, DELETE)
+ - Query Optimization: Whitespace normalization, LIMIT addition for SELECT queries, query rewriting, cost estimation
+ - Query Planning: Execution step identification (SELECT projection, pattern matching, filtering, sorting, pagination), cost estimation (heuristic-based: COUNT multiplier, join count multiplier, DISTINCT multiplier)
+ - Query Caching: Cache key generation (MD5 hash of normalized query), LRU-style cache eviction (oldest entry removal when cache full), cache hit/miss tracking, cache invalidation
+ - Result Processing: Binding extraction, variable extraction, result formatting, metadata attachment
+
+Query Optimization:
+ - Cost Estimation: Heuristic-based cost calculation (base cost * complexity multipliers), COUNT query detection (2x multiplier), join count estimation (1 + join_count * 0.1 multiplier), DISTINCT detection (1.5x multiplier)
+ - Execution Step Identification: Query parsing for step detection, step sequence construction, optimization opportunity detection
+ - Query Rewriting: Whitespace normalization, LIMIT injection, query simplification
+
+Store Adapters:
+ - Blazegraph Adapter: HTTP-based SPARQL endpoint communication, namespace management, graph management, bulk load via INSERT DATA, authentication handling
+ - Jena Adapter: rdflib integration, SPARQLStore for remote endpoints, in-memory graph support, model/dataset management, RDF serialization (Turtle, RDF/XML, N3), inference support
+ - RDF4J Adapter: RDF4J repository connection, SPARQL endpoint communication, transaction support, bulk operations
+ - Virtuoso Adapter: Virtuoso SPARQL endpoint communication, SQL/SPARQL hybrid queries, bulk loading, transaction support
+
+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
+ - Query Caching: Result caching for repeated queries, cache size management, cache hit optimization
+ - Parallel Processing: Batch-level parallelization (when supported by adapter), concurrent batch processing
+
Key Features:
- Multi-backend support (Blazegraph, Jena, RDF4J, Virtuoso)
- CRUD operations for RDF triples
@@ -13,6 +61,8 @@ Key Features:
- Query caching and optimization
- Transaction support
- Store adapter pattern
+ - Method registry for extensibility
+ - Configuration management with environment variables and config files
Main Classes:
- TripleManager: Main triple store management coordinator
@@ -27,8 +77,25 @@ Main Classes:
- 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
+ - 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
+
Example Usage:
- >>> from semantica.triple_store import TripleManager
+ >>> from semantica.triple_store import TripleManager, 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()
>>> store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
>>> result = manager.add_triple(triple, store_id="main")
@@ -65,6 +132,29 @@ from .bulk_loader import (
BulkLoader,
LoadProgress
)
+from .methods import (
+ register_store,
+ add_triple,
+ add_triples,
+ get_triples,
+ delete_triple,
+ update_triple,
+ execute_query,
+ optimize_query,
+ plan_query,
+ bulk_load,
+ validate_triples,
+ get_triple_store_method,
+ list_available_methods,
+)
+from .config import (
+ TripleStoreConfig,
+ triple_store_config,
+)
+from .registry import (
+ MethodRegistry,
+ method_registry,
+)
__all__ = [
# Triple management
@@ -85,4 +175,25 @@ __all__ = [
# Bulk loading
"BulkLoader",
"LoadProgress",
+
+ # Convenience functions
+ "register_store",
+ "add_triple",
+ "add_triples",
+ "get_triples",
+ "delete_triple",
+ "update_triple",
+ "execute_query",
+ "optimize_query",
+ "plan_query",
+ "bulk_load",
+ "validate_triples",
+ "get_triple_store_method",
+ "list_available_methods",
+
+ # Configuration and registry
+ "TripleStoreConfig",
+ "triple_store_config",
+ "MethodRegistry",
+ "method_registry",
]
diff --git a/semantica/triple_store/config.py b/semantica/triple_store/config.py
new file mode 100644
index 00000000..92b101cf
--- /dev/null
+++ b/semantica/triple_store/config.py
@@ -0,0 +1,230 @@
+"""
+Configuration Management Module for Triple Store
+
+This module provides centralized configuration management for triple 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.
+ - Config files: YAML, JSON, TOML formats
+ - Programmatic: Python API for setting triple store configurations
+
+Algorithms Used:
+ - Environment Variable Parsing: OS-level environment variable access
+ - YAML Parsing: YAML parser for configuration file loading
+ - JSON Parsing: JSON parser for configuration file loading
+ - TOML Parsing: TOML parser for configuration file loading
+ - Fallback Chain: Priority-based configuration resolution
+ - Dictionary Merging: Deep merge algorithms for configuration updates
+
+Key Features:
+ - Environment variable support for triple store parameters
+ - Config file support (YAML, JSON, TOML formats)
+ - Programmatic configuration via Python API
+ - Method-specific configuration management
+ - Automatic fallback chain (config file -> environment -> defaults)
+ - Global config instance for easy access
+
+Main Classes:
+ - TripleStoreConfig: Main configuration manager class for triple 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")
+"""
+
+import os
+from typing import Optional, Dict, Any
+from pathlib import Path
+
+from ..utils.logging import get_logger
+
+
+class TripleStoreConfig:
+ """Configuration manager for triple store module - supports .env files, environment variables, and programmatic config."""
+
+ def __init__(self, config_file: Optional[str] = None):
+ """
+ Initialize configuration manager.
+
+ Args:
+ config_file: Optional path to configuration file (YAML, JSON, or TOML)
+ """
+ self.logger = get_logger("triple_store_config")
+ self.config_file = config_file
+ self._config: Dict[str, Any] = {}
+ self._method_configs: Dict[str, Dict[str, Any]] = {}
+
+ # Load configuration
+ self._load_config()
+
+ def _load_config(self) -> None:
+ """Load configuration from file, environment variables, and defaults."""
+ # Load from config file if provided
+ if self.config_file:
+ self._load_from_file(self.config_file)
+
+ # Load from environment variables
+ self._load_from_env()
+
+ # Set defaults
+ self._set_defaults()
+
+ def _load_from_file(self, file_path: str) -> None:
+ """Load configuration from file."""
+ file_path = Path(file_path)
+ if not file_path.exists():
+ self.logger.warning(f"Config file not found: {file_path}")
+ return
+
+ try:
+ if file_path.suffix in ['.yaml', '.yml']:
+ import yaml
+ 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'])
+ 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'])
+ 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'])
+ 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',
+ }
+
+ for env_var, config_key in env_mappings.items():
+ value = os.getenv(env_var)
+ if value is not None:
+ # Convert string values to appropriate types
+ if config_key in ['batch_size', 'cache_size', 'max_retries', 'timeout']:
+ try:
+ self._config[config_key] = int(value)
+ except ValueError:
+ self.logger.warning(f"Invalid integer value for {env_var}: {value}")
+ elif config_key in ['enable_caching', 'enable_optimization']:
+ self._config[config_key] = value.lower() in ['true', '1', 'yes', 'on']
+ elif config_key == 'retry_delay':
+ try:
+ self._config[config_key] = float(value)
+ except ValueError:
+ self.logger.warning(f"Invalid float value for {env_var}: {value}")
+ else:
+ self._config[config_key] = value
+
+ def _set_defaults(self) -> None:
+ """Set default configuration values."""
+ defaults = {
+ 'default_store': None,
+ 'batch_size': 1000,
+ 'enable_caching': True,
+ 'cache_size': 1000,
+ 'enable_optimization': True,
+ 'max_retries': 3,
+ 'retry_delay': 1.0,
+ 'timeout': 30,
+ }
+
+ for key, default_value in defaults.items():
+ if key not in self._config:
+ self._config[key] = default_value
+
+ def get(self, key: str, default: Any = None) -> Any:
+ """
+ Get configuration value.
+
+ Args:
+ key: Configuration key
+ default: Default value if key not found
+
+ Returns:
+ Configuration value or default
+ """
+ return self._config.get(key, default)
+
+ def set(self, key: str, value: Any) -> None:
+ """
+ Set configuration value.
+
+ Args:
+ key: Configuration key
+ value: Configuration value
+ """
+ self._config[key] = value
+
+ def update(self, config: Dict[str, Any]) -> None:
+ """
+ Update configuration with dictionary.
+
+ Args:
+ config: Configuration dictionary
+ """
+ self._config.update(config)
+
+ def get_method_config(self, method_name: str) -> Dict[str, Any]:
+ """
+ Get method-specific configuration.
+
+ Args:
+ method_name: Method name
+
+ Returns:
+ Method configuration dictionary
+ """
+ return self._method_configs.get(method_name, {}).copy()
+
+ def set_method_config(self, method_name: str, config: Dict[str, Any]) -> None:
+ """
+ Set method-specific configuration.
+
+ Args:
+ method_name: Method name
+ config: Method configuration dictionary
+ """
+ self._method_configs[method_name] = config.copy()
+
+ def get_all(self) -> Dict[str, Any]:
+ """
+ Get all configuration.
+
+ Returns:
+ Complete configuration dictionary
+ """
+ return self._config.copy()
+
+ def reset(self) -> None:
+ """Reset configuration to defaults."""
+ self._config.clear()
+ self._method_configs.clear()
+ self._set_defaults()
+
+
+# Global configuration instance
+triple_store_config = TripleStoreConfig()
+
diff --git a/semantica/triple_store/methods.py b/semantica/triple_store/methods.py
new file mode 100644
index 00000000..12901e11
--- /dev/null
+++ b/semantica/triple_store/methods.py
@@ -0,0 +1,476 @@
+"""
+Triple 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
+multiple approaches and integrates with the method registry for extensibility.
+
+Supported Methods:
+
+Store Registration:
+ - "default": Default store registration using TripleManager
+ - "blazegraph": Blazegraph-specific registration
+ - "jena": Jena-specific registration
+ - "rdf4j": RDF4J-specific registration
+ - "virtuoso": Virtuoso-specific registration
+
+Triple Addition:
+ - "default": Default triple addition
+ - "single": Single triple addition
+ - "batch": Batch triple addition
+ - "bulk": Bulk triple addition
+
+Triple Retrieval:
+ - "default": Default triple retrieval
+ - "pattern": Pattern-based retrieval
+ - "sparql": SPARQL-based retrieval
+
+Triple Deletion:
+ - "default": Default triple deletion
+ - "single": Single triple deletion
+ - "batch": Batch triple deletion
+
+Triple Update:
+ - "default": Default triple update (delete-then-add)
+ - "atomic": Atomic update (when supported)
+
+SPARQL Query:
+ - "default": Default SPARQL query execution
+ - "optimized": Optimized query execution
+ - "cached": Cached query execution
+
+Query Optimization:
+ - "default": Default query optimization
+ - "basic": Basic optimization (whitespace, LIMIT)
+ - "advanced": Advanced optimization (cost-based)
+
+Bulk Loading:
+ - "default": Default bulk loading
+ - "batch": Batch-based bulk loading
+ - "stream": Stream-based bulk loading
+
+Validation:
+ - "default": Default validation
+ - "triple": Triple structure validation
+ - "pre_load": Pre-load validation
+
+Algorithms Used:
+
+Store Registration:
+ - Store Type Detection: Backend type identification, adapter factory pattern
+ - Configuration Management: Store configuration storage, default store selection
+ - Adapter Instantiation: Backend-specific adapter creation, connection initialization
+
+Triple Operations:
+ - Triple Validation: Required field checking, confidence validation, URI validation
+ - Batch Processing: Chunking algorithm, batch size optimization
+ - Pattern Matching: Subject/predicate/object filtering, SPARQL query construction
+
+SPARQL Query:
+ - Query Validation: Syntax checking, query type detection
+ - Query Optimization: Whitespace normalization, LIMIT injection, cost estimation
+ - Query Caching: MD5-based cache key generation, LRU-style eviction
+ - Result Processing: Binding extraction, variable extraction
+
+Bulk Loading:
+ - Progress Tracking: Load percentage calculation, elapsed time tracking, throughput calculation
+ - Retry Mechanism: Exponential backoff, max retry limit
+ - Stream Processing: Iterator-based processing, incremental batch collection
+
+Key Features:
+ - Multiple triple store operation methods
+ - Store registration with method dispatch
+ - Method dispatchers with registry support
+ - Custom method registration capability
+ - Consistent interface across all methods
+
+Main Functions:
+ - register_store: Store registration wrapper
+ - add_triple: Triple addition wrapper
+ - add_triples: Multiple triple addition wrapper
+ - get_triples: Triple retrieval wrapper
+ - delete_triple: Triple deletion wrapper
+ - update_triple: Triple update wrapper
+ - execute_query: SPARQL query execution wrapper
+ - 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
+ - list_available_methods: List registered methods
+
+Example Usage:
+ >>> from semantica.triple_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")
+"""
+
+from typing import Any, Dict, List, Optional, Union
+from ..semantic_extract.triple_extractor import Triple
+from .triple_manager import TripleManager, TripleStore
+from .query_engine import QueryEngine, QueryResult, QueryPlan
+from .bulk_loader import BulkLoader, LoadProgress
+from .registry import method_registry
+from .config import triple_store_config
+
+# Global manager instances
+_global_manager: Optional[TripleManager] = None
+_global_query_engine: Optional[QueryEngine] = None
+_global_bulk_loader: Optional[BulkLoader] = None
+
+
+def _get_manager() -> TripleManager:
+ """Get or create global TripleManager instance."""
+ global _global_manager
+ if _global_manager is None:
+ config = triple_store_config.get_all()
+ _global_manager = TripleManager(config=config)
+ return _global_manager
+
+
+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()
+ _global_query_engine = QueryEngine(config=config)
+ return _global_query_engine
+
+
+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()
+ _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:
+ """
+ Register a triple store.
+
+ Args:
+ store_id: Store identifier
+ store_type: Store type (blazegraph, jena, rdf4j, virtuoso)
+ endpoint: Store endpoint URL
+ method: Registration method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Registered store
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("register", method)
+ if custom_method:
+ return custom_method(store_id, store_type, endpoint, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.register_store(store_id, store_type, endpoint, **options)
+
+
+def add_triple(
+ triple: Triple,
+ store_id: Optional[str] = None,
+ method: str = "default",
+ **options
+) -> Dict[str, Any]:
+ """
+ Add single triple to store.
+
+ Args:
+ triple: Triple to add
+ store_id: Store identifier (uses default if not provided)
+ method: Addition method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Operation result
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("add", method)
+ if custom_method:
+ return custom_method(triple, store_id=store_id, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.add_triple(triple, store_id=store_id, **options)
+
+
+def add_triples(
+ triples: List[Triple],
+ store_id: Optional[str] = None,
+ method: str = "default",
+ **options
+) -> Dict[str, Any]:
+ """
+ Add multiple triples to store.
+
+ Args:
+ triples: List of triples to add
+ store_id: Store identifier
+ method: Addition method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Operation result
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("add", method)
+ if custom_method:
+ return custom_method(triples, store_id=store_id, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.add_triples(triples, store_id=store_id, **options)
+
+
+def get_triples(
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ store_id: Optional[str] = None,
+ method: str = "default",
+ **options
+) -> List[Triple]:
+ """
+ Get triples matching criteria.
+
+ Args:
+ subject: Optional subject URI
+ predicate: Optional predicate URI
+ object: Optional object URI
+ store_id: Store identifier
+ method: Retrieval method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ List of matching triples
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("get", method)
+ if custom_method:
+ return custom_method(subject, predicate, object, store_id=store_id, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.get_triple(subject, predicate, object, store_id=store_id, **options)
+
+
+def delete_triple(
+ triple: Triple,
+ store_id: Optional[str] = None,
+ method: str = "default",
+ **options
+) -> Dict[str, Any]:
+ """
+ Delete triple from store.
+
+ Args:
+ triple: Triple to delete
+ store_id: Store identifier
+ method: Deletion method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Operation result
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("delete", method)
+ if custom_method:
+ return custom_method(triple, store_id=store_id, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.delete_triple(triple, store_id=store_id, **options)
+
+
+def update_triple(
+ old_triple: Triple,
+ new_triple: Triple,
+ store_id: Optional[str] = None,
+ method: str = "default",
+ **options
+) -> Dict[str, Any]:
+ """
+ Update triple in store.
+
+ Args:
+ old_triple: Original triple
+ new_triple: Updated triple
+ store_id: Store identifier
+ method: Update method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Operation result
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("update", method)
+ if custom_method:
+ return custom_method(old_triple, new_triple, store_id=store_id, **options)
+
+ # Default implementation
+ manager = _get_manager()
+ return manager.update_triple(old_triple, new_triple, store_id=store_id, **options)
+
+
+def execute_query(
+ query: str,
+ store_adapter: Any,
+ method: str = "default",
+ **options
+) -> QueryResult:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ store_adapter: Triple store adapter instance
+ method: Query method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Query result
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("query", method)
+ if custom_method:
+ return custom_method(query, store_adapter, **options)
+
+ # Default implementation
+ engine = _get_query_engine()
+ return engine.execute_query(query, store_adapter, **options)
+
+
+def optimize_query(
+ query: str,
+ method: str = "default",
+ **options
+) -> str:
+ """
+ Optimize SPARQL query.
+
+ Args:
+ query: Original SPARQL query
+ method: Optimization method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Optimized query
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("optimize", method)
+ if custom_method:
+ return custom_method(query, **options)
+
+ # Default implementation
+ engine = _get_query_engine()
+ return engine.optimize_query(query, **options)
+
+
+def plan_query(
+ query: str,
+ **options
+) -> QueryPlan:
+ """
+ Create query execution plan.
+
+ Args:
+ query: SPARQL query
+ **options: Planning options
+
+ Returns:
+ Query execution plan
+ """
+ engine = _get_query_engine()
+ return engine.plan_query(query, **options)
+
+
+def bulk_load(
+ triples: List[Triple],
+ store_adapter: Any,
+ method: str = "default",
+ **options
+) -> LoadProgress:
+ """
+ Load triples in bulk.
+
+ Args:
+ triples: List of triples to load
+ store_adapter: Triple store adapter instance
+ method: Loading method name (default: "default")
+ **options: Additional options
+
+ Returns:
+ Load progress information
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("bulk_load", method)
+ if custom_method:
+ return custom_method(triples, store_adapter, **options)
+
+ # Default implementation
+ loader = _get_bulk_loader()
+ return loader.load_triples(triples, store_adapter, **options)
+
+
+def validate_triples(
+ triples: List[Triple],
+ method: str = "default",
+ **options
+) -> Dict[str, Any]:
+ """
+ Validate triples before loading.
+
+ Args:
+ triples: List of triples to validate
+ method: Validation method name (default: "default")
+ **options: Validation options
+
+ Returns:
+ Validation results
+ """
+ # Check registry for custom method
+ custom_method = method_registry.get("validate", method)
+ if custom_method:
+ return custom_method(triples, **options)
+
+ # Default implementation
+ loader = _get_bulk_loader()
+ return loader.validate_before_load(triples, **options)
+
+
+def get_triple_store_method(task: str, method_name: str) -> Optional[Any]:
+ """
+ Get triple store method by task and name.
+
+ Args:
+ task: Task type (register, add, get, delete, update, query, optimize, bulk_load, validate)
+ method_name: Method name
+
+ Returns:
+ Method function or None if not found
+ """
+ return method_registry.get(task, method_name)
+
+
+def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
+ """
+ List all available triple store methods.
+
+ Args:
+ task: Optional task type to filter by
+
+ Returns:
+ Dictionary mapping task types to lists of method names
+ """
+ return method_registry.list_all(task)
+
diff --git a/semantica/triple_store/registry.py b/semantica/triple_store/registry.py
new file mode 100644
index 00000000..fd624f5e
--- /dev/null
+++ b/semantica/triple_store/registry.py
@@ -0,0 +1,166 @@
+"""
+Method Registry Module for Triple Store
+
+This module provides a method registry system for registering custom triple store methods,
+enabling extensibility and community contributions to the triple store toolkit.
+
+Supported Registration Types:
+ - Method Registry: Register custom triple store methods for:
+ * "register": Store registration methods
+ * "add": Triple addition methods
+ * "get": Triple retrieval methods
+ * "delete": Triple deletion methods
+ * "update": Triple update methods
+ * "query": SPARQL query execution methods
+ * "optimize": Query optimization methods
+ * "bulk_load": Bulk loading methods
+ * "validate": Validation methods
+
+Algorithms Used:
+ - Registry Pattern: Dictionary-based registration and lookup
+ - Dynamic Registration: Runtime function registration
+ - Type Checking: Type validation for registered components
+ - Lookup Algorithms: Hash-based O(1) lookup for methods
+ - Task-based Organization: Hierarchical organization by task type
+
+Key Features:
+ - Method registry for custom triple 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
+
+Global Instances:
+ - method_registry: Global method registry instance
+
+Example Usage:
+ >>> from semantica.triple_store.registry import method_registry
+ >>> method_registry.register("add", "custom_method", custom_add_function)
+ >>> available = method_registry.list_all("add")
+"""
+
+from typing import Dict, Callable, Any, List, Optional
+
+
+class MethodRegistry:
+ """Registry for custom triple store methods."""
+
+ def __init__(self):
+ """Initialize method registry."""
+ self._registry: Dict[str, Dict[str, Callable]] = {
+ "register": {},
+ "add": {},
+ "get": {},
+ "delete": {},
+ "update": {},
+ "query": {},
+ "optimize": {},
+ "bulk_load": {},
+ "validate": {},
+ }
+
+ def register(
+ self,
+ task: str,
+ method_name: str,
+ method_func: Callable,
+ **metadata
+ ) -> None:
+ """
+ Register a method for a specific task.
+
+ Args:
+ task: Task type (register, add, get, delete, update, query, optimize, bulk_load, validate)
+ method_name: Name of the method
+ method_func: Method function to register
+ **metadata: Additional metadata for the method
+ """
+ if task not in self._registry:
+ raise ValueError(f"Unknown task type: {task}")
+
+ if not callable(method_func):
+ raise ValueError("method_func must be callable")
+
+ # Store method with metadata
+ method_func._registry_metadata = metadata
+ self._registry[task][method_name] = method_func
+
+ def unregister(self, task: str, method_name: str) -> None:
+ """
+ Unregister a method.
+
+ Args:
+ task: Task type
+ method_name: Name of the method to unregister
+ """
+ if task in self._registry and method_name in self._registry[task]:
+ del self._registry[task][method_name]
+
+ def get(self, task: str, method_name: str) -> Optional[Callable]:
+ """
+ Get a registered method.
+
+ Args:
+ task: Task type
+ method_name: Name of the method
+
+ Returns:
+ Method function or None if not found
+ """
+ if task not in self._registry:
+ return None
+ return self._registry[task].get(method_name)
+
+ def list_all(self, task: Optional[str] = None) -> Dict[str, List[str]]:
+ """
+ List all registered methods.
+
+ Args:
+ task: Optional task type to filter by
+
+ Returns:
+ Dictionary mapping task types to lists of method names
+ """
+ if task:
+ if task in self._registry:
+ return {task: list(self._registry[task].keys())}
+ return {}
+
+ return {task: list(methods.keys()) for task, methods in self._registry.items()}
+
+ def has(self, task: str, method_name: str) -> bool:
+ """
+ Check if a method is registered.
+
+ Args:
+ task: Task type
+ method_name: Name of the method
+
+ Returns:
+ True if method is registered, False otherwise
+ """
+ return task in self._registry and method_name in self._registry[task]
+
+ def get_metadata(self, task: str, method_name: str) -> Dict[str, Any]:
+ """
+ Get metadata for a registered method.
+
+ Args:
+ task: Task type
+ method_name: Name of the method
+
+ Returns:
+ Method metadata dictionary
+ """
+ method = self.get(task, method_name)
+ if method and hasattr(method, '_registry_metadata'):
+ return method._registry_metadata.copy()
+ return {}
+
+
+# Global method registry instance
+method_registry = MethodRegistry()
+
diff --git a/semantica/triple_store/triple_store_usage.md b/semantica/triple_store/triple_store_usage.md
new file mode 100644
index 00000000..662c7d34
--- /dev/null
+++ b/semantica/triple_store/triple_store_usage.md
@@ -0,0 +1,1067 @@
+# Triple 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.
+
+## Table of Contents
+
+1. [Basic Usage](#basic-usage)
+2. [Store Registration](#store-registration)
+3. [CRUD Operations](#crud-operations)
+4. [SPARQL Query Execution](#sparql-query-execution)
+5. [Query Optimization](#query-optimization)
+6. [Bulk Loading](#bulk-loading)
+7. [Store Adapters](#store-adapters)
+8. [Algorithms and Methods](#algorithms-and-methods)
+9. [Configuration](#configuration)
+10. [Advanced Examples](#advanced-examples)
+
+## Basic Usage
+
+### Using TripleManager
+
+```python
+from semantica.triple_store import TripleManager
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create triple manager
+manager = TripleManager()
+
+# Register a store
+store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Add a triple
+triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasName",
+ object="John Doe",
+ confidence=0.9
+)
+result = manager.add_triple(triple, store_id="main")
+
+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.semantic_extract.triple_extractor import Triple
+
+# Register store
+store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Add triple
+triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasName",
+ object="John Doe"
+)
+result = add_triple(triple, store_id="main")
+
+# Get triples
+triples = get_triples(subject="http://example.org/entity1", store_id="main")
+print(f"Found {len(triples)} triples")
+```
+
+### Using QueryEngine
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+# Create query engine
+engine = QueryEngine(enable_caching=True, enable_optimization=True)
+
+# Create adapter
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Execute query
+query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
+result = engine.execute_query(query, adapter)
+
+print(f"Found {len(result.bindings)} results")
+print(f"Execution time: {result.execution_time:.2f}s")
+```
+
+## Store Registration
+
+### Registering a Store
+
+```python
+from semantica.triple_store import TripleManager
+
+manager = TripleManager()
+
+# Register Blazegraph store
+blazegraph_store = manager.register_store(
+ store_id="blazegraph",
+ store_type="blazegraph",
+ endpoint="http://localhost:9999/blazegraph",
+ namespace="kb"
+)
+
+# Register Jena store
+jena_store = manager.register_store(
+ store_id="jena",
+ store_type="jena",
+ endpoint="http://localhost:3030/ds",
+ dataset="default"
+)
+
+# Register RDF4J store
+rdf4j_store = manager.register_store(
+ store_id="rdf4j",
+ store_type="rdf4j",
+ endpoint="http://localhost:8080/rdf4j-server",
+ repository="test"
+)
+
+# Register Virtuoso store
+virtuoso_store = manager.register_store(
+ store_id="virtuoso",
+ store_type="virtuoso",
+ endpoint="http://localhost:8890/sparql"
+)
+```
+
+### Using Convenience Function
+
+```python
+from semantica.triple_store import register_store
+
+# Register store using convenience function
+store = register_store(
+ "main",
+ "blazegraph",
+ "http://localhost:9999/blazegraph",
+ method="default"
+)
+
+print(f"Store registered: {store.store_id}")
+print(f"Store type: {store.store_type}")
+```
+
+### Multiple Stores
+
+```python
+from semantica.triple_store import TripleManager
+
+manager = TripleManager()
+
+# Register multiple stores
+manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
+manager.register_store("secondary", "jena", "http://localhost:3030/ds")
+
+# List all stores
+store_ids = manager.list_stores()
+print(f"Registered stores: {store_ids}")
+
+# Get specific store
+store = manager.get_store("primary")
+print(f"Store endpoint: {store.endpoint}")
+```
+
+## CRUD Operations
+
+### Adding Triples
+
+```python
+from semantica.triple_store import TripleManager
+from semantica.semantic_extract.triple_extractor import Triple
+
+manager = TripleManager()
+manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Add single triple
+triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasName",
+ object="John Doe",
+ confidence=0.9
+)
+result = manager.add_triple(triple, store_id="main")
+print(f"Added: {result['success']}")
+
+# Add multiple triples
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasAge", "30"),
+ Triple("http://example.org/entity1", "http://example.org/hasCity", "New York"),
+ Triple("http://example.org/entity2", "http://example.org/hasName", "Jane Smith")
+]
+result = manager.add_triples(triples, store_id="main", batch_size=1000)
+print(f"Added {result['total_triples']} triples in {result['batches']} batches")
+```
+
+### Retrieving Triples
+
+```python
+from semantica.triple_store import TripleManager
+
+manager = TripleManager()
+manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Get all triples for a subject
+triples = manager.get_triple(
+ subject="http://example.org/entity1",
+ store_id="main"
+)
+print(f"Found {len(triples)} triples for entity1")
+
+# Get triples matching predicate
+triples = manager.get_triple(
+ predicate="http://example.org/hasName",
+ store_id="main"
+)
+print(f"Found {len(triples)} triples with hasName predicate")
+
+# Get specific triple
+triples = manager.get_triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasName",
+ object="John Doe",
+ store_id="main"
+)
+```
+
+### Deleting Triples
+
+```python
+from semantica.triple_store import TripleManager
+from semantica.semantic_extract.triple_extractor import Triple
+
+manager = TripleManager()
+manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Delete triple
+triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasName",
+ object="John Doe"
+)
+result = manager.delete_triple(triple, store_id="main")
+print(f"Deleted: {result['success']}")
+```
+
+### Updating Triples
+
+```python
+from semantica.triple_store import TripleManager
+from semantica.semantic_extract.triple_extractor import Triple
+
+manager = TripleManager()
+manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# Update triple (delete old, add new)
+old_triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasAge",
+ object="30"
+)
+new_triple = Triple(
+ subject="http://example.org/entity1",
+ predicate="http://example.org/hasAge",
+ object="31"
+)
+result = manager.update_triple(old_triple, new_triple, store_id="main")
+print(f"Updated: {result['success']}")
+```
+
+## SPARQL Query Execution
+
+### Basic Query Execution
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+# Create query engine
+engine = QueryEngine(enable_caching=True)
+
+# Create adapter
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Execute SELECT query
+query = """
+SELECT ?s ?p ?o
+WHERE {
+ ?s ?p ?o .
+ ?s <http://example.org/hasName> ?o .
+}
+LIMIT 10
+"""
+result = engine.execute_query(query, adapter)
+
+print(f"Variables: {result.variables}")
+print(f"Results: {len(result.bindings)}")
+for binding in result.bindings[:5]:
+ print(binding)
+```
+
+### Using Convenience Function
+
+```python
+from semantica.triple_store import execute_query, BlazegraphAdapter
+
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
+result = execute_query(query, adapter, method="default")
+
+print(f"Found {len(result.bindings)} results")
+```
+
+### Query Result Processing
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+engine = QueryEngine()
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+query = "SELECT ?name ?age WHERE { ?s <http://example.org/hasName> ?name . ?s <http://example.org/hasAge> ?age }"
+result = engine.execute_query(query, adapter)
+
+# Process results
+for binding in result.bindings:
+ name = binding.get("name", {}).get("value", "")
+ age = binding.get("age", {}).get("value", "")
+ print(f"Name: {name}, Age: {age}")
+
+print(f"Execution time: {result.execution_time:.2f}s")
+print(f"Metadata: {result.metadata}")
+```
+
+### Query Caching
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+# Enable caching
+engine = QueryEngine(enable_caching=True, cache_size=1000)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
+
+# First execution (not cached)
+result1 = engine.execute_query(query, adapter)
+print(f"First execution: {result1.execution_time:.2f}s, Cached: {result1.metadata.get('cached', False)}")
+
+# Second execution (cached)
+result2 = engine.execute_query(query, adapter)
+print(f"Second execution: {result2.execution_time:.2f}s, Cached: {result2.metadata.get('cached', False)}")
+
+# Clear cache
+engine.clear_cache()
+```
+
+## Query Optimization
+
+### Basic Query Optimization
+
+```python
+from semantica.triple_store import QueryEngine
+
+engine = QueryEngine(enable_optimization=True)
+
+# Original query
+query = """
+SELECT ?s ?p ?o
+WHERE {
+ ?s ?p ?o .
+}
+"""
+
+# Optimize query
+optimized = engine.optimize_query(query, add_limit=True, default_limit=1000)
+print(f"Optimized query:\n{optimized}")
+```
+
+### Query Planning
+
+```python
+from semantica.triple_store import QueryEngine
+
+engine = QueryEngine(enable_optimization=True)
+
+query = """
+SELECT ?s ?p ?o
+WHERE {
+ ?s ?p ?o .
+ FILTER(?o > 10)
+}
+ORDER BY ?s
+LIMIT 100
+"""
+
+# Create query plan
+plan = engine.plan_query(query)
+
+print(f"Original query: {plan.query}")
+print(f"Optimized query: {plan.optimized_query}")
+print(f"Estimated cost: {plan.estimated_cost}")
+print(f"Execution steps: {plan.execution_steps}")
+```
+
+### Query Statistics
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+engine = QueryEngine(enable_caching=True)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Execute multiple queries
+for i in range(10):
+ query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o }} LIMIT {i * 10}"
+ engine.execute_query(query, adapter)
+
+# Get statistics
+stats = engine.get_query_statistics()
+print(f"Total queries: {stats['total_queries']}")
+print(f"Average execution time: {stats['average_execution_time']:.2f}s")
+print(f"Min execution time: {stats['min_execution_time']:.2f}s")
+print(f"Max execution time: {stats['max_execution_time']:.2f}s")
+print(f"Cache size: {stats['cache_size']}")
+```
+
+## Bulk Loading
+
+### Basic Bulk Loading
+
+```python
+from semantica.triple_store import BulkLoader, BlazegraphAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create bulk loader
+loader = BulkLoader(batch_size=1000, max_retries=3)
+
+# Create adapter
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Generate triples
+triples = [
+ Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+ for i in range(10000)
+]
+
+# Load triples
+progress = loader.load_triples(triples, adapter)
+
+print(f"Loaded: {progress.loaded_triples}/{progress.total_triples}")
+print(f"Failed: {progress.failed_triples}")
+print(f"Progress: {progress.progress_percentage:.1f}%")
+print(f"Elapsed time: {progress.elapsed_time:.2f}s")
+print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec")
+```
+
+### Progress Tracking
+
+```python
+from semantica.triple_store import BulkLoader, BlazegraphAdapter, LoadProgress
+from semantica.semantic_extract.triple_extractor import Triple
+
+loader = BulkLoader(batch_size=1000)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Progress callback
+def progress_callback(progress: LoadProgress):
+ print(f"Batch {progress.current_batch}/{progress.total_batches}: "
+ f"{progress.progress_percentage:.1f}% "
+ f"({progress.loaded_triples}/{progress.total_triples})")
+
+# Load with progress callback
+triples = [Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+ for i in range(5000)]
+progress = loader.load_triples(triples, adapter, progress_callback=progress_callback)
+```
+
+### Pre-load Validation
+
+```python
+from semantica.triple_store import BulkLoader
+from semantica.semantic_extract.triple_extractor import Triple
+
+loader = BulkLoader()
+
+# Create triples (some invalid)
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasName", "John"), # Valid
+ Triple("", "http://example.org/hasName", "Jane"), # Invalid (empty subject)
+ Triple("http://example.org/entity3", "", "Bob"), # Invalid (empty predicate)
+ Triple("http://example.org/entity4", "http://example.org/hasAge", "30"), # Valid
+]
+
+# Validate before loading
+validation = loader.validate_before_load(triples)
+
+print(f"Valid: {validation['valid']}")
+print(f"Errors: {validation['errors']}")
+print(f"Warnings: {validation['warnings']}")
+print(f"Valid triples: {validation['valid_triples']}/{validation['total_triples']}")
+```
+
+### Stream-based Loading
+
+```python
+from semantica.triple_store import BulkLoader, BlazegraphAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+loader = BulkLoader(batch_size=1000)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Create stream of triples
+def triple_stream():
+ for i in range(10000):
+ yield Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+
+# Load from stream
+progress = loader.load_from_stream(triple_stream(), adapter)
+print(f"Loaded {progress.loaded_triples} triples from stream")
+```
+
+## Store Adapters
+
+### Blazegraph Adapter
+
+```python
+from semantica.triple_store import BlazegraphAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create Blazegraph adapter
+adapter = BlazegraphAdapter(
+ endpoint="http://localhost:9999/blazegraph",
+ namespace="kb",
+ auth=("user", "password") # Optional
+)
+
+# Add triples
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+]
+result = adapter.add_triples(triples)
+print(f"Added: {result['success']}")
+
+# Execute SPARQL query
+query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
+result = adapter.execute_sparql(query)
+print(f"Found {len(result['bindings'])} results")
+```
+
+### Jena Adapter
+
+```python
+from semantica.triple_store import JenaAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create Jena adapter (in-memory)
+adapter = JenaAdapter()
+
+# Or connect to Fuseki endpoint
+adapter = JenaAdapter(
+ endpoint="http://localhost:3030/ds",
+ dataset="default",
+ enable_inference=True
+)
+
+# Add triples
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+]
+result = adapter.add_triples(triples)
+
+# Serialize to Turtle
+turtle = adapter.serialize(format="turtle")
+print(turtle)
+```
+
+### RDF4J Adapter
+
+```python
+from semantica.triple_store import RDF4JAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create RDF4J adapter
+adapter = RDF4JAdapter(
+ endpoint="http://localhost:8080/rdf4j-server",
+ repository="test"
+)
+
+# Add triples
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+]
+result = adapter.add_triples(triples)
+```
+
+### Virtuoso Adapter
+
+```python
+from semantica.triple_store import VirtuosoAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+# Create Virtuoso adapter
+adapter = VirtuosoAdapter(
+ endpoint="http://localhost:8890/sparql",
+ user="dba",
+ password="dba"
+)
+
+# Add triples
+triples = [
+ Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+]
+result = adapter.add_triples(triples)
+```
+
+## Algorithms and Methods
+
+### Triple Store Management Algorithms
+
+#### Store Registration
+**Algorithm**: Store type detection and adapter factory pattern
+
+1. **Store Type Detection**: Identify backend type (blazegraph, jena, rdf4j, virtuoso)
+2. **Configuration Storage**: Store store configuration (endpoint, namespace, etc.)
+3. **Adapter Factory**: Create appropriate adapter instance based on store type
+4. **Default Store Selection**: Set first registered store as default if none specified
+
+**Time Complexity**: O(1) for registration
+**Space Complexity**: O(1) per store
+
+```python
+# Store registration
+store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+```
+
+#### Adapter Pattern
+**Algorithm**: Unified interface for multiple backends
+
+1. **Interface Definition**: Common interface for all adapters (add_triple, execute_sparql, etc.)
+2. **Backend-Specific Implementation**: Each adapter implements interface for its backend
+3. **Adapter Instantiation**: Create adapter instance on-demand
+4. **Operation Delegation**: Delegate operations to appropriate adapter
+
+**Time Complexity**: O(1) for adapter creation
+**Space Complexity**: O(1) per adapter
+
+### CRUD Operations Algorithms
+
+#### Triple Addition
+**Algorithm**: Single and batch triple insertion
+
+1. **Triple Validation**: Check required fields (subject, predicate, object), validate confidence (0-1)
+2. **Adapter Selection**: Get adapter for specified store
+3. **Operation Delegation**: Delegate to adapter's add_triple/add_triples method
+4. **Result Processing**: Process and return operation result
+
+**Time Complexity**: O(1) for single, O(n) for batch where n = triples
+**Space Complexity**: O(1) for single, O(n) for batch
+
+```python
+# Triple addition
+result = manager.add_triple(triple, store_id="main")
+result = manager.add_triples(triples, store_id="main", batch_size=1000)
+```
+
+#### Triple Retrieval
+**Algorithm**: Pattern-based triple retrieval
+
+1. **Pattern Construction**: Build SPARQL query from subject/predicate/object patterns
+2. **Query Execution**: Execute SPARQL query via adapter
+3. **Result Binding Extraction**: Extract bindings from query result
+4. **Triple Reconstruction**: Convert bindings to Triple objects
+
+**Time Complexity**: O(n) where n = result count
+**Space Complexity**: O(n) for results
+
+```python
+# Triple retrieval
+triples = manager.get_triple(subject="http://example.org/entity1", store_id="main")
+```
+
+### Bulk Loading Algorithms
+
+#### Batch Processing
+**Algorithm**: Chunking algorithm for large datasets
+
+1. **Batch Creation**: Divide triples into fixed-size batches
+2. **Batch Processing**: Process each batch sequentially
+3. **Progress Tracking**: Track loaded count, failed count, progress percentage
+4. **Error Handling**: Retry failed batches with exponential backoff
+
+**Time Complexity**: O(n) where n = total triples
+**Space Complexity**: O(b) where b = batch size
+
+```python
+# Batch processing
+progress = loader.load_triples(triples, adapter, batch_size=1000)
+```
+
+#### Progress Tracking
+**Algorithm**: Load progress calculation
+
+1. **Progress Calculation**: loaded_triples / total_triples * 100
+2. **Elapsed Time Tracking**: Track time since start
+3. **Estimated Remaining**: (elapsed / loaded) * (total - loaded)
+4. **Throughput Calculation**: loaded_triples / elapsed_time
+
+**Time Complexity**: O(1) per update
+**Space Complexity**: O(1)
+
+#### Retry Mechanism
+**Algorithm**: Exponential backoff retry
+
+1. **Retry Attempt**: Try batch load operation
+2. **Failure Detection**: Catch exceptions
+3. **Backoff Calculation**: delay = retry_delay * (attempt + 1)
+4. **Max Retry Check**: Stop after max_retries attempts
+
+**Time Complexity**: O(r) where r = max_retries
+**Space Complexity**: O(1)
+
+### SPARQL Query Execution Algorithms
+
+#### Query Validation
+**Algorithm**: Syntax validation and query type detection
+
+1. **Keyword Checking**: Check for valid SPARQL keywords (SELECT, ASK, CONSTRUCT, etc.)
+2. **Structure Validation**: Validate query structure
+3. **Query Type Detection**: Identify query type (SELECT, ASK, CONSTRUCT, DESCRIBE, INSERT, DELETE)
+
+**Time Complexity**: O(n) where n = query length
+**Space Complexity**: O(1)
+
+```python
+# Query validation
+is_valid = engine._validate_query(query)
+```
+
+#### Query Optimization
+**Algorithm**: Basic query optimization
+
+1. **Whitespace Normalization**: Remove unnecessary whitespace
+2. **LIMIT Injection**: Add LIMIT clause if SELECT query doesn't have one
+3. **Query Rewriting**: Simplify query structure
+
+**Time Complexity**: O(n) where n = query length
+**Space Complexity**: O(n) for optimized query
+
+```python
+# Query optimization
+optimized = engine.optimize_query(query, add_limit=True, default_limit=1000)
+```
+
+#### Query Caching
+**Algorithm**: MD5-based cache key generation and LRU-style eviction
+
+1. **Cache Key Generation**: MD5 hash of normalized query
+2. **Cache Lookup**: Check if query result is cached
+3. **Cache Storage**: Store query result with cache key
+4. **Cache Eviction**: Remove oldest entry when cache is full
+
+**Time Complexity**: O(1) for lookup/storage
+**Space Complexity**: O(c) where c = cache size
+
+```python
+# Query caching
+result = engine.execute_query(query, adapter) # Cached on second call
+```
+
+#### Cost Estimation
+**Algorithm**: Heuristic-based cost calculation
+
+1. **Base Cost**: Start with base cost of 1.0
+2. **COUNT Detection**: Multiply by 2.0 if COUNT query
+3. **Join Count**: Multiply by (1.0 + join_count * 0.1)
+4. **DISTINCT Detection**: Multiply by 1.5 if DISTINCT
+
+**Time Complexity**: O(n) where n = query length
+**Space Complexity**: O(1)
+
+```python
+# Cost estimation
+cost = engine._estimate_query_cost(query)
+```
+
+### Methods
+
+#### TripleManager Methods
+
+- `register_store(store_id, store_type, endpoint, **config)`: Register triple 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
+- `delete_triple(triple, store_id, **options)`: Delete triple
+- `update_triple(old_triple, new_triple, store_id, **options)`: Update triple
+- `get_store(store_id)`: Get store by ID
+- `list_stores()`: List all store IDs
+
+#### QueryEngine Methods
+
+- `execute_query(query, store_adapter, **options)`: Execute SPARQL query
+- `optimize_query(query, **options)`: Optimize SPARQL query
+- `plan_query(query, **options)`: Create query execution plan
+- `clear_cache()`: Clear query cache
+- `get_query_statistics()`: Get query execution statistics
+
+#### BulkLoader Methods
+
+- `load_triples(triples, store_adapter, **options)`: Load triples in bulk
+- `load_from_file(file_path, store_adapter, **options)`: Load triples from file
+- `load_from_stream(triples_stream, store_adapter, **options)`: Load triples from stream
+- `validate_before_load(triples, **options)`: Validate triples before loading
+
+#### Convenience Functions
+
+- `register_store(store_id, store_type, endpoint, method, **options)`: Register store wrapper
+- `add_triple(triple, store_id, method, **options)`: Add triple wrapper
+- `add_triples(triples, store_id, method, **options)`: Add triples wrapper
+- `get_triples(subject, predicate, object, store_id, method, **options)`: Get triples wrapper
+- `delete_triple(triple, store_id, method, **options)`: Delete triple wrapper
+- `update_triple(old_triple, new_triple, store_id, method, **options)`: Update triple wrapper
+- `execute_query(query, store_adapter, method, **options)`: Execute query wrapper
+- `optimize_query(query, method, **options)`: Optimize query wrapper
+- `bulk_load(triples, store_adapter, method, **options)`: Bulk load wrapper
+- `validate_triples(triples, method, **options)`: Validate triples wrapper
+
+## Configuration
+
+### 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
+
+# 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
+```
+
+### Programmatic Configuration
+
+```python
+from semantica.triple_store.config import triple_store_config
+
+# Get configuration
+batch_size = triple_store_config.get("batch_size", default=1000)
+enable_caching = triple_store_config.get("enable_caching", default=True)
+
+# Set configuration
+triple_store_config.set("batch_size", 2000)
+triple_store_config.set("enable_caching", False)
+
+# Update with dictionary
+triple_store_config.update({
+ "batch_size": 2000,
+ "enable_caching": True,
+ "cache_size": 2000
+})
+```
+
+### Configuration File (YAML)
+
+```yaml
+# config.yaml
+triple_store:
+ default_store: main
+ batch_size: 1000
+ enable_caching: true
+ cache_size: 1000
+ enable_optimization: true
+ max_retries: 3
+ retry_delay: 1.0
+ timeout: 30
+ blazegraph_endpoint: http://localhost:9999/blazegraph
+ jena_endpoint: http://localhost:3030/ds
+ rdf4j_endpoint: http://localhost:8080/rdf4j-server
+ virtuoso_endpoint: http://localhost:8890/sparql
+```
+
+## Advanced Examples
+
+### Complete Triple Store Pipeline
+
+```python
+from semantica.triple_store import (
+ TripleManager,
+ QueryEngine,
+ BulkLoader,
+ register_store,
+ add_triples,
+ execute_query
+)
+from semantica.semantic_extract.triple_extractor import Triple
+
+# 1. Register store
+store = register_store("main", "blazegraph", "http://localhost:9999/blazegraph")
+
+# 2. Generate and add triples
+triples = [
+ Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+ for i in range(1000)
+]
+result = add_triples(triples, store_id="main", batch_size=100)
+
+# 3. Execute queries
+from semantica.triple_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)
+
+print(f"Added {result['total_triples']} triples")
+print(f"Query returned {len(query_result.bindings)} results")
+```
+
+### Multi-Store Operations
+
+```python
+from semantica.triple_store import TripleManager
+from semantica.semantic_extract.triple_extractor import Triple
+
+manager = TripleManager()
+
+# Register multiple stores
+manager.register_store("primary", "blazegraph", "http://localhost:9999/blazegraph")
+manager.register_store("backup", "jena", "http://localhost:3030/ds")
+
+# Add to primary store
+triple = Triple("http://example.org/entity1", "http://example.org/hasName", "John")
+manager.add_triple(triple, store_id="primary")
+
+# Replicate to backup store
+manager.add_triple(triple, store_id="backup")
+```
+
+### Query Optimization Workflow
+
+```python
+from semantica.triple_store import QueryEngine, BlazegraphAdapter
+
+engine = QueryEngine(enable_optimization=True, enable_caching=True)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Original query
+query = """
+SELECT ?s ?p ?o
+WHERE {
+ ?s ?p ?o .
+ FILTER(?o > 10)
+}
+"""
+
+# Plan query
+plan = engine.plan_query(query)
+print(f"Estimated cost: {plan.estimated_cost}")
+print(f"Execution steps: {plan.execution_steps}")
+
+# Execute optimized query
+result = engine.execute_query(query, adapter)
+print(f"Execution time: {result.execution_time:.2f}s")
+print(f"Optimized: {result.metadata.get('optimized', False)}")
+```
+
+### Bulk Loading with Validation
+
+```python
+from semantica.triple_store import BulkLoader, BlazegraphAdapter
+from semantica.semantic_extract.triple_extractor import Triple
+
+loader = BulkLoader(batch_size=1000, max_retries=3)
+adapter = BlazegraphAdapter(endpoint="http://localhost:9999/blazegraph")
+
+# Generate triples
+triples = [
+ Triple(f"http://example.org/entity{i}", "http://example.org/hasName", f"Entity {i}")
+ for i in range(10000)
+]
+
+# Validate before loading
+validation = loader.validate_before_load(triples)
+if validation['valid']:
+ # Load triples
+ progress = loader.load_triples(triples, adapter)
+ print(f"Loaded {progress.loaded_triples}/{progress.total_triples} triples")
+ print(f"Throughput: {progress.metadata.get('throughput', 0):.0f} triples/sec")
+else:
+ print(f"Validation failed: {validation['errors']}")
+```
+
+### Custom Method Registration
+
+```python
+from semantica.triple_store.registry import method_registry
+from semantica.triple_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
+ 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
+result = add_triple(triple, store_id="main", method="custom")
+```
+
+## Best Practices
+
+1. **Store Registration**:
+ - Register stores before use
+ - Use descriptive store IDs
+ - Set appropriate default store
+ - Configure store-specific options
+
+2. **Triple Operations**:
+ - Validate triples before adding
+ - Use batch operations for multiple triples
+ - Set appropriate batch sizes
+ - Handle errors gracefully
+
+3. **Query Execution**:
+ - Enable caching for repeated queries
+ - Use query optimization for complex queries
+ - Monitor query performance
+ - Use appropriate LIMIT clauses
+
+4. **Bulk Loading**:
+ - Validate triples before loading
+ - Use appropriate batch sizes
+ - Monitor progress for large loads
+ - Handle retries appropriately
+
+5. **Performance**:
+ - Use batch operations when possible
+ - Enable query caching
+ - Optimize queries before execution
+ - Monitor query statistics
+
+6. **Error Handling**:
+ - Validate triples before operations
+ - Handle adapter errors gracefully
+ - Use retry mechanisms for bulk operations
+ - Log errors for debugging
+
+7. **Configuration**:
+ - Use environment variables for deployment
+ - Use config files for development
+ - Set appropriate defaults
+ - Document configuration options
+
+8. **Testing**:
+ - Test with sample data first
+ - Validate query results
+ - Test error handling
+ - Monitor performance
+