Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Implement triple_store module - comprehensive RDF triple store integration

KaifAhmad117adcd885b7b
diff --git a/libs/semantica/semantic_extract/__init__.py b/libs/semantica/semantic_extract/__init__.py
index 8aee29cb..f63a2775 100644
--- a/libs/semantica/semantic_extract/__init__.py
+++ b/libs/semantica/semantic_extract/__init__.py
@@ -10,11 +10,125 @@ Exports:
- CoreferenceResolver: Coreference resolution
- TripleExtractor: RDF triple extraction
- SemanticAnalyzer: Semantic analysis engine
+ - NERExtractor: Alternative NER implementation
+ - LLMEnhancer: LLM-based extraction enhancement
+ - ExtractionValidator: Extraction validation
+ - SemanticNetworkExtractor: Semantic network extraction
"""
-# from .named_entity_recognizer import NamedEntityRecognizer
-# from .relation_extractor import RelationExtractor
-# from .event_detector import EventDetector
-# from .coreference_resolver import CoreferenceResolver
-# from .triple_extractor import TripleExtractor
-# from .semantic_analyzer import SemanticAnalyzer
+from .named_entity_recognizer import (
+ NamedEntityRecognizer,
+ EntityClassifier,
+ EntityConfidenceScorer,
+ CustomEntityDetector
+)
+from .ner_extractor import (
+ NERExtractor,
+ Entity
+)
+from .relation_extractor import (
+ RelationExtractor,
+ Relation
+)
+from .event_detector import (
+ EventDetector,
+ Event,
+ EventClassifier,
+ TemporalEventProcessor,
+ EventRelationshipExtractor
+)
+from .coreference_resolver import (
+ CoreferenceResolver,
+ Mention,
+ CoreferenceChain,
+ PronounResolver,
+ EntityCoreferenceDetector,
+ CoreferenceChainBuilder
+)
+from .triple_extractor import (
+ TripleExtractor,
+ Triple,
+ TripleValidator,
+ RDFSerializer,
+ TripleQualityChecker
+)
+from .semantic_analyzer import (
+ SemanticAnalyzer,
+ SemanticRole,
+ SemanticCluster,
+ SimilarityAnalyzer,
+ RoleLabeler,
+ SemanticClusterer
+)
+from .semantic_network_extractor import (
+ SemanticNetworkExtractor,
+ SemanticNode,
+ SemanticEdge,
+ SemanticNetwork
+)
+from .llm_enhancer import (
+ LLMEnhancer,
+ LLMResponse
+)
+from .extraction_validator import (
+ ExtractionValidator,
+ ValidationResult
+)
+
+__all__ = [
+ # Named Entity Recognition
+ "NamedEntityRecognizer",
+ "EntityClassifier",
+ "EntityConfidenceScorer",
+ "CustomEntityDetector",
+ "NERExtractor",
+ "Entity",
+
+ # Relation Extraction
+ "RelationExtractor",
+ "Relation",
+
+ # Event Detection
+ "EventDetector",
+ "Event",
+ "EventClassifier",
+ "TemporalEventProcessor",
+ "EventRelationshipExtractor",
+
+ # Coreference Resolution
+ "CoreferenceResolver",
+ "Mention",
+ "CoreferenceChain",
+ "PronounResolver",
+ "EntityCoreferenceDetector",
+ "CoreferenceChainBuilder",
+
+ # Triple Extraction
+ "TripleExtractor",
+ "Triple",
+ "TripleValidator",
+ "RDFSerializer",
+ "TripleQualityChecker",
+
+ # Semantic Analysis
+ "SemanticAnalyzer",
+ "SemanticRole",
+ "SemanticCluster",
+ "SimilarityAnalyzer",
+ "RoleLabeler",
+ "SemanticClusterer",
+
+ # Semantic Network
+ "SemanticNetworkExtractor",
+ "SemanticNode",
+ "SemanticEdge",
+ "SemanticNetwork",
+
+ # LLM Enhancement
+ "LLMEnhancer",
+ "LLMResponse",
+
+ # Validation
+ "ExtractionValidator",
+ "ValidationResult",
+]
diff --git a/libs/semantica/streaming/__init__.py b/libs/semantica/streaming/__init__.py
deleted file mode 100644
index d2638861..00000000
--- a/libs/semantica/streaming/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""
-Streaming and Real-time Processing Module
-
-This module provides comprehensive streaming and real-time processing capabilities.
-
-Exports:
- - StreamProcessor: Main streaming processor
- - StreamMonitor: Stream monitoring and management
- - StreamAggregator: Stream data aggregation
- - StreamTransformer: Stream data transformation
-"""
-
-# from .stream_processor import StreamProcessor
-# from .stream_monitor import StreamMonitor
-# from .stream_aggregator import StreamAggregator
-# from .stream_transformer import StreamTransformer
diff --git a/libs/semantica/streaming/backpressure_handler.py b/libs/semantica/streaming/backpressure_handler.py
deleted file mode 100644
index c15e1f31..00000000
--- a/libs/semantica/streaming/backpressure_handler.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Backpressure handler for Semantica framework.
-
-This module provides flow control and backpressure handling
-for stream processing operations.
-"""
-
-# TODO: Implement backpressure handling
-# - Flow control and backpressure detection
-# - Rate limiting and throttling
-# - Resource management and allocation
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced backpressure strategies
diff --git a/libs/semantica/streaming/checkpoint_manager.py b/libs/semantica/streaming/checkpoint_manager.py
deleted file mode 100644
index 9853ac10..00000000
--- a/libs/semantica/streaming/checkpoint_manager.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Checkpoint manager for Semantica framework.
-
-This module provides checkpoint management for
-stream processing and fault tolerance.
-"""
-
-# TODO: Implement checkpoint management
-# - Checkpoint creation and management
-# - State persistence and recovery
-# - Fault tolerance and error recovery
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced checkpoint strategies
diff --git a/libs/semantica/streaming/exactly_once.py b/libs/semantica/streaming/exactly_once.py
deleted file mode 100644
index 79687814..00000000
--- a/libs/semantica/streaming/exactly_once.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Exactly-once semantics for Semantica framework.
-
-This module provides exactly-once processing guarantees
-for stream processing operations.
-"""
-
-# TODO: Implement exactly-once semantics
-# - Exactly-once processing implementation
-# - Idempotency and deduplication
-# - Transaction management and coordination
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced exactly-once techniques
diff --git a/libs/semantica/streaming/kafka_adapter.py b/libs/semantica/streaming/kafka_adapter.py
deleted file mode 100644
index 33a9bc5c..00000000
--- a/libs/semantica/streaming/kafka_adapter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Kafka adapter for Semantica framework.
-
-This module provides Apache Kafka integration for
-real-time stream processing and data ingestion.
-"""
-
-# TODO: Implement Kafka adapter
-# - Kafka producer and consumer integration
-# - Topic management and configuration
-# - Message serialization and deserialization
-# - Error handling and recovery
-# - Performance optimization
-# - Advanced Kafka features
diff --git a/libs/semantica/streaming/kinesis_adapter.py b/libs/semantica/streaming/kinesis_adapter.py
deleted file mode 100644
index d8dc0e23..00000000
--- a/libs/semantica/streaming/kinesis_adapter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Kinesis adapter for Semantica framework.
-
-This module provides AWS Kinesis integration for
-real-time stream processing and data ingestion.
-"""
-
-# TODO: Implement Kinesis adapter
-# - Kinesis producer and consumer integration
-# - Stream management and configuration
-# - Data serialization and deserialization
-# - Error handling and recovery
-# - Performance optimization
-# - Advanced Kinesis features
diff --git a/libs/semantica/streaming/pulsar_adapter.py b/libs/semantica/streaming/pulsar_adapter.py
deleted file mode 100644
index a7dd0fa1..00000000
--- a/libs/semantica/streaming/pulsar_adapter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Pulsar adapter for Semantica framework.
-
-This module provides Apache Pulsar integration for
-real-time stream processing and messaging.
-"""
-
-# TODO: Implement Pulsar adapter
-# - Pulsar producer and consumer integration
-# - Topic and namespace management
-# - Message serialization and deserialization
-# - Error handling and recovery
-# - Performance optimization
-# - Advanced Pulsar features
diff --git a/libs/semantica/streaming/rabbitmq_adapter.py b/libs/semantica/streaming/rabbitmq_adapter.py
deleted file mode 100644
index 9af89db6..00000000
--- a/libs/semantica/streaming/rabbitmq_adapter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-RabbitMQ adapter for Semantica framework.
-
-This module provides RabbitMQ integration for
-message queuing and stream processing.
-"""
-
-# TODO: Implement RabbitMQ adapter
-# - RabbitMQ connection and channel management
-# - Queue and exchange management
-# - Message publishing and consuming
-# - Error handling and recovery
-# - Performance optimization
-# - Advanced RabbitMQ features
diff --git a/libs/semantica/streaming/stream_processor.py b/libs/semantica/streaming/stream_processor.py
deleted file mode 100644
index 824feb49..00000000
--- a/libs/semantica/streaming/stream_processor.py
+++ /dev/null
@@ -1,266 +0,0 @@
-"""
-Stream Processing Module
-
-Handles real-time stream processing and data transformation.
-
-Key Features:
- - Real-time stream processing
- - Stream data transformation
- - Stream aggregation and windowing
- - Stream monitoring and management
- - Error handling and recovery
-
-Main Classes:
- - StreamProcessor: Main stream processing class
- - StreamTransformer: Stream data transformation
- - StreamAggregator: Stream data aggregation
- - StreamMonitor: Stream monitoring engine
-"""
-
-
-class StreamProcessor:
- """
- Real-time stream processing handler.
-
- • Processes data streams in real-time
- • Handles stream data transformation
- • Manages stream aggregation and windowing
- • Monitors stream health and performance
- • Handles stream errors and recovery
- • Supports various streaming protocols
-
- Attributes:
- • transformer: Stream data transformer
- • aggregator: Stream data aggregator
- • monitor: Stream monitoring engine
- • error_handler: Stream error handler
- • supported_protocols: List of supported protocols
-
- Methods:
- • process_stream(): Process data stream
- • transform_data(): Transform stream data
- • aggregate_data(): Aggregate stream data
- • monitor_stream(): Monitor stream health
- """
-
- def __init__(self, config=None, **kwargs):
- """
- Initialize stream processor.
-
- • Setup stream processing engines
- • Configure data transformation
- • Initialize aggregation tools
- • Setup monitoring systems
- • Configure error handling
- """
- pass
-
- def process_stream(self, stream_source, **options):
- """
- Process data stream from source.
-
- • Connect to stream source
- • Process stream data
- • Apply transformations
- • Handle stream errors
- • Return processed data
- """
- pass
-
- def transform_data(self, data, transformation_rules, **options):
- """
- Transform stream data according to rules.
-
- • Apply transformation rules
- • Handle data format changes
- • Process data validation
- • Return transformed data
- """
- pass
-
- def aggregate_data(self, data, aggregation_config, **options):
- """
- Aggregate stream data using configuration.
-
- • Apply aggregation functions
- • Handle time windows
- • Process aggregation results
- • Return aggregated data
- """
- pass
-
- def monitor_stream(self, stream, **options):
- """
- Monitor stream health and performance.
-
- • Track stream metrics
- • Monitor stream health
- • Handle stream alerts
- • Return monitoring data
- """
- pass
-
-
-class StreamTransformer:
- """
- Stream data transformation engine.
-
- • Transforms stream data
- • Handles data format conversion
- • Manages transformation rules
- • Processes data validation
- """
-
- def __init__(self, **config):
- """
- Initialize stream transformer.
-
- • Setup transformation engines
- • Configure format converters
- • Initialize validation tools
- • Setup rule processors
- """
- pass
-
- def transform_data(self, data, transformation_rules):
- """
- Transform data according to rules.
-
- • Apply transformation rules
- • Handle data conversion
- • Process data validation
- • Return transformed data
- """
- pass
-
- def convert_format(self, data, from_format, to_format):
- """
- Convert data between formats.
-
- • Parse data from source format
- • Convert to target format
- • Handle format validation
- • Return converted data
- """
- pass
-
- def validate_data(self, data, validation_rules):
- """
- Validate data against rules.
-
- • Apply validation rules
- • Check data integrity
- • Handle validation errors
- • Return validation results
- """
- pass
-
-
-class StreamAggregator:
- """
- Stream data aggregation engine.
-
- • Aggregates stream data
- • Handles time windows
- • Manages aggregation functions
- • Processes aggregation results
- """
-
- def __init__(self, **config):
- """
- Initialize stream aggregator.
-
- • Setup aggregation functions
- • Configure time windowing
- • Initialize result processors
- • Setup aggregation rules
- """
- pass
-
- def aggregate_data(self, data, aggregation_config):
- """
- Aggregate data using configuration.
-
- • Apply aggregation functions
- • Handle time windows
- • Process aggregation results
- • Return aggregated data
- """
- pass
-
- def apply_time_window(self, data, window_config):
- """
- Apply time window to data.
-
- • Configure time windows
- • Process windowed data
- • Handle window boundaries
- • Return windowed data
- """
- pass
-
- def calculate_aggregates(self, data, functions):
- """
- Calculate aggregation functions.
-
- • Apply aggregation functions
- • Calculate statistics
- • Handle function combinations
- • Return aggregation results
- """
- pass
-
-
-class StreamMonitor:
- """
- Stream monitoring engine.
-
- • Monitors stream health
- • Tracks stream metrics
- • Handles stream alerts
- • Manages stream recovery
- """
-
- def __init__(self, **config):
- """
- Initialize stream monitor.
-
- • Setup monitoring tools
- • Configure metric collection
- • Initialize alert systems
- • Setup recovery mechanisms
- """
- pass
-
- def monitor_stream(self, stream, **options):
- """
- Monitor stream health and performance.
-
- • Track stream metrics
- • Monitor stream health
- • Handle stream alerts
- • Return monitoring data
- """
- pass
-
- def collect_metrics(self, stream):
- """
- Collect stream metrics.
-
- • Gather performance metrics
- • Calculate stream statistics
- • Track resource usage
- • Return metrics data
- """
- pass
-
- def handle_alerts(self, alerts):
- """
- Handle stream alerts and notifications.
-
- • Process alert conditions
- • Send notifications
- • Handle alert escalation
- • Return alert handling results
- """
- pass
diff --git a/libs/semantica/triple_store/__init__.py b/libs/semantica/triple_store/__init__.py
index f5c2c9bc..d05947d0 100644
--- a/libs/semantica/triple_store/__init__.py
+++ b/libs/semantica/triple_store/__init__.py
@@ -3,4 +3,60 @@ Triple store module for Semantica framework.
This module provides triple store integration and management
for RDF data storage and querying.
+
+Exports:
+ - TripleManager: Triple store management and CRUD operations
+ - BlazegraphAdapter: Blazegraph integration
+ - JenaAdapter: Apache Jena integration
+ - RDF4JAdapter: Eclipse RDF4J integration
+ - VirtuosoAdapter: Virtuoso RDF store integration
+ - QueryEngine: SPARQL query execution and optimization
+ - BulkLoader: High-volume data loading
"""
+
+from .triple_manager import (
+ TripleManager,
+ TripleStore
+)
+from .blazegraph_adapter import (
+ BlazegraphAdapter
+)
+from .jena_adapter import (
+ JenaAdapter
+)
+from .rdf4j_adapter import (
+ RDF4JAdapter
+)
+from .virtuoso_adapter import (
+ VirtuosoAdapter
+)
+from .query_engine import (
+ QueryEngine,
+ QueryResult,
+ QueryPlan
+)
+from .bulk_loader import (
+ BulkLoader,
+ LoadProgress
+)
+
+__all__ = [
+ # Triple management
+ "TripleManager",
+ "TripleStore",
+
+ # Store adapters
+ "BlazegraphAdapter",
+ "JenaAdapter",
+ "RDF4JAdapter",
+ "VirtuosoAdapter",
+
+ # Query engine
+ "QueryEngine",
+ "QueryResult",
+ "QueryPlan",
+
+ # Bulk loading
+ "BulkLoader",
+ "LoadProgress",
+]
diff --git a/libs/semantica/triple_store/blazegraph_adapter.py b/libs/semantica/triple_store/blazegraph_adapter.py
index d44edbce..c881c89f 100644
--- a/libs/semantica/triple_store/blazegraph_adapter.py
+++ b/libs/semantica/triple_store/blazegraph_adapter.py
@@ -5,10 +5,291 @@ This module provides Blazegraph integration for RDF storage
and SPARQL querying.
"""
-# TODO: Implement Blazegraph adapter
-# - Blazegraph connection and authentication
-# - SPARQL query execution
-# - Bulk data loading and management
-# - Namespace and graph management
-# - Performance optimization
-# - Error handling and recovery
+from typing import Any, Dict, List, Optional
+import requests
+from urllib.parse import urljoin
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+
+class BlazegraphAdapter:
+ """
+ Blazegraph triple store adapter.
+
+ • Blazegraph connection and authentication
+ • SPARQL query execution
+ • Bulk data loading and management
+ • Namespace and graph management
+ • Performance optimization
+ • Error handling and recovery
+ """
+
+ def __init__(self, endpoint: str, **config):
+ """
+ Initialize Blazegraph adapter.
+
+ Args:
+ endpoint: Blazegraph endpoint URL
+ **config: Additional configuration:
+ - namespace: Namespace name (default: "kb")
+ - username: Username for authentication
+ - password: Password for authentication
+ - timeout: Request timeout (default: 30)
+ """
+ self.logger = get_logger("blazegraph_adapter")
+ self.config = config
+
+ self.endpoint = endpoint.rstrip('/')
+ self.namespace = config.get("namespace", "kb")
+ self.username = config.get("username")
+ self.password = config.get("password")
+ self.timeout = config.get("timeout", 30)
+
+ self.connected = False
+ self._connect()
+
+ def _connect(self) -> None:
+ """Connect to Blazegraph instance."""
+ try:
+ # Test connection
+ sparql_endpoint = self._get_sparql_endpoint()
+ response = requests.get(
+ sparql_endpoint,
+ params={"query": "SELECT * WHERE { ?s ?p ?o } LIMIT 1"},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ if response.status_code == 200:
+ self.connected = True
+ self.logger.info(f"Connected to Blazegraph: {self.endpoint}")
+ else:
+ self.logger.warning(f"Blazegraph connection test failed: {response.status_code}")
+ except Exception as e:
+ self.logger.warning(f"Could not connect to Blazegraph: {e}")
+
+ def _get_sparql_endpoint(self) -> str:
+ """Get SPARQL endpoint URL."""
+ return urljoin(self.endpoint, f"/blazegraph/namespace/{self.namespace}/sparql")
+
+ def _get_update_endpoint(self) -> str:
+ """Get SPARQL Update endpoint URL."""
+ return urljoin(self.endpoint, f"/blazegraph/namespace/{self.namespace}/sparql")
+
+ def execute_sparql(
+ self,
+ query: str,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ **options: Additional options
+
+ Returns:
+ Query results
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to Blazegraph")
+
+ sparql_endpoint = self._get_sparql_endpoint()
+
+ try:
+ response = requests.post(
+ sparql_endpoint,
+ data={"query": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ # Parse JSON response
+ result_data = response.json()
+
+ return {
+ "success": True,
+ "bindings": result_data.get("results", {}).get("bindings", []),
+ "variables": result_data.get("head", {}).get("vars", []),
+ "metadata": {
+ "query": query,
+ "endpoint": sparql_endpoint
+ }
+ }
+ except Exception as e:
+ self.logger.error(f"SPARQL query failed: {e}")
+ raise ProcessingError(f"SPARQL query failed: {e}")
+
+ def bulk_load(
+ self,
+ triples: List[Triple],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Load triples in bulk.
+
+ Args:
+ triples: List of triples
+ **options: Additional options:
+ - format: RDF format (turtle, ntriples, rdfxml)
+ - graph: Named graph URI
+
+ Returns:
+ Load status
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to Blazegraph")
+
+ # Convert triples to RDF format
+ format = options.get("format", "turtle")
+ rdf_data = self._triples_to_rdf(triples, format)
+
+ # Upload endpoint
+ upload_endpoint = urljoin(self.endpoint, f"/blazegraph/namespace/{self.namespace}/sparql")
+
+ try:
+ # Use SPARQL INSERT for bulk loading
+ graph = options.get("graph", "")
+ graph_clause = f"GRAPH <{graph}>" if graph else ""
+
+ # Build INSERT query
+ insert_data = self._build_insert_data(triples)
+ query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"
+
+ response = requests.post(
+ upload_endpoint,
+ data={"update": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout * 2, # Longer timeout for bulk operations
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {
+ "success": True,
+ "triples_loaded": len(triples),
+ "namespace": self.namespace
+ }
+ except Exception as e:
+ self.logger.error(f"Bulk load failed: {e}")
+ raise ProcessingError(f"Bulk load failed: {e}")
+
+ def _triples_to_rdf(self, triples: List[Triple], format: str = "turtle") -> str:
+ """Convert triples to RDF format."""
+ if format == "turtle":
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return "\n".join(lines)
+ else:
+ # For other formats, use simple turtle conversion
+ return self._triples_to_rdf(triples, "turtle")
+
+ def _build_insert_data(self, triples: List[Triple]) -> str:
+ """Build SPARQL INSERT DATA clause."""
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return " ".join(lines)
+
+ def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Add single triple."""
+ return self.bulk_load([triple], **options)
+
+ def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ """Add multiple triples."""
+ return self.bulk_load(triples, **options)
+
+ def get_triples(
+ self,
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ **options
+ ) -> List[Triple]:
+ """Get triples matching criteria."""
+ # Build SPARQL query
+ where_clauses = []
+ if subject:
+ where_clauses.append(f"?s = <{subject}>")
+ if predicate:
+ where_clauses.append(f"?p = <{predicate}>")
+ if object:
+ where_clauses.append(f"?o = <{object}>")
+
+ where_clause = " ".join(where_clauses) if where_clauses else ""
+ query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"
+
+ result = self.execute_sparql(query, **options)
+
+ # Convert bindings to triples
+ triples = []
+ for binding in result["bindings"]:
+ triples.append(Triple(
+ subject=binding.get("s", {}).get("value", ""),
+ predicate=binding.get("p", {}).get("value", ""),
+ object=binding.get("o", {}).get("value", ""),
+ metadata={"source": "blazegraph"}
+ ))
+
+ return triples
+
+ def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Delete triple."""
+ if not self.connected:
+ raise ProcessingError("Not connected to Blazegraph")
+
+ update_endpoint = self._get_update_endpoint()
+
+ query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+
+ try:
+ response = requests.post(
+ update_endpoint,
+ data={"update": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {"success": True}
+ except Exception as e:
+ self.logger.error(f"Delete triple failed: {e}")
+ raise ProcessingError(f"Delete triple failed: {e}")
+
+ def create_namespace(self, namespace: str, **options) -> Dict[str, Any]:
+ """
+ Create new namespace.
+
+ Args:
+ namespace: Namespace name
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ # Blazegraph namespace creation via REST API
+ create_endpoint = urljoin(self.endpoint, "/blazegraph/namespace")
+
+ try:
+ response = requests.post(
+ create_endpoint,
+ json={"namespace": namespace, **options},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {"success": True, "namespace": namespace}
+ except Exception as e:
+ self.logger.error(f"Create namespace failed: {e}")
+ raise ProcessingError(f"Create namespace failed: {e}")
diff --git a/libs/semantica/triple_store/bulk_loader.py b/libs/semantica/triple_store/bulk_loader.py
index 18ea6714..99a4b339 100644
--- a/libs/semantica/triple_store/bulk_loader.py
+++ b/libs/semantica/triple_store/bulk_loader.py
@@ -5,10 +5,294 @@ This module provides high-volume data loading capabilities
for triple stores.
"""
-# TODO: Implement bulk loading
-# - High-volume data loading strategies
-# - Batch processing and chunking
-# - Progress monitoring and reporting
-# - Error handling and recovery
-# - Performance optimization
-# - Memory management for large datasets
+from typing import Any, Dict, List, Optional
+from dataclasses import dataclass, field
+from datetime import datetime
+import time
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+
+@dataclass
+class LoadProgress:
+ """Bulk loading progress information."""
+ total_triples: int
+ loaded_triples: int
+ failed_triples: int = 0
+ current_batch: int = 0
+ total_batches: int = 0
+ progress_percentage: float = 0.0
+ elapsed_time: float = 0.0
+ estimated_remaining: Optional[float] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class BulkLoader:
+ """
+ High-volume data loading system for triple stores.
+
+ • High-volume data loading strategies
+ • Batch processing and chunking
+ • Progress monitoring and reporting
+ • Error handling and recovery
+ • Performance optimization
+ • Memory management for large datasets
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize bulk loader.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options:
+ - batch_size: Batch size for loading (default: 1000)
+ - max_retries: Maximum retry attempts (default: 3)
+ - retry_delay: Delay between retries in seconds (default: 1.0)
+ """
+ self.logger = get_logger("bulk_loader")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.batch_size = self.config.get("batch_size", 1000)
+ self.max_retries = self.config.get("max_retries", 3)
+ self.retry_delay = self.config.get("retry_delay", 1.0)
+
+ def load_triples(
+ self,
+ triples: List[Triple],
+ store_adapter: Any,
+ **options
+ ) -> LoadProgress:
+ """
+ Load triples in bulk.
+
+ Args:
+ triples: List of triples to load
+ store_adapter: Triple store adapter instance
+ **options: Additional options:
+ - batch_size: Override default batch size
+ - progress_callback: Callback function for progress updates
+ - stop_on_error: Stop loading on first error (default: False)
+
+ Returns:
+ Load progress information
+ """
+ start_time = time.time()
+ batch_size = options.get("batch_size", self.batch_size)
+ stop_on_error = options.get("stop_on_error", False)
+ progress_callback = options.get("progress_callback")
+
+ total_triples = len(triples)
+ total_batches = (total_triples + batch_size - 1) // batch_size
+
+ loaded_count = 0
+ failed_count = 0
+
+ self.logger.info(f"Starting bulk load: {total_triples} triples in {total_batches} batches")
+
+ # Process in batches
+ for batch_num in range(total_batches):
+ batch_start = batch_num * batch_size
+ batch_end = min(batch_start + batch_size, total_triples)
+ batch = triples[batch_start:batch_end]
+
+ # Load batch with retries
+ batch_loaded = 0
+ for attempt in range(self.max_retries):
+ try:
+ if hasattr(store_adapter, "bulk_load"):
+ result = store_adapter.bulk_load(batch, **options)
+ elif hasattr(store_adapter, "add_triples"):
+ result = store_adapter.add_triples(batch, **options)
+ else:
+ raise ProcessingError("Store adapter does not support bulk loading")
+
+ batch_loaded = len(batch)
+ loaded_count += batch_loaded
+ break
+
+ except Exception as e:
+ if attempt < self.max_retries - 1:
+ self.logger.warning(f"Batch {batch_num} failed, retrying: {e}")
+ time.sleep(self.retry_delay * (attempt + 1))
+ else:
+ self.logger.error(f"Batch {batch_num} failed after {self.max_retries} attempts: {e}")
+ failed_count += len(batch)
+
+ if stop_on_error:
+ raise ProcessingError(f"Bulk load stopped due to error: {e}")
+
+ # Update progress
+ elapsed = time.time() - start_time
+ progress = (loaded_count / total_triples * 100) if total_triples > 0 else 0.0
+ estimated_remaining = None
+ if loaded_count > 0:
+ estimated_remaining = (elapsed / loaded_count) * (total_triples - loaded_count)
+
+ progress_info = LoadProgress(
+ total_triples=total_triples,
+ loaded_triples=loaded_count,
+ failed_triples=failed_count,
+ current_batch=batch_num + 1,
+ total_batches=total_batches,
+ progress_percentage=progress,
+ elapsed_time=elapsed,
+ estimated_remaining=estimated_remaining,
+ metadata={
+ "batch_size": batch_size,
+ "store_type": store_adapter.__class__.__name__
+ }
+ )
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(progress_info)
+
+ self.logger.debug(f"Progress: {progress:.1f}% ({loaded_count}/{total_triples} triples)")
+
+ elapsed = time.time() - start_time
+
+ final_progress = LoadProgress(
+ total_triples=total_triples,
+ loaded_triples=loaded_count,
+ failed_triples=failed_count,
+ current_batch=total_batches,
+ total_batches=total_batches,
+ progress_percentage=100.0,
+ elapsed_time=elapsed,
+ estimated_remaining=0.0,
+ metadata={
+ "success": failed_count == 0,
+ "throughput": loaded_count / elapsed if elapsed > 0 else 0.0
+ }
+ )
+
+ self.logger.info(
+ f"Bulk load completed: {loaded_count}/{total_triples} triples loaded "
+ f"in {elapsed:.2f}s ({loaded_count / elapsed:.0f} triples/sec)"
+ )
+
+ return final_progress
+
+ def load_from_file(
+ self,
+ file_path: str,
+ store_adapter: Any,
+ **options
+ ) -> LoadProgress:
+ """
+ Load triples from file.
+
+ Args:
+ file_path: Path to RDF file
+ store_adapter: Triple store adapter
+ **options: Additional options:
+ - format: File format (turtle, ntriples, rdfxml)
+ - chunk_size: Chunk size for reading large files
+
+ Returns:
+ Load progress information
+ """
+ format = options.get("format", "turtle")
+ chunk_size = options.get("chunk_size", 10000)
+
+ # This would parse the file and extract triples
+ # For now, return placeholder
+ self.logger.warning("File loading not fully implemented - would parse and load RDF file")
+
+ return LoadProgress(
+ total_triples=0,
+ loaded_triples=0,
+ metadata={"file_path": file_path, "format": format}
+ )
+
+ def load_from_stream(
+ self,
+ triples_stream: Any,
+ store_adapter: Any,
+ **options
+ ) -> LoadProgress:
+ """
+ Load triples from stream.
+
+ Args:
+ triples_stream: Stream of triples
+ store_adapter: Triple store adapter
+ **options: Additional options
+
+ Returns:
+ Load progress information
+ """
+ # Collect triples from stream in batches
+ batch = []
+ total_loaded = 0
+
+ for triple in triples_stream:
+ batch.append(triple)
+
+ if len(batch) >= self.batch_size:
+ # Load batch
+ progress = self.load_triples(batch, store_adapter, **options)
+ total_loaded += progress.loaded_triples
+ batch = []
+
+ # Load remaining triples
+ if batch:
+ progress = self.load_triples(batch, store_adapter, **options)
+ total_loaded += progress.loaded_triples
+
+ return LoadProgress(
+ total_triples=total_loaded,
+ loaded_triples=total_loaded,
+ metadata={"source": "stream"}
+ )
+
+ def validate_before_load(
+ self,
+ triples: List[Triple],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Validate triples before loading.
+
+ Args:
+ triples: List of triples to validate
+ **options: Validation options
+
+ Returns:
+ Validation results
+ """
+ errors = []
+ warnings = []
+
+ # Check for empty triples
+ empty_triples = [t for t in triples if not t.subject or not t.predicate or not t.object]
+ if empty_triples:
+ errors.append(f"{len(empty_triples)} triples have empty components")
+
+ # Check for invalid URIs
+ invalid_uris = []
+ for triple in triples:
+ if not triple.subject.startswith("http") and not triple.subject.startswith("<"):
+ invalid_uris.append(f"Subject: {triple.subject}")
+ if not triple.predicate.startswith("http") and not triple.predicate.startswith("<"):
+ invalid_uris.append(f"Predicate: {triple.predicate}")
+
+ if invalid_uris:
+ warnings.append(f"{len(invalid_uris)} triples may have invalid URIs")
+
+ # Check confidence scores
+ low_confidence = [t for t in triples if t.confidence < 0.5]
+ if low_confidence:
+ warnings.append(f"{len(low_confidence)} triples have low confidence scores")
+
+ return {
+ "valid": len(errors) == 0,
+ "errors": errors,
+ "warnings": warnings,
+ "total_triples": len(triples),
+ "valid_triples": len(triples) - len(empty_triples)
+ }
diff --git a/libs/semantica/triple_store/jena_adapter.py b/libs/semantica/triple_store/jena_adapter.py
index bc4ef398..f66809fe 100644
--- a/libs/semantica/triple_store/jena_adapter.py
+++ b/libs/semantica/triple_store/jena_adapter.py
@@ -5,10 +5,283 @@ This module provides Apache Jena integration for RDF storage
and SPARQL querying.
"""
-# TODO: Implement Jena adapter
-# - Jena connection and configuration
-# - SPARQL query execution
-# - Model and dataset management
-# - Inference and reasoning support
-# - Performance optimization
-# - Error handling and recovery
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+# Optional Jena imports
+try:
+ from rdflib import Graph, Namespace, URIRef, Literal, RDF
+ from rdflib.plugins.stores.sparqlstore import SPARQLStore
+ HAS_JENA_RDFLIB = True
+except ImportError:
+ HAS_JENA_RDFLIB = False
+ Graph = None
+ RDF = None
+
+
+class JenaAdapter:
+ """
+ Apache Jena adapter for triple store operations.
+
+ • Jena connection and configuration
+ • SPARQL query execution
+ • Model and dataset management
+ • Inference and reasoning support
+ • Performance optimization
+ • Error handling and recovery
+ """
+
+ def __init__(self, **config):
+ """
+ Initialize Jena adapter.
+
+ Args:
+ **config: Configuration options:
+ - endpoint: Jena Fuseki endpoint (optional)
+ - dataset: Dataset name
+ - enable_inference: Enable inference (default: False)
+ """
+ self.logger = get_logger("jena_adapter")
+ self.config = config
+
+ self.endpoint = config.get("endpoint")
+ self.dataset = config.get("dataset", "default")
+ self.enable_inference = config.get("enable_inference", False)
+
+ self.graph: Optional[Graph] = None
+ self._initialize_graph()
+
+ def _initialize_graph(self) -> None:
+ """Initialize RDF graph."""
+ if HAS_JENA_RDFLIB:
+ if self.endpoint:
+ # Use SPARQL store for remote endpoint
+ try:
+ store = SPARQLStore(query_endpoint=self.endpoint)
+ self.graph = Graph(store=store)
+ except Exception as e:
+ self.logger.warning(f"Could not initialize SPARQL store: {e}")
+ self.graph = Graph()
+ else:
+ # Use in-memory graph
+ self.graph = Graph()
+ else:
+ self.logger.warning("rdflib not available. Jena adapter will use basic operations.")
+ self.graph = None
+
+ def create_model(self, **options) -> Dict[str, Any]:
+ """
+ Create and manage RDF models.
+
+ Args:
+ **options: Model options
+
+ Returns:
+ Model information
+ """
+ if self.graph is None:
+ self._initialize_graph()
+
+ return {
+ "model_id": self.dataset,
+ "endpoint": self.endpoint,
+ "triple_count": len(self.graph) if self.graph else 0
+ }
+
+ def add_triples(
+ self,
+ triples: List[Triple],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Add triples to model.
+
+ Args:
+ triples: List of triples
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ if not self.graph:
+ raise ProcessingError("Graph not initialized")
+
+ try:
+ added_count = 0
+ for triple in triples:
+ try:
+ subject = URIRef(triple.subject)
+ predicate = URIRef(triple.predicate)
+ obj = URIRef(triple.object) if triple.object.startswith("http") else Literal(triple.object)
+
+ self.graph.add((subject, predicate, obj))
+ added_count += 1
+ except Exception as e:
+ self.logger.warning(f"Failed to add triple: {e}")
+
+ return {
+ "success": True,
+ "added": added_count,
+ "total": len(triples)
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to add triples: {e}")
+ raise ProcessingError(f"Failed to add triples: {e}")
+
+ def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Add single triple."""
+ return self.add_triples([triple], **options)
+
+ def get_triples(
+ self,
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ **options
+ ) -> List[Triple]:
+ """Get triples matching criteria."""
+ if not self.graph:
+ return []
+
+ try:
+ # Build SPARQL query
+ query_parts = []
+ if subject:
+ query_parts.append(f"?s = <{subject}>")
+ if predicate:
+ query_parts.append(f"?p = <{predicate}>")
+ if object:
+ query_parts.append(f"?o = <{object}>")
+
+ where_clause = " ".join(query_parts) if query_parts else ""
+ query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"
+
+ results = self.graph.query(query)
+
+ triples = []
+ for row in results:
+ triples.append(Triple(
+ subject=str(row.s),
+ predicate=str(row.p),
+ object=str(row.o),
+ metadata={"source": "jena"}
+ ))
+
+ return triples
+ except Exception as e:
+ self.logger.error(f"Failed to get triples: {e}")
+ return []
+
+ def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Delete triple."""
+ if not self.graph:
+ raise ProcessingError("Graph not initialized")
+
+ try:
+ subject = URIRef(triple.subject)
+ predicate = URIRef(triple.predicate)
+ obj = URIRef(triple.object) if triple.object.startswith("http") else Literal(triple.object)
+
+ self.graph.remove((subject, predicate, obj))
+
+ return {"success": True}
+ except Exception as e:
+ self.logger.error(f"Failed to delete triple: {e}")
+ raise ProcessingError(f"Failed to delete triple: {e}")
+
+ def run_inference(
+ self,
+ model: Optional[Any] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Execute inference rules.
+
+ Args:
+ model: Optional model (uses default if not provided)
+ **options: Inference options
+
+ Returns:
+ Inference results
+ """
+ if not self.enable_inference:
+ self.logger.warning("Inference not enabled")
+ return {"success": False, "message": "Inference not enabled"}
+
+ # Basic inference would require OWL reasoner
+ # This is a placeholder implementation
+ self.logger.info("Inference would be executed here with OWL reasoner")
+
+ return {
+ "success": True,
+ "inferred_triples": 0,
+ "message": "Inference placeholder"
+ }
+
+ def execute_sparql(
+ self,
+ query: str,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ **options: Additional options
+
+ Returns:
+ Query results
+ """
+ if not self.graph:
+ raise ProcessingError("Graph not initialized")
+
+ try:
+ results = self.graph.query(query)
+
+ bindings = []
+ variables = []
+
+ if results.vars:
+ variables = [str(v) for v in results.vars]
+
+ for row in results:
+ binding = {}
+ for var in results.vars:
+ value = getattr(row, str(var))
+ if value:
+ binding[str(var)] = {"value": str(value), "type": "uri" if isinstance(value, URIRef) else "literal"}
+ bindings.append(binding)
+
+ return {
+ "success": True,
+ "bindings": bindings,
+ "variables": variables,
+ "metadata": {"query": query}
+ }
+ except Exception as e:
+ self.logger.error(f"SPARQL query failed: {e}")
+ raise ProcessingError(f"SPARQL query failed: {e}")
+
+ def serialize(self, format: str = "turtle", **options) -> str:
+ """
+ Serialize graph to RDF format.
+
+ Args:
+ format: RDF format (turtle, rdfxml, n3)
+ **options: Serialization options
+
+ Returns:
+ Serialized RDF string
+ """
+ if not self.graph:
+ return ""
+
+ try:
+ return self.graph.serialize(format=format)
+ except Exception as e:
+ self.logger.error(f"Serialization failed: {e}")
+ return ""
diff --git a/libs/semantica/triple_store/query_engine.py b/libs/semantica/triple_store/query_engine.py
index a3967a06..a0af3168 100644
--- a/libs/semantica/triple_store/query_engine.py
+++ b/libs/semantica/triple_store/query_engine.py
@@ -5,10 +5,298 @@ This module provides SPARQL query execution and optimization
for triple store operations.
"""
-# TODO: Implement query engine
-# - SPARQL query execution and optimization
-# - Query planning and caching
-# - Result processing and formatting
-# - Performance monitoring and profiling
-# - Error handling and validation
-# - Multi-store query support
+from typing import Any, Dict, List, Optional
+from dataclasses import dataclass, field
+from datetime import datetime
+import time
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class QueryResult:
+ """SPARQL query result."""
+ bindings: List[Dict[str, Any]]
+ variables: List[str]
+ execution_time: float = 0.0
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class QueryPlan:
+ """Query execution plan."""
+ query: str
+ optimized_query: str
+ estimated_cost: float = 0.0
+ execution_steps: List[str] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class QueryEngine:
+ """
+ SPARQL query execution and optimization engine.
+
+ • SPARQL query execution and optimization
+ • Query planning and caching
+ • Result processing and formatting
+ • Performance monitoring and profiling
+ • Error handling and validation
+ • Multi-store query support
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize query engine.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options:
+ - enable_caching: Enable query caching (default: True)
+ - cache_size: Cache size limit
+ - enable_optimization: Enable query optimization (default: True)
+ """
+ self.logger = get_logger("query_engine")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.enable_caching = self.config.get("enable_caching", True)
+ self.enable_optimization = self.config.get("enable_optimization", True)
+ self.cache_size = self.config.get("cache_size", 1000)
+
+ self.query_cache: Dict[str, QueryResult] = {}
+ self.query_history: List[Dict[str, Any]] = []
+
+ def execute_query(
+ self,
+ query: str,
+ store_adapter: Any,
+ **options
+ ) -> QueryResult:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ store_adapter: Triple store adapter instance
+ **options: Additional options
+
+ Returns:
+ Query result
+ """
+ start_time = time.time()
+
+ # Validate query
+ if not self._validate_query(query):
+ raise ValidationError("Invalid SPARQL query")
+
+ # Check cache
+ if self.enable_caching:
+ cache_key = self._get_cache_key(query)
+ if cache_key in self.query_cache:
+ self.logger.debug("Returning cached query result")
+ cached_result = self.query_cache[cache_key]
+ cached_result.metadata["cached"] = True
+ return cached_result
+
+ # Optimize query
+ if self.enable_optimization:
+ optimized_query = self.optimize_query(query, **options)
+ else:
+ optimized_query = query
+
+ # Execute query
+ try:
+ if hasattr(store_adapter, "execute_sparql"):
+ result_data = store_adapter.execute_sparql(optimized_query, **options)
+ else:
+ raise ProcessingError("Store adapter does not support SPARQL execution")
+
+ execution_time = time.time() - start_time
+
+ result = QueryResult(
+ bindings=result_data.get("bindings", []),
+ variables=result_data.get("variables", []),
+ execution_time=execution_time,
+ metadata={
+ **result_data.get("metadata", {}),
+ "optimized": optimized_query != query,
+ "cached": False
+ }
+ )
+
+ # Cache result
+ if self.enable_caching:
+ self._cache_result(query, result)
+
+ # Record history
+ self.query_history.append({
+ "query": query,
+ "execution_time": execution_time,
+ "result_count": len(result.bindings),
+ "timestamp": datetime.now().isoformat()
+ })
+
+ return result
+
+ except Exception as e:
+ execution_time = time.time() - start_time
+ self.logger.error(f"Query execution failed: {e}")
+ raise ProcessingError(f"Query execution failed: {e}")
+
+ def optimize_query(
+ self,
+ query: str,
+ **options
+ ) -> str:
+ """
+ Optimize SPARQL query.
+
+ Args:
+ query: Original query
+ **options: Optimization options
+
+ Returns:
+ Optimized query
+ """
+ optimized = query.strip()
+
+ # Remove unnecessary whitespace
+ optimized = " ".join(optimized.split())
+
+ # Add LIMIT if SELECT query doesn't have one
+ if "SELECT" in optimized.upper() and "LIMIT" not in optimized.upper():
+ if options.get("add_limit", True):
+ default_limit = options.get("default_limit", 1000)
+ optimized += f" LIMIT {default_limit}"
+
+ # Basic query rewriting
+ # (More sophisticated optimization would require query parser)
+
+ return optimized
+
+ def plan_query(
+ self,
+ query: str,
+ **options
+ ) -> QueryPlan:
+ """
+ Create query execution plan.
+
+ Args:
+ query: SPARQL query
+ **options: Planning options
+
+ Returns:
+ Query execution plan
+ """
+ optimized_query = self.optimize_query(query, **options) if self.enable_optimization else query
+
+ # Estimate cost (simplified)
+ estimated_cost = self._estimate_query_cost(query)
+
+ # Identify execution steps
+ execution_steps = self._identify_execution_steps(query)
+
+ return QueryPlan(
+ query=query,
+ optimized_query=optimized_query,
+ estimated_cost=estimated_cost,
+ execution_steps=execution_steps,
+ metadata={
+ "optimization_enabled": self.enable_optimization
+ }
+ )
+
+ def _validate_query(self, query: str) -> bool:
+ """Validate SPARQL query syntax (basic)."""
+ if not query or not query.strip():
+ return False
+
+ query_upper = query.upper()
+
+ # Check for valid SPARQL keywords
+ valid_keywords = ["SELECT", "ASK", "CONSTRUCT", "DESCRIBE", "INSERT", "DELETE", "WHERE"]
+ if not any(keyword in query_upper for keyword in valid_keywords):
+ return False
+
+ return True
+
+ def _estimate_query_cost(self, query: str) -> float:
+ """Estimate query execution cost."""
+ # Simple heuristic based on query complexity
+ cost = 1.0
+
+ # COUNT queries are more expensive
+ if "COUNT" in query.upper():
+ cost *= 2.0
+
+ # Multiple joins increase cost
+ join_count = query.upper().count("JOIN") + query.count(".")
+ cost *= (1.0 + join_count * 0.1)
+
+ # DISTINCT increases cost
+ if "DISTINCT" in query.upper():
+ cost *= 1.5
+
+ return cost
+
+ def _identify_execution_steps(self, query: str) -> List[str]:
+ """Identify query execution steps."""
+ steps = []
+
+ query_upper = query.upper()
+
+ if "SELECT" in query_upper:
+ steps.append("SELECT projection")
+ if "WHERE" in query_upper:
+ steps.append("Pattern matching")
+ if "FILTER" in query_upper:
+ steps.append("Filtering")
+ if "ORDER BY" in query_upper:
+ steps.append("Sorting")
+ if "LIMIT" in query_upper or "OFFSET" in query_upper:
+ steps.append("Pagination")
+
+ return steps
+
+ def _get_cache_key(self, query: str) -> str:
+ """Generate cache key for query."""
+ import hashlib
+ normalized = " ".join(query.split())
+ return hashlib.md5(normalized.encode()).hexdigest()
+
+ def _cache_result(self, query: str, result: QueryResult) -> None:
+ """Cache query result."""
+ if len(self.query_cache) >= self.cache_size:
+ # Remove oldest entry
+ oldest_key = next(iter(self.query_cache))
+ del self.query_cache[oldest_key]
+
+ cache_key = self._get_cache_key(query)
+ self.query_cache[cache_key] = result
+
+ def clear_cache(self) -> None:
+ """Clear query cache."""
+ self.query_cache.clear()
+
+ def get_query_statistics(self) -> Dict[str, Any]:
+ """Get query execution statistics."""
+ if not self.query_history:
+ return {
+ "total_queries": 0,
+ "average_execution_time": 0.0,
+ "total_execution_time": 0.0
+ }
+
+ execution_times = [q["execution_time"] for q in self.query_history]
+
+ return {
+ "total_queries": len(self.query_history),
+ "average_execution_time": sum(execution_times) / len(execution_times),
+ "total_execution_time": sum(execution_times),
+ "min_execution_time": min(execution_times),
+ "max_execution_time": max(execution_times),
+ "cache_size": len(self.query_cache),
+ "cache_hit_rate": 0.0 # Would need to track hits/misses
+ }
diff --git a/libs/semantica/triple_store/rdf4j_adapter.py b/libs/semantica/triple_store/rdf4j_adapter.py
index 7369f0f0..e6e1e4db 100644
--- a/libs/semantica/triple_store/rdf4j_adapter.py
+++ b/libs/semantica/triple_store/rdf4j_adapter.py
@@ -5,10 +5,296 @@ This module provides RDF4J integration for RDF storage
and SPARQL querying.
"""
-# TODO: Implement RDF4J adapter
-# - RDF4J connection and repository management
-# - SPARQL query execution
-# - Repository configuration and setup
-# - Transaction support
-# - Performance optimization
-# - Error handling and recovery
+from typing import Any, Dict, List, Optional
+import requests
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+
+class RDF4JAdapter:
+ """
+ Eclipse RDF4J adapter for triple store operations.
+
+ • RDF4J connection and repository management
+ • SPARQL query execution
+ • Repository configuration and setup
+ • Transaction support
+ • Performance optimization
+ • Error handling and recovery
+ """
+
+ def __init__(self, endpoint: str, **config):
+ """
+ Initialize RDF4J adapter.
+
+ Args:
+ endpoint: RDF4J server endpoint
+ **config: Additional configuration:
+ - repository_id: Repository identifier
+ - username: Username for authentication
+ - password: Password for authentication
+ - timeout: Request timeout (default: 30)
+ """
+ self.logger = get_logger("rdf4j_adapter")
+ self.config = config
+
+ self.endpoint = endpoint.rstrip('/')
+ self.repository_id = config.get("repository_id", "default")
+ self.username = config.get("username")
+ self.password = config.get("password")
+ self.timeout = config.get("timeout", 30)
+
+ self.connected = False
+ self._connect()
+
+ def _connect(self) -> None:
+ """Connect to RDF4J server."""
+ try:
+ # Test connection
+ test_url = f"{self.endpoint}/repositories/{self.repository_id}"
+ response = requests.get(
+ test_url,
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ if response.status_code == 200:
+ self.connected = True
+ self.logger.info(f"Connected to RDF4J: {self.endpoint}")
+ else:
+ self.logger.warning(f"RDF4J connection test failed: {response.status_code}")
+ except Exception as e:
+ self.logger.warning(f"Could not connect to RDF4J: {e}")
+
+ def _get_sparql_endpoint(self) -> str:
+ """Get SPARQL query endpoint."""
+ return f"{self.endpoint}/repositories/{self.repository_id}"
+
+ def _get_update_endpoint(self) -> str:
+ """Get SPARQL Update endpoint."""
+ return f"{self.endpoint}/repositories/{self.repository_id}/statements"
+
+ def create_repository(
+ self,
+ repository_config: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Create and configure repository.
+
+ Args:
+ repository_config: Repository configuration
+ **options: Additional options
+
+ Returns:
+ Repository information
+ """
+ # RDF4J repository creation via REST API
+ create_url = f"{self.endpoint}/repositories"
+
+ try:
+ response = requests.post(
+ create_url,
+ json=repository_config,
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {
+ "success": True,
+ "repository_id": repository_config.get("id", "new_repository")
+ }
+ except Exception as e:
+ self.logger.error(f"Create repository failed: {e}")
+ raise ProcessingError(f"Create repository failed: {e}")
+
+ def begin_transaction(self, **options) -> str:
+ """
+ Start transaction for batch operations.
+
+ Args:
+ **options: Transaction options
+
+ Returns:
+ Transaction ID
+ """
+ # RDF4J transaction support
+ transaction_url = f"{self.endpoint}/repositories/{self.repository_id}/transactions"
+
+ try:
+ response = requests.post(
+ transaction_url,
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+ transaction_id = response.headers.get("Location", "").split("/")[-1]
+
+ return transaction_id
+ except Exception as e:
+ self.logger.error(f"Begin transaction failed: {e}")
+ raise ProcessingError(f"Begin transaction failed: {e}")
+
+ def execute_sparql(
+ self,
+ query: str,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ **options: Additional options
+
+ Returns:
+ Query results
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to RDF4J")
+
+ sparql_endpoint = self._get_sparql_endpoint()
+
+ try:
+ response = requests.post(
+ sparql_endpoint,
+ data={"query": query},
+ headers={"Accept": "application/sparql-results+json"},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ result_data = response.json()
+
+ return {
+ "success": True,
+ "bindings": result_data.get("results", {}).get("bindings", []),
+ "variables": result_data.get("head", {}).get("vars", []),
+ "metadata": {
+ "query": query,
+ "endpoint": sparql_endpoint
+ }
+ }
+ except Exception as e:
+ self.logger.error(f"SPARQL query failed: {e}")
+ raise ProcessingError(f"SPARQL query failed: {e}")
+
+ def add_triples(
+ self,
+ triples: List[Triple],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Add triples to repository.
+
+ Args:
+ triples: List of triples
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to RDF4J")
+
+ update_endpoint = self._get_update_endpoint()
+
+ # Convert triples to RDF format
+ rdf_data = self._triples_to_ntriples(triples)
+
+ try:
+ response = requests.post(
+ update_endpoint,
+ data=rdf_data,
+ headers={"Content-Type": "application/n-triples"},
+ timeout=self.timeout * 2,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {
+ "success": True,
+ "triples_added": len(triples)
+ }
+ except Exception as e:
+ self.logger.error(f"Add triples failed: {e}")
+ raise ProcessingError(f"Add triples failed: {e}")
+
+ def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Add single triple."""
+ return self.add_triples([triple], **options)
+
+ def get_triples(
+ self,
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ **options
+ ) -> List[Triple]:
+ """Get triples matching criteria."""
+ # Build SPARQL query
+ where_clauses = []
+ if subject:
+ where_clauses.append(f"?s = <{subject}>")
+ if predicate:
+ where_clauses.append(f"?p = <{predicate}>")
+ if object:
+ where_clauses.append(f"?o = <{object}>")
+
+ where_clause = " ".join(where_clauses) if where_clauses else ""
+ query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"
+
+ result = self.execute_sparql(query, **options)
+
+ # Convert bindings to triples
+ triples = []
+ for binding in result["bindings"]:
+ triples.append(Triple(
+ subject=binding.get("s", {}).get("value", ""),
+ predicate=binding.get("p", {}).get("value", ""),
+ object=binding.get("o", {}).get("value", ""),
+ metadata={"source": "rdf4j"}
+ ))
+
+ return triples
+
+ def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Delete triple."""
+ if not self.connected:
+ raise ProcessingError("Not connected to RDF4J")
+
+ update_endpoint = self._get_update_endpoint()
+
+ # Use SPARQL DELETE
+ query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+
+ try:
+ response = requests.post(
+ update_endpoint,
+ data={"update": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout,
+ auth=(self.username, self.password) if self.username and self.password else None
+ )
+
+ response.raise_for_status()
+
+ return {"success": True}
+ except Exception as e:
+ self.logger.error(f"Delete triple failed: {e}")
+ raise ProcessingError(f"Delete triple failed: {e}")
+
+ def _triples_to_ntriples(self, triples: List[Triple]) -> str:
+ """Convert triples to N-Triples format."""
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return "\n".join(lines)
diff --git a/libs/semantica/triple_store/triple_manager.py b/libs/semantica/triple_store/triple_manager.py
index d8ec90b4..6de99d90 100644
--- a/libs/semantica/triple_store/triple_manager.py
+++ b/libs/semantica/triple_store/triple_manager.py
@@ -5,10 +5,307 @@ This module provides CRUD operations for RDF triples
and triple store management.
"""
-# TODO: Implement triple management
-# - CRUD operations for RDF triples
-# - Batch operations and bulk loading
-# - Triple validation and consistency
-# - Transaction support
-# - Performance optimization
-# - Error handling and recovery
+from typing import Any, Dict, List, Optional
+from dataclasses import dataclass, field
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+
+@dataclass
+class TripleStore:
+ """Triple store configuration."""
+ store_id: str
+ store_type: str # "blazegraph", "jena", "rdf4j", "virtuoso"
+ endpoint: str
+ config: Dict[str, Any] = field(default_factory=dict)
+ connected: bool = False
+
+
+class TripleManager:
+ """
+ Triple store management system.
+
+ • CRUD operations for RDF triples
+ • Batch operations and bulk loading
+ • Triple validation and consistency
+ • Transaction support
+ • Performance optimization
+ • Error handling and recovery
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize triple manager.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options:
+ - default_store: Default triple store to use
+ """
+ self.logger = get_logger("triple_manager")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.stores: Dict[str, TripleStore] = {}
+ self.default_store_id = self.config.get("default_store")
+
+ def register_store(
+ self,
+ store_id: str,
+ store_type: str,
+ endpoint: str,
+ **config
+ ) -> TripleStore:
+ """
+ Register a triple store.
+
+ Args:
+ store_id: Store identifier
+ store_type: Store type
+ endpoint: Store endpoint URL
+ **config: Additional configuration
+
+ Returns:
+ Registered store
+ """
+ store = TripleStore(
+ store_id=store_id,
+ store_type=store_type,
+ endpoint=endpoint,
+ config=config
+ )
+
+ self.stores[store_id] = store
+
+ if not self.default_store_id:
+ self.default_store_id = store_id
+
+ self.logger.info(f"Registered triple store: {store_id} ({store_type})")
+
+ return store
+
+ def add_triple(
+ self,
+ triple: Triple,
+ store_id: Optional[str] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Add single triple to store.
+
+ Args:
+ triple: Triple to add
+ store_id: Store identifier (uses default if not provided)
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ store = self._get_store(store_id)
+
+ # Validate triple
+ if not self._validate_triple(triple):
+ raise ValidationError("Invalid triple")
+
+ # Add to store (delegates to adapter)
+ try:
+ adapter = self._get_adapter(store)
+ result = adapter.add_triple(triple, **options)
+
+ return {
+ "success": True,
+ "store_id": store.store_id,
+ "triple": triple,
+ **result
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to add triple: {e}")
+ raise ProcessingError(f"Failed to add triple: {e}")
+
+ def add_triples(
+ self,
+ triples: List[Triple],
+ store_id: Optional[str] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Add multiple triples to store.
+
+ Args:
+ triples: List of triples
+ store_id: Store identifier
+ **options: Additional options:
+ - batch_size: Batch size for bulk operations
+ - validate: Validate triples before adding
+
+ Returns:
+ Operation status
+ """
+ store = self._get_store(store_id)
+
+ # Validate triples
+ if options.get("validate", True):
+ valid_triples = [t for t in triples if self._validate_triple(t)]
+ invalid_count = len(triples) - len(valid_triples)
+ if invalid_count > 0:
+ self.logger.warning(f"{invalid_count} invalid triples filtered out")
+ else:
+ valid_triples = triples
+
+ # Add to store
+ try:
+ adapter = self._get_adapter(store)
+ batch_size = options.get("batch_size", 1000)
+
+ results = []
+ for i in range(0, len(valid_triples), batch_size):
+ batch = valid_triples[i:i + batch_size]
+ result = adapter.add_triples(batch, **options)
+ results.append(result)
+
+ return {
+ "success": True,
+ "store_id": store.store_id,
+ "total_triples": len(valid_triples),
+ "batches": len(results),
+ "results": results
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to add triples: {e}")
+ raise ProcessingError(f"Failed to add triples: {e}")
+
+ def get_triple(
+ self,
+ subject: str,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ store_id: Optional[str] = None,
+ **options
+ ) -> List[Triple]:
+ """
+ Get triples matching criteria.
+
+ Args:
+ subject: Subject URI
+ predicate: Optional predicate URI
+ object: Optional object URI
+ store_id: Store identifier
+ **options: Additional options
+
+ Returns:
+ List of matching triples
+ """
+ store = self._get_store(store_id)
+
+ try:
+ adapter = self._get_adapter(store)
+ return adapter.get_triples(subject, predicate, object, **options)
+ except Exception as e:
+ self.logger.error(f"Failed to get triples: {e}")
+ raise ProcessingError(f"Failed to get triples: {e}")
+
+ def delete_triple(
+ self,
+ triple: Triple,
+ store_id: Optional[str] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Delete triple from store.
+
+ Args:
+ triple: Triple to delete
+ store_id: Store identifier
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ store = self._get_store(store_id)
+
+ try:
+ adapter = self._get_adapter(store)
+ result = adapter.delete_triple(triple, **options)
+
+ return {
+ "success": True,
+ "store_id": store.store_id,
+ **result
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to delete triple: {e}")
+ raise ProcessingError(f"Failed to delete triple: {e}")
+
+ def update_triple(
+ self,
+ old_triple: Triple,
+ new_triple: Triple,
+ store_id: Optional[str] = None,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Update triple in store.
+
+ Args:
+ old_triple: Original triple
+ new_triple: Updated triple
+ store_id: Store identifier
+ **options: Additional options
+
+ Returns:
+ Operation status
+ """
+ # Delete old and add new
+ self.delete_triple(old_triple, store_id, **options)
+ return self.add_triple(new_triple, store_id, **options)
+
+ def _validate_triple(self, triple: Triple) -> bool:
+ """Validate triple structure."""
+ if not triple.subject or not triple.predicate or not triple.object:
+ return False
+
+ if triple.confidence < 0 or triple.confidence > 1:
+ return False
+
+ return True
+
+ def _get_store(self, store_id: Optional[str] = None) -> TripleStore:
+ """Get store by ID."""
+ store_id = store_id or self.default_store_id
+
+ if not store_id:
+ raise ValidationError("No store specified and no default store configured")
+
+ if store_id not in self.stores:
+ raise ValidationError(f"Store not found: {store_id}")
+
+ return self.stores[store_id]
+
+ def _get_adapter(self, store: TripleStore) -> Any:
+ """Get adapter for store type."""
+ store_type = store.store_type.lower()
+
+ if store_type == "blazegraph":
+ from .blazegraph_adapter import BlazegraphAdapter
+ return BlazegraphAdapter(endpoint=store.endpoint, **store.config)
+ elif store_type == "jena":
+ from .jena_adapter import JenaAdapter
+ return JenaAdapter(**store.config)
+ elif store_type == "rdf4j":
+ from .rdf4j_adapter import RDF4JAdapter
+ return RDF4JAdapter(endpoint=store.endpoint, **store.config)
+ elif store_type == "virtuoso":
+ from .virtuoso_adapter import VirtuosoAdapter
+ return VirtuosoAdapter(endpoint=store.endpoint, **store.config)
+ else:
+ raise ValidationError(f"Unsupported store type: {store_type}")
+
+ def get_store(self, store_id: str) -> Optional[TripleStore]:
+ """Get store by ID."""
+ return self.stores.get(store_id)
+
+ def list_stores(self) -> List[str]:
+ """List all store IDs."""
+ return list(self.stores.keys())
diff --git a/libs/semantica/triple_store/virtuoso_adapter.py b/libs/semantica/triple_store/virtuoso_adapter.py
index 1c798a7d..e0db523e 100644
--- a/libs/semantica/triple_store/virtuoso_adapter.py
+++ b/libs/semantica/triple_store/virtuoso_adapter.py
@@ -5,10 +5,324 @@ This module provides Virtuoso integration for RDF storage
and SPARQL querying.
"""
-# TODO: Implement Virtuoso adapter
-# - Virtuoso connection and authentication
-# - SPARQL query execution
-# - Bulk data loading and management
-# - Graph and namespace management
-# - Performance optimization
-# - Error handling and recovery
+from typing import Any, Dict, List, Optional
+import requests
+from urllib.parse import urljoin
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..semantic_extract.triple_extractor import Triple
+
+
+class VirtuosoAdapter:
+ """
+ Virtuoso RDF store adapter.
+
+ • Virtuoso connection and authentication
+ • SPARQL query execution
+ • Bulk data loading and management
+ • Graph and namespace management
+ • Performance optimization
+ • Error handling and recovery
+ """
+
+ def __init__(self, endpoint: str, **config):
+ """
+ Initialize Virtuoso adapter.
+
+ Args:
+ endpoint: Virtuoso endpoint URL
+ **config: Additional configuration:
+ - username: Username for authentication
+ - password: Password for authentication
+ - timeout: Request timeout (default: 30)
+ - graph: Default graph URI
+ """
+ self.logger = get_logger("virtuoso_adapter")
+ self.config = config
+
+ self.endpoint = endpoint.rstrip('/')
+ self.username = config.get("username", "dba")
+ self.password = config.get("password", "dba")
+ self.timeout = config.get("timeout", 30)
+ self.default_graph = config.get("graph", "")
+
+ self.connected = False
+ self._connect()
+
+ def _connect(self) -> None:
+ """Connect to Virtuoso instance."""
+ try:
+ # Test connection with simple query
+ sparql_endpoint = self._get_sparql_endpoint()
+ response = requests.get(
+ sparql_endpoint,
+ params={"query": "SELECT * WHERE { ?s ?p ?o } LIMIT 1"},
+ timeout=self.timeout,
+ auth=(self.username, self.password)
+ )
+
+ if response.status_code == 200:
+ self.connected = True
+ self.logger.info(f"Connected to Virtuoso: {self.endpoint}")
+ else:
+ self.logger.warning(f"Virtuoso connection test failed: {response.status_code}")
+ except Exception as e:
+ self.logger.warning(f"Could not connect to Virtuoso: {e}")
+
+ def _get_sparql_endpoint(self) -> str:
+ """Get SPARQL endpoint URL."""
+ return urljoin(self.endpoint, "/sparql")
+
+ def _get_sparql_update_endpoint(self) -> str:
+ """Get SPARQL Update endpoint URL."""
+ return urljoin(self.endpoint, "/sparql-auth")
+
+ def connect_cluster(
+ self,
+ cluster_config: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Connect to Virtuoso cluster.
+
+ Args:
+ cluster_config: Cluster configuration
+ **options: Additional options
+
+ Returns:
+ Connection status
+ """
+ # Virtuoso cluster connection
+ # This would typically involve multiple endpoints
+ endpoints = cluster_config.get("endpoints", [self.endpoint])
+
+ connections = []
+ for endpoint in endpoints:
+ try:
+ adapter = VirtuosoAdapter(endpoint, **cluster_config)
+ if adapter.connected:
+ connections.append(endpoint)
+ except Exception as e:
+ self.logger.warning(f"Failed to connect to {endpoint}: {e}")
+
+ return {
+ "success": len(connections) > 0,
+ "connected_endpoints": connections,
+ "total_endpoints": len(endpoints)
+ }
+
+ def execute_sparql(
+ self,
+ query: str,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Execute SPARQL query.
+
+ Args:
+ query: SPARQL query string
+ **options: Additional options
+
+ Returns:
+ Query results
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to Virtuoso")
+
+ sparql_endpoint = self._get_sparql_endpoint()
+
+ try:
+ response = requests.get(
+ sparql_endpoint,
+ params={"query": query, "default-graph-uri": self.default_graph} if self.default_graph else {"query": query},
+ headers={"Accept": "application/sparql-results+json"},
+ timeout=self.timeout,
+ auth=(self.username, self.password)
+ )
+
+ response.raise_for_status()
+
+ result_data = response.json()
+
+ return {
+ "success": True,
+ "bindings": result_data.get("results", {}).get("bindings", []),
+ "variables": result_data.get("head", {}).get("vars", []),
+ "metadata": {
+ "query": query,
+ "endpoint": sparql_endpoint
+ }
+ }
+ except Exception as e:
+ self.logger.error(f"SPARQL query failed: {e}")
+ raise ProcessingError(f"SPARQL query failed: {e}")
+
+ def optimize_queries(
+ self,
+ queries: List[str],
+ **options
+ ) -> List[str]:
+ """
+ Optimize query performance.
+
+ Args:
+ queries: List of SPARQL queries
+ **options: Optimization options
+
+ Returns:
+ List of optimized queries
+ """
+ optimized = []
+
+ for query in queries:
+ # Basic optimization: remove unnecessary whitespace
+ opt_query = " ".join(query.split())
+
+ # Add LIMIT if not present (for SELECT queries)
+ if "SELECT" in query.upper() and "LIMIT" not in query.upper():
+ opt_query += " LIMIT 1000"
+
+ optimized.append(opt_query)
+
+ return optimized
+
+ def bulk_load(
+ self,
+ triples: List[Triple],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Load triples in bulk.
+
+ Args:
+ triples: List of triples
+ **options: Additional options:
+ - graph: Named graph URI
+ - format: RDF format (turtle, ntriples)
+
+ Returns:
+ Load status
+ """
+ if not self.connected:
+ raise ProcessingError("Not connected to Virtuoso")
+
+ graph = options.get("graph", self.default_graph)
+ format = options.get("format", "turtle")
+
+ # Convert triples to RDF
+ rdf_data = self._triples_to_rdf(triples, format)
+
+ # Use SPARQL INSERT for bulk loading
+ update_endpoint = self._get_sparql_update_endpoint()
+
+ graph_clause = f"GRAPH <{graph}>" if graph else ""
+ insert_data = self._build_insert_data(triples)
+ query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"
+
+ try:
+ response = requests.post(
+ update_endpoint,
+ data={"query": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout * 2,
+ auth=(self.username, self.password)
+ )
+
+ response.raise_for_status()
+
+ return {
+ "success": True,
+ "triples_loaded": len(triples),
+ "graph": graph
+ }
+ except Exception as e:
+ self.logger.error(f"Bulk load failed: {e}")
+ raise ProcessingError(f"Bulk load failed: {e}")
+
+ def _triples_to_rdf(self, triples: List[Triple], format: str = "turtle") -> str:
+ """Convert triples to RDF format."""
+ if format == "turtle":
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return "\n".join(lines)
+ else: # ntriples
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return "\n".join(lines)
+
+ def _build_insert_data(self, triples: List[Triple]) -> str:
+ """Build SPARQL INSERT DATA clause."""
+ lines = []
+ for triple in triples:
+ lines.append(f"<{triple.subject}> <{triple.predicate}> <{triple.object}> .")
+ return " ".join(lines)
+
+ def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Add single triple."""
+ return self.bulk_load([triple], **options)
+
+ def add_triples(self, triples: List[Triple], **options) -> Dict[str, Any]:
+ """Add multiple triples."""
+ return self.bulk_load(triples, **options)
+
+ def get_triples(
+ self,
+ subject: Optional[str] = None,
+ predicate: Optional[str] = None,
+ object: Optional[str] = None,
+ **options
+ ) -> List[Triple]:
+ """Get triples matching criteria."""
+ # Build SPARQL query
+ where_clauses = []
+ if subject:
+ where_clauses.append(f"?s = <{subject}>")
+ if predicate:
+ where_clauses.append(f"?p = <{predicate}>")
+ if object:
+ where_clauses.append(f"?o = <{object}>")
+
+ where_clause = " ".join(where_clauses) if where_clauses else ""
+ query = f"SELECT ?s ?p ?o WHERE {{ ?s ?p ?o {where_clause} }}"
+
+ result = self.execute_sparql(query, **options)
+
+ # Convert bindings to triples
+ triples = []
+ for binding in result["bindings"]:
+ triples.append(Triple(
+ subject=binding.get("s", {}).get("value", ""),
+ predicate=binding.get("p", {}).get("value", ""),
+ object=binding.get("o", {}).get("value", ""),
+ metadata={"source": "virtuoso"}
+ ))
+
+ return triples
+
+ def delete_triple(self, triple: Triple, **options) -> Dict[str, Any]:
+ """Delete triple."""
+ if not self.connected:
+ raise ProcessingError("Not connected to Virtuoso")
+
+ update_endpoint = self._get_sparql_update_endpoint()
+
+ query = f"DELETE DATA {{ <{triple.subject}> <{triple.predicate}> <{triple.object}> }}"
+
+ try:
+ response = requests.post(
+ update_endpoint,
+ data={"query": query},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=self.timeout,
+ auth=(self.username, self.password)
+ )
+
+ response.raise_for_status()
+
+ return {"success": True}
+ except Exception as e:
+ self.logger.error(f"Delete triple failed: {e}")
+ raise ProcessingError(f"Delete triple failed: {e}")