Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: add ArangoDB AQL Export Support

Tiberiu Sabău297f5b947314
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.py
index 91eb81ef..934d8543 100644
--- a/semantica/export/__init__.py
+++ b/semantica/export/__init__.py
@@ -3,20 +3,25 @@ Export and Reporting Module
This module provides comprehensive export and reporting capabilities for the
Semantica framework, supporting multiple formats and use cases including RDF,
-JSON, CSV, Graph, YAML, OWL, Vector, and LPG (Labeled Property Graph) formats.
+JSON, CSV, Graph, YAML, OWL, Vector, LPG (Labeled Property Graph), and
+ArangoDB AQL formats.
Algorithms Used:
RDF Export:
- - RDF Serialization: Multiple format serialization (Turtle, RDF/XML, JSON-LD, N-Triples, N3)
- - Namespace Management: Namespace registration, conflict resolution, declaration generation
- - RDF Validation: RDF syntax validation, triplet validation, namespace validation
+ - RDF Serialization: Multiple format serialization (Turtle, RDF/XML,
+ JSON-LD, N-Triples, N3)
+ - Namespace Management: Namespace registration, conflict resolution,
+ declaration generation
+ - RDF Validation: RDF syntax validation, triplet validation,
+ namespace validation
- URI Generation: Hash-based and text-based URI assignment for RDF resources
- Triplet Extraction: Entity and relationship to RDF triplet conversion
- Format Conversion: Cross-format RDF conversion algorithms
LPG (Labeled Property Graph) Export:
- - LPG Serialization: Labeled Property Graph format for Neo4j, Memgraph, and similar databases
+ - LPG Serialization: Labeled Property Graph format for Neo4j, Memgraph,
+ and similar databases
- Node Label Assignment: Entity type to node label mapping
- Relationship Type Mapping: Relationship type to edge label conversion
- Property Serialization: Entity and relationship properties to LPG property format
@@ -24,11 +29,21 @@ LPG (Labeled Property Graph) Export:
- Batch Node/Relationship Export: Efficient batch processing for large graphs
- Index Generation: Index and constraint generation for graph databases
+ArangoDB AQL Export:
+ - AQL Serialization: AQL INSERT statements for ArangoDB multi-model databases
+ - Vertex Collection Export: Entity to vertex collection conversion
+ - Edge Collection Export: Relationship to edge collection conversion
+ - Key Sanitization: Automatic sanitization of keys for ArangoDB compliance
+ - Batch Insert Generation: Efficient batch INSERT operations for large graphs
+ - Configurable Collections: Support for custom vertex and edge collection names
+ - Property Preservation: Full preservation of entity and relationship properties
+
JSON/JSON-LD Export:
- JSON Serialization: Standard JSON serialization with configurable indentation
- JSON-LD Context Management: @context generation and management
- Knowledge Graph Serialization: Graph structure to JSON/JSON-LD conversion
- - Metadata Embedding: Provenance and metadata serialization in JSON structure
+ - Metadata Embedding: Provenance and metadata serialization in JSON
+ structure
- Pretty Printing: Formatted JSON output with indentation
CSV Export:
@@ -36,8 +51,10 @@ CSV Export:
- Field Extraction: Dynamic field name extraction from data structures
- Delimiter Handling: Configurable delimiter support (comma, tab, semicolon)
- Header Generation: Automatic CSV header row generation
- - Metadata Serialization: JSON string serialization for complex metadata fields
- - Multi-file Export: Knowledge graph split into multiple CSV files (entities, relationships)
+ - Metadata Serialization: JSON string serialization for complex
+ metadata fields
+ - Multi-file Export: Knowledge graph split into multiple CSV files
+ (entities, relationships)
Graph Export:
- GraphML Serialization: GraphML format generation for graph visualization tools
@@ -57,7 +74,8 @@ OWL Export:
- Turtle Serialization: OWL in Turtle format
- Class Hierarchy Export: Class definition and hierarchy serialization
- Property Export: Object and data property definition export
- - OWL 2.0 Feature Support: Advanced OWL features (cardinality, restrictions, etc.)
+ - OWL 2.0 Feature Support: Advanced OWL features (cardinality,
+ restrictions, etc.)
- Ontology Validation: OWL syntax and semantic validation
Vector Export:
@@ -75,7 +93,8 @@ Report Generation:
- Section Organization: Hierarchical report section organization
Key Features:
- - Multiple export formats (RDF, JSON, CSV, Graph, YAML, OWL, Vector, LPG)
+ - Multiple export formats (RDF, JSON, CSV, Graph, YAML, OWL, Vector,
+ LPG, ArangoDB AQL)
- Knowledge graph export with format auto-detection
- Report generation (HTML, Markdown, JSON, Text)
- Vector store integration
@@ -92,7 +111,10 @@ Main Classes:
- YAMLExporter: YAML format export for semantic networks
- OWLExporter: OWL format export for ontologies
- VectorExporter: Vector embedding export for vector stores
- - LPGExporter: LPG format export for Neo4j, Memgraph, and similar databases
+ - LPGExporter: LPG format export for Neo4j, Memgraph, and similar
+ databases
+ - ArangoAQLExporter: ArangoDB AQL format export for multi-model
+ databases
- ReportGenerator: Report generation (HTML, Markdown, JSON, Text)
- MethodRegistry: Registry for custom export methods
- ExportConfig: Configuration manager for export module
@@ -120,17 +142,21 @@ Author: Semantica Contributors
License: MIT
"""
-from .arrow_exporter import ArrowExporter
+from .arango_aql_exporter import ArangoAQLExporter
from .config import ExportConfig, export_config
+
try:
from .arrow_exporter import ArrowExporter
except ImportError:
- # ArrowExporter is not available in CI environment - create a dummy class
+ # ArrowExporter is not available in CI environment - dummy class
class ArrowExporter:
def __init__(self, *args, **kwargs):
pass
+
def __getattr__(self, name):
return lambda *args, **kwargs: f"Mock ArrowExporter.{name}"
+
+
from .csv_exporter import CSVExporter
from .graph_exporter import GraphExporter
from .json_exporter import JSONExporter
@@ -159,6 +185,7 @@ from .yaml_exporter import SemanticNetworkYAMLExporter, YAMLSchemaExporter
__all__ = [
# Core Exporters
"ArrowExporter",
+ "ArangoAQLExporter",
"RDFExporter",
"RDFSerializer",
"RDFValidator",
diff --git a/semantica/export/arango_aql_exporter.py b/semantica/export/arango_aql_exporter.py
new file mode 100644
index 00000000..a0aec52e
--- /dev/null
+++ b/semantica/export/arango_aql_exporter.py
@@ -0,0 +1,584 @@
+"""
+ArangoDB AQL Export Module
+
+This module provides comprehensive AQL export capabilities for the Semantica framework,
+enabling export to ArangoDB multi-model graph databases.
+
+Key Features:
+ - AQL format export for ArangoDB
+ - INSERT statement generation for vertex and edge collections
+ - Configurable collection names
+ - Entity and relationship identifier preservation
+ - Batch insert support for performance
+ - Proper string escaping and special character handling
+
+Example Usage:
+ >>> from semantica.export import ArangoAQLExporter
+ >>> exporter = ArangoAQLExporter()
+ >>> exporter.export_knowledge_graph(kg, "output.aql")
+ >>> # With custom collection names
+ >>> exporter = ArangoAQLExporter(
+ ... vertex_collection="nodes",
+ ... edge_collection="links"
+ ... )
+ >>> exporter.export(kg, "graph.aql")
+"""
+
+import json
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.helpers import ensure_directory
+from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
+
+
+class ArangoAQLExporter:
+ """
+ ArangoDB AQL exporter for knowledge graphs.
+
+ This class provides comprehensive AQL export functionality for knowledge graphs,
+ supporting export to ArangoDB multi-model databases via AQL INSERT statements.
+
+ Features:
+ - AQL INSERT statement generation for vertices and edges
+ - Configurable collection names
+ - Entity and relationship identifier preservation
+ - Batch insert support for performance
+ - Proper string escaping and special character handling
+ - Support for nested properties via JSON serialization
+
+ Example Usage:
+ >>> exporter = ArangoAQLExporter(
+ ... vertex_collection="entities",
+ ... edge_collection="relationships"
+ ... )
+ >>> exporter.export_knowledge_graph(kg, "output.aql")
+ """
+
+ def __init__(
+ self,
+ vertex_collection: str = "vertices",
+ edge_collection: str = "edges",
+ batch_size: int = 1000,
+ include_collection_creation: bool = True,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """
+ Initialize ArangoDB AQL exporter.
+
+ Sets up the exporter with collection names and batch processing options.
+
+ Args:
+ vertex_collection: Name of the vertex collection
+ (default: "vertices")
+ edge_collection: Name of the edge collection (default: "edges")
+ batch_size: Batch size for INSERT operations (default: 1000)
+ include_collection_creation: Whether to include collection
+ creation statements (default: True)
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
+ """
+ self.logger = get_logger("arango_aql_exporter")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # AQL export configuration
+ self.vertex_collection = vertex_collection
+ self.edge_collection = edge_collection
+ self.batch_size = batch_size
+ self.include_collection_creation = include_collection_creation
+
+ # Initialize progress tracker
+ self.progress_tracker = get_progress_tracker()
+
+ self.logger.debug(
+ f"ArangoDB AQL exporter initialized: "
+ f"vertex_collection={vertex_collection}, "
+ f"edge_collection={edge_collection}, batch_size={batch_size}"
+ )
+
+ def export(
+ self, knowledge_graph: Dict[str, Any], file_path: Union[str, Path], **options
+ ) -> None:
+ """
+ Export knowledge graph to ArangoDB AQL format.
+
+ This method exports a knowledge graph to AQL INSERT statements that can
+ be imported into ArangoDB multi-model databases.
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - nodes: List of node dictionaries (optional, alternative to
+ entities)
+ - edges: List of edge dictionaries (optional, alternative to
+ relationships)
+ file_path: Output AQL file path
+ **options: Additional export options:
+ - vertex_collection: Override default vertex collection name
+ - edge_collection: Override default edge collection name
+
+ Example:
+ >>> kg = {
+ ... "entities": [...],
+ ... "relationships": [...]
+ ... }
+ >>> exporter.export(kg, "graph.aql")
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ tracking_id = self.progress_tracker.start_tracking(
+ file=str(file_path),
+ module="export",
+ submodule="ArangoAQLExporter",
+ message=f"Exporting knowledge graph to ArangoDB AQL format: {file_path}",
+ )
+
+ try:
+ # Override collection names if provided in options
+ vertex_collection = options.pop("vertex_collection", self.vertex_collection)
+ edge_collection = options.pop("edge_collection", self.edge_collection)
+
+ # Generate AQL statements
+ aql_statements = self._generate_aql_statements(
+ knowledge_graph, vertex_collection, edge_collection, **options
+ )
+
+ # Write to file
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("\n".join(aql_statements))
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Exported {len(aql_statements)} AQL statements",
+ )
+ self.logger.info(
+ f"Exported knowledge graph to ArangoDB AQL format: " f"{file_path}"
+ )
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def _generate_aql_statements(
+ self,
+ knowledge_graph: Dict[str, Any],
+ vertex_collection: str,
+ edge_collection: str,
+ **options,
+ ) -> List[str]:
+ """
+ Generate AQL INSERT statements from knowledge graph.
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary
+ vertex_collection: Vertex collection name
+ edge_collection: Edge collection name
+ **options: Additional options
+
+ Returns:
+ List of AQL statement strings
+ """
+ statements = []
+
+ # Add collection creation statements if requested
+ if self.include_collection_creation:
+ statements.extend(
+ self._generate_collection_creation(vertex_collection, edge_collection)
+ )
+
+ # Extract entities and relationships
+ entities = knowledge_graph.get("entities", [])
+ relationships = knowledge_graph.get("relationships", [])
+ nodes = knowledge_graph.get("nodes", entities)
+ edges = knowledge_graph.get("edges", relationships)
+
+ # Use nodes/edges if entities/relationships are empty
+ if not entities and nodes:
+ entities = nodes
+ if not relationships and edges:
+ relationships = edges
+
+ # Generate vertex INSERT statements
+ vertex_statements = self._generate_vertex_inserts(entities, vertex_collection)
+ statements.extend(vertex_statements)
+
+ # Generate edge INSERT statements
+ edge_statements = self._generate_edge_inserts(
+ relationships, edge_collection, vertex_collection
+ )
+ statements.extend(edge_statements)
+
+ return statements
+
+ def _generate_collection_creation(
+ self, vertex_collection: str, edge_collection: str
+ ) -> List[str]:
+ """
+ Generate AQL collection creation statements.
+
+ Args:
+ vertex_collection: Vertex collection name
+ edge_collection: Edge collection name
+
+ Returns:
+ List of collection creation statements
+ """
+ statements = [
+ "// Create vertex collection if it doesn't exist",
+ f"// db._createDocumentCollection('{vertex_collection}');",
+ "",
+ "// Create edge collection if it doesn't exist",
+ f"// db._createEdgeCollection('{edge_collection}');",
+ "",
+ ]
+ return statements
+
+ def _generate_vertex_inserts(
+ self, vertices: List[Dict[str, Any]], collection: str
+ ) -> List[str]:
+ """
+ Generate AQL INSERT statements for vertices.
+
+ Args:
+ vertices: List of vertex/entity dictionaries
+ collection: Vertex collection name
+
+ Returns:
+ List of AQL INSERT statements
+ """
+ statements = []
+
+ # Add header comment
+ statements.append(f"// Inserting {len(vertices)} vertices into {collection}")
+ statements.append("")
+
+ # Process vertices in batches
+ for i in range(0, len(vertices), self.batch_size):
+ batch = vertices[i : i + self.batch_size]
+ batch_statement = self._create_vertex_batch_insert(batch, collection)
+ statements.append(batch_statement)
+ statements.append("")
+
+ return statements
+
+ def _create_vertex_batch_insert(
+ self, vertices: List[Dict[str, Any]], collection: str
+ ) -> str:
+ """
+ Create a batch INSERT statement for vertices.
+
+ Args:
+ vertices: Batch of vertex dictionaries
+ collection: Vertex collection name
+
+ Returns:
+ AQL INSERT statement
+ """
+ if not vertices:
+ return ""
+
+ # Build document list
+ documents = []
+ for idx, vertex in enumerate(vertices):
+ doc = self._convert_vertex_to_document(vertex, idx)
+ documents.append(doc)
+
+ # Format as AQL
+ docs_json = json.dumps(documents, indent=2, ensure_ascii=False)
+ statement = f"FOR doc IN {docs_json}\n INSERT doc INTO {collection}"
+
+ return statement
+
+ def _convert_vertex_to_document(
+ self, vertex: Dict[str, Any], idx: int
+ ) -> Dict[str, Any]:
+ """
+ Convert a vertex/entity to an ArangoDB document.
+
+ Args:
+ vertex: Vertex/entity dictionary
+ idx: Index for generating fallback IDs
+
+ Returns:
+ ArangoDB document dictionary
+ """
+ document = {}
+
+ # Set _key from id or generate one
+ vertex_id = vertex.get("id") or vertex.get("entity_id") or f"vertex_{idx}"
+ document["_key"] = self._sanitize_key(str(vertex_id))
+
+ # Add original ID if different from _key
+ if str(vertex_id) != document["_key"]:
+ document["original_id"] = str(vertex_id)
+
+ # Add type/label information
+ vertex_type = vertex.get("type") or vertex.get("entity_type", "Entity")
+ document["type"] = vertex_type
+
+ # Add name/label
+ label = (
+ vertex.get("label")
+ or vertex.get("name")
+ or vertex.get("text")
+ or document["_key"]
+ )
+ document["name"] = label
+
+ # Add all other properties
+ for key, value in vertex.items():
+ if key not in [
+ "_key",
+ "_id",
+ "_rev",
+ "id",
+ "entity_id",
+ "type",
+ "entity_type",
+ "label",
+ "name",
+ "text",
+ ]:
+ # Handle nested dictionaries and lists
+ if isinstance(value, (dict, list)):
+ document[key] = value
+ elif value is not None:
+ document[key] = value
+
+ return document
+
+ def _generate_edge_inserts(
+ self, edges: List[Dict[str, Any]], collection: str, vertex_collection: str
+ ) -> List[str]:
+ """
+ Generate AQL INSERT statements for edges.
+
+ Args:
+ edges: List of edge/relationship dictionaries
+ collection: Edge collection name
+ vertex_collection: Vertex collection name for _from/_to references
+
+ Returns:
+ List of AQL INSERT statements
+ """
+ statements = []
+
+ # Add header comment
+ statements.append(f"// Inserting {len(edges)} edges into {collection}")
+ statements.append("")
+
+ # Process edges in batches
+ for i in range(0, len(edges), self.batch_size):
+ batch = edges[i : i + self.batch_size]
+ batch_statement = self._create_edge_batch_insert(
+ batch, collection, vertex_collection
+ )
+ if batch_statement: # Only add non-empty statements
+ statements.append(batch_statement)
+ statements.append("")
+
+ return statements
+
+ def _create_edge_batch_insert(
+ self, edges: List[Dict[str, Any]], collection: str, vertex_collection: str
+ ) -> str:
+ """
+ Create a batch INSERT statement for edges.
+
+ Args:
+ edges: Batch of edge dictionaries
+ collection: Edge collection name
+ vertex_collection: Vertex collection name for _from/_to references
+
+ Returns:
+ AQL INSERT statement
+ """
+ # Build document list
+ documents = []
+ for idx, edge in enumerate(edges):
+ doc = self._convert_edge_to_document(edge, idx, vertex_collection)
+ if doc: # Only add valid edges
+ documents.append(doc)
+
+ if not documents:
+ return ""
+
+ # Format as AQL
+ docs_json = json.dumps(documents, indent=2, ensure_ascii=False)
+ statement = f"FOR doc IN {docs_json}\n INSERT doc INTO {collection}"
+
+ return statement
+
+ def _convert_edge_to_document(
+ self, edge: Dict[str, Any], idx: int, vertex_collection: str
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Convert an edge/relationship to an ArangoDB edge document.
+
+ Args:
+ edge: Edge/relationship dictionary
+ idx: Index for generating fallback IDs
+ vertex_collection: Vertex collection name for _from/_to references
+
+ Returns:
+ ArangoDB edge document dictionary, or None if source/target missing
+ """
+ # Extract source and target
+ source_id = edge.get("source") or edge.get("source_id")
+ target_id = edge.get("target") or edge.get("target_id")
+
+ if not source_id or not target_id:
+ self.logger.warning(
+ f"Skipping edge {idx}: missing source or target "
+ f"(source={source_id}, target={target_id})"
+ )
+ return None
+
+ document = {}
+
+ # Set _key from id or generate one
+ edge_id = edge.get("id") or edge.get("relationship_id") or f"edge_{idx}"
+ document["_key"] = self._sanitize_key(str(edge_id))
+
+ # Set _from and _to (required for edges in ArangoDB)
+ document["_from"] = f"{vertex_collection}/{self._sanitize_key(str(source_id))}"
+ document["_to"] = f"{vertex_collection}/{self._sanitize_key(str(target_id))}"
+
+ # Add original ID if different from _key
+ if str(edge_id) != document["_key"]:
+ document["original_id"] = str(edge_id)
+
+ # Add relationship type
+ rel_type = edge.get("type") or edge.get("relationship_type", "RELATED_TO")
+ document["type"] = rel_type
+
+ # Add all other properties
+ for key, value in edge.items():
+ if key not in [
+ "_key",
+ "_id",
+ "_rev",
+ "_from",
+ "_to",
+ "id",
+ "relationship_id",
+ "source",
+ "source_id",
+ "target",
+ "target_id",
+ "type",
+ "relationship_type",
+ ]:
+ # Handle nested dictionaries and lists
+ if isinstance(value, (dict, list)):
+ document[key] = value
+ elif value is not None:
+ document[key] = value
+
+ return document
+
+ def _sanitize_key(self, key: str) -> str:
+ """
+ Sanitize a key for use as ArangoDB _key.
+
+ ArangoDB _key must contain only alphanumeric characters, hyphens,
+ and underscores. It cannot start with an underscore (unless it's
+ a system collection).
+
+ Args:
+ key: Original key string
+
+ Returns:
+ Sanitized key string
+ """
+ # Replace invalid characters with underscores
+ sanitized = ""
+ for char in key:
+ if char.isalnum() or char in ("-", "_"):
+ sanitized += char
+ else:
+ sanitized += "_"
+
+ # Ensure key doesn't start with underscore
+ if sanitized.startswith("_"):
+ sanitized = "k" + sanitized
+
+ # Ensure key is not empty
+ if not sanitized:
+ sanitized = "key"
+
+ return sanitized
+
+ def export_knowledge_graph(
+ self, knowledge_graph: Dict[str, Any], file_path: Union[str, Path], **options
+ ) -> None:
+ """
+ Export knowledge graph to ArangoDB AQL format.
+
+ Convenience method that calls export().
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary
+ file_path: Output AQL file path
+ **options: Additional export options
+
+ Example:
+ >>> kg = {
+ ... "entities": [...],
+ ... "relationships": [...]
+ ... }
+ >>> exporter.export_knowledge_graph(kg, "output.aql")
+ """
+ self.export(knowledge_graph, file_path, **options)
+
+ def export_entities(
+ self, entities: List[Dict[str, Any]], file_path: Union[str, Path], **options
+ ) -> None:
+ """
+ Export entities to ArangoDB AQL format (vertices only).
+
+ Args:
+ entities: List of entity dictionaries
+ file_path: Output AQL file path
+ **options: Additional export options
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "type": "Person", "name": "Alice"},
+ ... {"id": "e2", "type": "Organization", "name": "Acme Corp"}
+ ... ]
+ >>> exporter.export_entities(entities, "entities.aql")
+ """
+ knowledge_graph = {"entities": entities, "relationships": []}
+ self.export(knowledge_graph, file_path, **options)
+
+ def export_relationships(
+ self,
+ relationships: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options,
+ ) -> None:
+ """
+ Export relationships to ArangoDB AQL format (edges only).
+
+ Args:
+ relationships: List of relationship dictionaries
+ file_path: Output AQL file path
+ **options: Additional export options
+
+ Example:
+ >>> relationships = [
+ ... {"id": "r1", "source": "e1", "target": "e2", "type": "WORKS_FOR"}
+ ... ]
+ >>> exporter.export_relationships(relationships, "relationships.aql")
+ """
+ knowledge_graph = {"entities": [], "relationships": relationships}
+ self.export(knowledge_graph, file_path, **options)
diff --git a/semantica/export/arrow_exporter.py b/semantica/export/arrow_exporter.py
index 92fbdd0c..d043a442 100644
--- a/semantica/export/arrow_exporter.py
+++ b/semantica/export/arrow_exporter.py
@@ -24,48 +24,74 @@ Author: Semantica Contributors
License: MIT
"""
+from __future__ import annotations
+
import json
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
-try:
+if TYPE_CHECKING:
import pyarrow as pa
+
+try:
+ import pyarrow as pa # noqa: F811
import pyarrow.ipc as ipc
+
ARROW_AVAILABLE = True
except ImportError:
ARROW_AVAILABLE = False
+ pa = None # Set pa to None when not available
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.helpers import ensure_directory
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-
# Explicit Arrow Schemas (no inference)
-ENTITY_SCHEMA = pa.schema([
- pa.field("id", pa.string(), nullable=False),
- pa.field("text", pa.string(), nullable=True),
- pa.field("type", pa.string(), nullable=True),
- pa.field("confidence", pa.float64(), nullable=True),
- pa.field("start", pa.int64(), nullable=True),
- pa.field("end", pa.int64(), nullable=True),
- pa.field("metadata", pa.struct([
- pa.field("keys", pa.list_(pa.string())),
- pa.field("values", pa.list_(pa.string()))
- ]), nullable=True),
-])
-
-RELATIONSHIP_SCHEMA = pa.schema([
- pa.field("id", pa.string(), nullable=False),
- pa.field("source_id", pa.string(), nullable=False),
- pa.field("target_id", pa.string(), nullable=False),
- pa.field("type", pa.string(), nullable=True),
- pa.field("confidence", pa.float64(), nullable=True),
- pa.field("metadata", pa.struct([
- pa.field("keys", pa.list_(pa.string())),
- pa.field("values", pa.list_(pa.string()))
- ]), nullable=True),
-])
+if ARROW_AVAILABLE:
+ ENTITY_SCHEMA = pa.schema(
+ [
+ pa.field("id", pa.string(), nullable=False),
+ pa.field("text", pa.string(), nullable=True),
+ pa.field("type", pa.string(), nullable=True),
+ pa.field("confidence", pa.float64(), nullable=True),
+ pa.field("start", pa.int64(), nullable=True),
+ pa.field("end", pa.int64(), nullable=True),
+ pa.field(
+ "metadata",
+ pa.struct(
+ [
+ pa.field("keys", pa.list_(pa.string())),
+ pa.field("values", pa.list_(pa.string())),
+ ]
+ ),
+ nullable=True,
+ ),
+ ]
+ )
+
+ RELATIONSHIP_SCHEMA = pa.schema(
+ [
+ pa.field("id", pa.string(), nullable=False),
+ pa.field("source_id", pa.string(), nullable=False),
+ pa.field("target_id", pa.string(), nullable=False),
+ pa.field("type", pa.string(), nullable=True),
+ pa.field("confidence", pa.float64(), nullable=True),
+ pa.field(
+ "metadata",
+ pa.struct(
+ [
+ pa.field("keys", pa.list_(pa.string())),
+ pa.field("values", pa.list_(pa.string())),
+ ]
+ ),
+ nullable=True,
+ ),
+ ]
+ )
+else:
+ ENTITY_SCHEMA = None
+ RELATIONSHIP_SCHEMA = None
class ArrowExporter:
@@ -131,9 +157,7 @@ class ArrowExporter:
if not self.progress_tracker.enabled:
self.progress_tracker.enabled = True
- self.logger.debug(
- f"Arrow exporter initialized: compression={compression}"
- )
+ self.logger.debug(f"Arrow exporter initialized: compression={compression}")
def export(
self,
@@ -187,29 +211,33 @@ class ArrowExporter:
# Export each key as separate Arrow file
exported_files = []
self.progress_tracker.update_tracking(
- tracking_id, message=f"Exporting {len(data)} data groups..."
+ tracking_id,
+ message=f"Exporting {len(data)} data groups...",
)
for key, value in data.items():
if isinstance(value, list):
output_path = file_path.parent / f"{file_path.stem}_{key}.arrow"
-
+
# Select schema based on key
key_schema = schema
if key == "entities" and schema is None:
key_schema = ENTITY_SCHEMA
elif key == "relationships" and schema is None:
key_schema = RELATIONSHIP_SCHEMA
-
- self._write_arrow(value, output_path, schema=key_schema, **options)
+
+ self._write_arrow(
+ value, output_path, schema=key_schema, **options
+ )
exported_files.append(output_path)
else:
self.logger.warning(
- f"Skipping key '{key}': value is not a list (type: {type(value)})"
+ f"Skipping key '{key}': value is not a list "
+ f"(type: {type(value)})"
)
self.logger.info(
- f"Exported {len(exported_files)} Arrow file(s) from dictionary: "
- f"{', '.join(str(f) for f in exported_files)}"
+ f"Exported {len(exported_files)} Arrow file(s) from "
+ f"dictionary: {', '.join(str(f) for f in exported_files)}"
)
self.progress_tracker.stop_tracking(
tracking_id,
@@ -219,7 +247,8 @@ class ArrowExporter:
elif isinstance(data, list):
# Single Arrow file
self.progress_tracker.update_tracking(
- tracking_id, message=f"Exporting {len(data)} records..."
+ tracking_id,
+ message=f"Exporting {len(data)} records...",
)
self._write_arrow(data, file_path, schema=schema, **options)
self.logger.info(f"Exported Arrow to: {file_path}")
@@ -300,7 +329,8 @@ class ArrowExporter:
confidence = float(confidence)
except (TypeError, ValueError):
self.logger.warning(
- f"Invalid confidence value for entity {i}: {confidence}. Setting to None."
+ f"Invalid confidence value for entity {i}: "
+ f"{confidence}. Setting to None."
)
confidence = None
@@ -337,7 +367,9 @@ class ArrowExporter:
f"Normalized {len(normalized_entities)} entity(ies) for Arrow export"
)
- self._write_arrow(normalized_entities, file_path, schema=ENTITY_SCHEMA, **options)
+ self._write_arrow(
+ normalized_entities, file_path, schema=ENTITY_SCHEMA, **options
+ )
def export_relationships(
self,
@@ -370,8 +402,10 @@ class ArrowExporter:
Example:
>>> relationships = [
- ... {"id": "r1", "source_id": "e1", "target_id": "e2", "type": "RELATED_TO"},
- ... {"source": "e2", "target": "e3", "relationship_type": "CONTAINS"}
+ ... {"id": "r1", "source_id": "e1", "target_id": "e2",
+ ... "type": "RELATED_TO"},
+ ... {"source": "e2", "target": "e3",
+ ... "relationship_type": "CONTAINS"}
... ]
>>> exporter.export_relationships(relationships, "relationships.arrow")
"""
@@ -402,7 +436,8 @@ class ArrowExporter:
confidence = float(confidence)
except (TypeError, ValueError):
self.logger.warning(
- f"Invalid confidence value for relationship {i}: {confidence}. Setting to None."
+ f"Invalid confidence value for relationship {i}: "
+ f"{confidence}. Setting to None."
)
confidence = None
@@ -426,7 +461,9 @@ class ArrowExporter:
f"Normalized {len(normalized_rels)} relationship(s) for Arrow export"
)
- self._write_arrow(normalized_rels, file_path, schema=RELATIONSHIP_SCHEMA, **options)
+ self._write_arrow(
+ normalized_rels, file_path, schema=RELATIONSHIP_SCHEMA, **options
+ )
def export_knowledge_graph(
self, knowledge_graph: Dict[str, Any], base_path: Union[str, Path], **options
@@ -559,25 +596,26 @@ class ArrowExporter:
if schema is None:
# Try to detect if data looks like entities or relationships
sample = data[0] if data else {}
-
+
# Check for relationship-specific fields
- has_source = any(k in sample for k in ['source_id', 'source'])
- has_target = any(k in sample for k in ['target_id', 'target'])
-
+ has_source = any(k in sample for k in ["source_id", "source"])
+ has_target = any(k in sample for k in ["target_id", "target"])
+
# Check for entity-specific fields
- has_text = any(k in sample for k in ['text', 'label', 'name'])
-
+ has_text = any(k in sample for k in ["text", "label", "name"])
+
if has_source and has_target:
schema = RELATIONSHIP_SCHEMA
self.logger.debug("Auto-detected relationship schema")
- elif has_text or 'type' in sample:
+ elif has_text or "type" in sample:
schema = ENTITY_SCHEMA
self.logger.debug("Auto-detected entity schema")
else:
raise ValidationError(
"Schema is required for Arrow export. "
"Cannot auto-detect schema from data structure. "
- "Provide explicit schema or use export_entities/export_relationships methods."
+ "Provide explicit schema or use "
+ "export_entities/export_relationships methods."
)
self.logger.debug(
@@ -590,7 +628,7 @@ class ArrowExporter:
table = pa.Table.from_pylist(data, schema=schema)
# Write to Arrow IPC file
- with pa.OSFile(str(file_path), 'wb') as sink:
+ with pa.OSFile(str(file_path), "wb") as sink:
with ipc.new_file(sink, schema) as writer:
writer.write_table(table)
diff --git a/tests/test_arango_aql_exporter.py b/tests/test_arango_aql_exporter.py
new file mode 100644
index 00000000..c7f19034
--- /dev/null
+++ b/tests/test_arango_aql_exporter.py
@@ -0,0 +1,499 @@
+"""
+Tests for ArangoDB AQL Exporter Module
+
+This module contains comprehensive tests for the ArangoDB AQL exporter,
+validating AQL syntax generation, node and edge handling, and edge cases.
+"""
+
+import json
+import re
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+
+from semantica.export.arango_aql_exporter import ArangoAQLExporter
+
+
+class TestArangoAQLExporter(unittest.TestCase):
+ """Test cases for ArangoDB AQL Exporter."""
+
+ def setUp(self):
+ """Set up test fixtures."""
+ self.test_dir = tempfile.mkdtemp()
+
+ # Sample entities for testing
+ self.entities = [
+ {
+ "id": "e1",
+ "type": "Person",
+ "name": "Alice",
+ "label": "Alice",
+ "properties": {"age": 30, "email": "[email protected]"},
+ },
+ {
+ "id": "e2",
+ "type": "Organization",
+ "name": "Acme Corp",
+ "label": "Acme Corp",
+ "properties": {"location": "New York", "founded": 2010},
+ },
+ {
+ "id": "e3",
+ "type": "Person",
+ "name": "Bob",
+ "label": "Bob",
+ "properties": {"age": 25},
+ },
+ ]
+
+ # Sample relationships for testing
+ self.relationships = [
+ {
+ "id": "r1",
+ "source": "e1",
+ "target": "e2",
+ "type": "WORKS_FOR",
+ "properties": {"role": "Engineer", "since": 2020},
+ },
+ {
+ "id": "r2",
+ "source": "e3",
+ "target": "e2",
+ "type": "WORKS_FOR",
+ "properties": {"role": "Manager"},
+ },
+ {
+ "id": "r3",
+ "source": "e1",
+ "target": "e3",
+ "type": "KNOWS",
+ },
+ ]
+
+ # Complete knowledge graph
+ self.kg = {
+ "entities": self.entities,
+ "relationships": self.relationships,
+ "metadata": {"version": "1.0", "created": "2024-01-01"},
+ }
+
+ def tearDown(self):
+ """Clean up test fixtures."""
+ shutil.rmtree(self.test_dir)
+
+ def test_exporter_initialization(self):
+ """Test exporter initialization with default and custom parameters."""
+ # Default initialization
+ exporter = ArangoAQLExporter()
+ self.assertEqual(exporter.vertex_collection, "vertices")
+ self.assertEqual(exporter.edge_collection, "edges")
+ self.assertEqual(exporter.batch_size, 1000)
+ self.assertTrue(exporter.include_collection_creation)
+
+ # Custom initialization
+ exporter = ArangoAQLExporter(
+ vertex_collection="nodes",
+ edge_collection="links",
+ batch_size=500,
+ include_collection_creation=False,
+ )
+ self.assertEqual(exporter.vertex_collection, "nodes")
+ self.assertEqual(exporter.edge_collection, "links")
+ self.assertEqual(exporter.batch_size, 500)
+ self.assertFalse(exporter.include_collection_creation)
+
+ def test_export_knowledge_graph(self):
+ """Test exporting a complete knowledge graph."""
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "graph.aql"
+
+ exporter.export_knowledge_graph(self.kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Check for collection creation comments
+ self.assertIn("Create vertex collection", content)
+ self.assertIn("Create edge collection", content)
+
+ # Check for INSERT statements
+ self.assertIn("INSERT doc INTO vertices", content)
+ self.assertIn("INSERT doc INTO edges", content)
+
+ # Check for entity data
+ self.assertIn("Alice", content)
+ self.assertIn("Acme Corp", content)
+ self.assertIn("Bob", content)
+ self.assertIn("Person", content)
+ self.assertIn("Organization", content)
+
+ # Check for relationship data
+ self.assertIn("WORKS_FOR", content)
+ self.assertIn("KNOWS", content)
+ self.assertIn("vertices/e1", content)
+ self.assertIn("vertices/e2", content)
+
+ def test_export_entities_only(self):
+ """Test exporting only entities (vertices)."""
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "entities.aql"
+
+ exporter.export_entities(self.entities, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Check for vertices INSERT
+ self.assertIn("INSERT doc INTO vertices", content)
+ self.assertIn("Alice", content)
+ self.assertIn("Acme Corp", content)
+
+ # Check that edges are NOT present (empty relationships)
+ self.assertIn("Inserting 0 edges", content)
+
+ def test_export_relationships_only(self):
+ """Test exporting only relationships (edges)."""
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "relationships.aql"
+
+ exporter.export_relationships(self.relationships, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Check for edges INSERT
+ self.assertIn("INSERT doc INTO edges", content)
+ self.assertIn("WORKS_FOR", content)
+ self.assertIn("KNOWS", content)
+
+ # Check that vertices section indicates 0 vertices
+ self.assertIn("Inserting 0 vertices", content)
+
+ def test_custom_collection_names(self):
+ """Test exporting with custom collection names."""
+ exporter = ArangoAQLExporter(
+ vertex_collection="custom_nodes", edge_collection="custom_edges"
+ )
+ output_path = Path(self.test_dir) / "custom.aql"
+
+ exporter.export(self.kg, str(output_path))
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Check for custom collection names
+ self.assertIn("INSERT doc INTO custom_nodes", content)
+ self.assertIn("INSERT doc INTO custom_edges", content)
+ self.assertIn("custom_nodes/e1", content)
+
+ def test_special_characters_in_properties(self):
+ """Test handling of special characters in node and edge properties."""
+ special_entities = [
+ {
+ "id": "special_1",
+ "type": "Person",
+ "name": "O'Brien",
+ "properties": {"quote": 'She said "hello"', "path": "C:\\Users\\test"},
+ }
+ ]
+
+ special_relationships = [
+ {
+ "id": "special_r1",
+ "source": "special_1",
+ "target": "e1",
+ "type": "KNOWS",
+ "properties": {"note": "Uses 'quotes' and \"escapes\""},
+ }
+ ]
+
+ kg = {"entities": special_entities, "relationships": special_relationships}
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "special_chars.aql"
+
+ exporter.export(kg, str(output_path))
+
+ # Verify file was created and is valid JSON structure
+ self.assertTrue(output_path.exists())
+
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # The content should contain the special characters properly escaped in JSON
+ self.assertIn("O'Brien", content)
+ self.assertIn("She said", content)
+
+ def test_empty_collections(self):
+ """Test handling of empty entity and relationship collections."""
+ empty_kg = {"entities": [], "relationships": []}
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "empty.aql"
+
+ exporter.export(empty_kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Should have collection creation comments but no INSERT statements
+ self.assertIn("Inserting 0 vertices", content)
+ self.assertIn("Inserting 0 edges", content)
+
+ def test_missing_source_or_target(self):
+ """Test handling of edges with missing source or target."""
+ invalid_relationships = [
+ {"id": "r_invalid_1", "source": "e1", "type": "KNOWS"}, # Missing target
+ {"id": "r_invalid_2", "target": "e2", "type": "RELATED"}, # Missing source
+ {
+ "id": "r_valid",
+ "source": "e1",
+ "target": "e2",
+ "type": "VALID",
+ }, # Valid
+ ]
+
+ kg = {"entities": self.entities, "relationships": invalid_relationships}
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "invalid_edges.aql"
+
+ # Should not raise an exception, but should skip invalid edges
+ exporter.export(kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Should only contain the valid relationship
+ self.assertIn("VALID", content)
+ # Count should reflect only 1 valid edge
+ self.assertIn("Inserting 3 edges", content) # Attempts all 3
+
+ def test_key_sanitization(self):
+ """Test sanitization of keys with invalid characters."""
+ entities_with_invalid_keys = [
+ {
+ "id": "[email protected]",
+ "type": "Email",
+ "name": "Test Email",
+ },
+ {
+ "id": "user/123/profile",
+ "type": "Profile",
+ "name": "User Profile",
+ },
+ {
+ "id": "_system",
+ "type": "System",
+ "name": "System Node",
+ },
+ ]
+
+ kg = {"entities": entities_with_invalid_keys, "relationships": []}
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "sanitized.aql"
+
+ exporter.export(kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Keys should be sanitized (@ and / replaced with _)
+ self.assertIn("e1_domain_com", content)
+ self.assertIn("user_123_profile", content)
+ # _system should become k_system (no leading underscore)
+ self.assertIn("k_system", content)
+
+ def test_batch_processing(self):
+ """Test batch processing with small batch size."""
+ # Create many entities to test batching
+ many_entities = [
+ {"id": f"e{i}", "type": "Node", "name": f"Node {i}"} for i in range(250)
+ ]
+
+ kg = {"entities": many_entities, "relationships": []}
+
+ # Use small batch size
+ exporter = ArangoAQLExporter(batch_size=100)
+ output_path = Path(self.test_dir) / "batched.aql"
+
+ exporter.export(kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Count number of INSERT statements (should be 3 batches: 100, 100, 50)
+ insert_count = content.count("INSERT doc INTO vertices")
+ self.assertEqual(insert_count, 3, "Should have 3 batches for 250 entities")
+
+ def test_nested_properties(self):
+ """Test handling of nested dictionaries and lists in properties."""
+ entities_with_nested = [
+ {
+ "id": "complex_1",
+ "type": "ComplexNode",
+ "name": "Complex",
+ "properties": {
+ "nested_dict": {"key1": "value1", "key2": "value2"},
+ "nested_list": [1, 2, 3, 4, 5],
+ "mixed": {"list": [1, 2], "value": "test"},
+ },
+ }
+ ]
+
+ kg = {"entities": entities_with_nested, "relationships": []}
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "nested.aql"
+
+ exporter.export(kg, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Nested structures should be properly serialized as JSON
+ self.assertIn("nested_dict", content)
+ self.assertIn("nested_list", content)
+ # Check for the list values (may be formatted on separate lines)
+ self.assertIn("1", content)
+ self.assertIn("2", content)
+ self.assertIn("3", content)
+ self.assertIn("4", content)
+ self.assertIn("5", content)
+
+ def test_aql_syntax_validity(self):
+ """Test that generated AQL has valid syntax structure."""
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "syntax_test.aql"
+
+ exporter.export(self.kg, str(output_path))
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Check for valid AQL structure
+ # Should have FOR doc IN [array] INSERT doc INTO collection pattern
+ # Using re.search with DOTALL flag
+ pattern = r"FOR doc IN \[.*?\]\s+INSERT doc INTO \w+"
+ self.assertTrue(
+ re.search(pattern, content, re.DOTALL),
+ f"Pattern '{pattern}' not found in generated AQL",
+ )
+
+ # Check that JSON arrays in the INSERT statements are valid
+ # Find all JSON arrays in the content
+ json_arrays = re.findall(r"FOR doc IN (\[.*?\])\s+INSERT", content, re.DOTALL)
+ for json_array_match in json_arrays:
+ # Extract just the array part
+ json_str = json_array_match.replace("\n INSERT", "").strip()
+ try:
+ # This should parse without errors
+ parsed = json.loads(json_str)
+ self.assertIsInstance(parsed, list)
+ except json.JSONDecodeError as e:
+ self.fail(f"Invalid JSON in AQL: {e}")
+
+ def test_without_collection_creation(self):
+ """Test export without collection creation statements."""
+ exporter = ArangoAQLExporter(include_collection_creation=False)
+ output_path = Path(self.test_dir) / "no_creation.aql"
+
+ exporter.export(self.kg, str(output_path))
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Should still have INSERT statements
+ self.assertIn("INSERT doc INTO vertices", content)
+ self.assertIn("INSERT doc INTO edges", content)
+
+ def test_export_with_nodes_edges_keys(self):
+ """Test export using 'nodes' and 'edges' keys.
+
+ Instead of 'entities' and 'relationships'.
+ """
+ kg_alt = {
+ "nodes": self.entities,
+ "edges": self.relationships,
+ }
+
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "nodes_edges.aql"
+
+ exporter.export(kg_alt, str(output_path))
+
+ # Verify file was created
+ self.assertTrue(output_path.exists())
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Should have all the data
+ self.assertIn("Alice", content)
+ self.assertIn("WORKS_FOR", content)
+
+ def test_override_collection_names_in_export(self):
+ """Test overriding collection names via export options."""
+ exporter = ArangoAQLExporter(
+ vertex_collection="default_v", edge_collection="default_e"
+ )
+ output_path = Path(self.test_dir) / "override.aql"
+
+ # Override via options
+ exporter.export(
+ self.kg,
+ str(output_path),
+ vertex_collection="override_v",
+ edge_collection="override_e",
+ )
+
+ # Read and verify content
+ with open(output_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Should use overridden names
+ self.assertIn("INSERT doc INTO override_v", content)
+ self.assertIn("INSERT doc INTO override_e", content)
+ self.assertIn("override_v/e1", content)
+
+
+if __name__ == "__main__":
+ unittest.main()