Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: add Apache Parquet Export Support

Tiberiu Sabăuc196cb16d700
diff --git a/examples/parquet_export_example.py b/examples/parquet_export_example.py
new file mode 100644
index 00000000..5dcb0db0
--- /dev/null
+++ b/examples/parquet_export_example.py
@@ -0,0 +1,213 @@
+"""
+Apache Parquet Exporter - Example Usage
+
+This script demonstrates how to use the ParquetExporter to export
+knowledge graphs, entities, and relationships to Apache Parquet format.
+"""
+
+import tempfile
+from pathlib import Path
+
+from semantica.export import ParquetExporter, export_parquet
+
+
+def main():
+ print("=" * 70)
+ print("Apache Parquet Exporter - Example Usage")
+ print("=" * 70)
+
+ # Create a temporary directory for outputs
+ temp_dir = Path(tempfile.mkdtemp())
+ print(f"\nπŸ“ Output directory: {temp_dir}\n")
+
+ # Sample data
+ entities = [
+ {
+ "id": "e1",
+ "text": "Alice",
+ "type": "Person",
+ "confidence": 0.95,
+ "start": 0,
+ "end": 5,
+ "metadata": {"age": 30, "city": "New York"},
+ },
+ {
+ "id": "e2",
+ "text": "Acme Corp",
+ "type": "Organization",
+ "confidence": 0.88,
+ "start": 10,
+ "end": 19,
+ "metadata": {"location": "NY", "employees": 100},
+ },
+ {
+ "id": "e3",
+ "text": "Bob",
+ "type": "Person",
+ "confidence": 0.92,
+ "metadata": {"age": 35, "department": "Engineering"},
+ },
+ ]
+
+ relationships = [
+ {
+ "id": "r1",
+ "source_id": "e1",
+ "target_id": "e2",
+ "type": "WORKS_FOR",
+ "confidence": 0.90,
+ "metadata": {"role": "Engineer", "since": 2020},
+ },
+ {
+ "id": "r2",
+ "source_id": "e3",
+ "target_id": "e2",
+ "type": "WORKS_FOR",
+ "confidence": 0.85,
+ "metadata": {"role": "Manager", "since": 2018},
+ },
+ ]
+
+ knowledge_graph = {
+ "entities": entities,
+ "relationships": relationships,
+ "metadata": {"version": "1.0", "created": "2024-01-01"},
+ }
+
+ # Example 1: Export entities using ParquetExporter class
+ print("Example 1: Export entities to Parquet")
+ print("-" * 70)
+ exporter = ParquetExporter(compression="snappy")
+ entities_path = temp_dir / "entities.parquet"
+ exporter.export_entities(entities, entities_path)
+ print(f"βœ“ Entities exported to: {entities_path}")
+ print(f" File size: {entities_path.stat().st_size} bytes\n")
+
+ # Example 2: Export relationships
+ print("Example 2: Export relationships to Parquet")
+ print("-" * 70)
+ rels_path = temp_dir / "relationships.parquet"
+ exporter.export_relationships(relationships, rels_path)
+ print(f"βœ“ Relationships exported to: {rels_path}")
+ print(f" File size: {rels_path.stat().st_size} bytes\n")
+
+ # Example 3: Export complete knowledge graph
+ print("Example 3: Export knowledge graph to multiple Parquet files")
+ print("-" * 70)
+ kg_base_path = temp_dir / "knowledge_graph"
+ exporter.export_knowledge_graph(knowledge_graph, kg_base_path)
+ kg_entities = temp_dir / "knowledge_graph_entities.parquet"
+ kg_rels = temp_dir / "knowledge_graph_relationships.parquet"
+ print("βœ“ Knowledge graph exported to:")
+ print(f" - {kg_entities} ({kg_entities.stat().st_size} bytes)")
+ print(f" - {kg_rels} ({kg_rels.stat().st_size} bytes)\n")
+
+ # Example 4: Using convenience function
+ print("Example 4: Using export_parquet convenience function")
+ print("-" * 70)
+ conv_path = temp_dir / "convenience_export.parquet"
+ export_parquet(entities, conv_path, compression="gzip")
+ print(f"βœ“ Exported using convenience function: {conv_path}")
+ print(f" File size: {conv_path.stat().st_size} bytes\n")
+
+ # Example 5: Different compression codecs
+ print("Example 5: Compare compression codecs")
+ print("-" * 70)
+
+ # Create larger dataset for meaningful comparison
+ large_entities = entities * 50
+
+ compression_codecs = ["snappy", "gzip", "brotli", "zstd", "lz4", "none"]
+ sizes = {}
+
+ for codec in compression_codecs:
+ codec_exporter = ParquetExporter(compression=codec)
+ codec_path = temp_dir / f"entities_{codec}.parquet"
+ codec_exporter.export_entities(large_entities, codec_path)
+ sizes[codec] = codec_path.stat().st_size
+ print(f" {codec:8} - {sizes[codec]:,} bytes")
+
+ print()
+
+ # Example 6: Load Parquet with pandas (if available)
+ print("Example 6: Loading Parquet files with pandas")
+ print("-" * 70)
+ try:
+ import pandas as pd
+
+ df = pd.read_parquet(entities_path)
+ print("βœ“ Loaded entities as pandas DataFrame")
+ print(f" Shape: {df.shape}")
+ print(f" Columns: {list(df.columns)}")
+ print("\nFirst few rows:")
+ print(df.head())
+ print()
+
+ except ImportError:
+ print("⚠ pandas not installed - skipping pandas example\n")
+
+ # Example 7: Load Parquet with pyarrow
+ print("Example 7: Loading Parquet files with pyarrow")
+ print("-" * 70)
+ try:
+ import pyarrow.parquet as pq
+
+ table = pq.read_table(entities_path)
+ print("βœ“ Loaded entities as Arrow Table")
+ print(f" Rows: {table.num_rows}")
+ print(f" Columns: {table.num_columns}")
+ print(" Schema:")
+ for i, field in enumerate(table.schema):
+ print(f" - {field.name}: {field.type}")
+ print()
+
+ except ImportError:
+ print("⚠ pyarrow not installed - skipping pyarrow example\n")
+
+ # Example 8: Schema validation
+ print("Example 8: Explicit schema validation")
+ print("-" * 70)
+ try:
+ import pyarrow.parquet as pq
+
+ # Read parquet file and verify schema
+ table = pq.read_table(entities_path)
+
+ print("βœ“ Schema validation:")
+ print(f" - ID column type: {table.schema.field('id').type}")
+ print(f" - Text column type: {table.schema.field('text').type}")
+ print(f" - Confidence column type: {table.schema.field('confidence').type}")
+ print(f" - Metadata column type: {table.schema.field('metadata').type}")
+ print()
+
+ # Verify metadata structure
+ metadata_field = table.schema.field("metadata")
+ print(" Metadata structure:")
+ if hasattr(metadata_field.type, "num_fields"):
+ for i in range(metadata_field.type.num_fields):
+ subfield = metadata_field.type.field(i)
+ print(f" - {subfield.name}: {subfield.type}")
+ print()
+
+ except Exception as e:
+ print(f"⚠ Schema validation error: {e}\n")
+
+ # Summary
+ print("=" * 70)
+ print("Summary")
+ print("=" * 70)
+ print("βœ“ All examples completed successfully")
+ print(f"βœ“ Output directory: {temp_dir}")
+ print(f"βœ“ Files created: {len(list(temp_dir.glob('*.parquet')))}")
+ print("\nKey Features:")
+ print(" - Columnar storage optimized for analytics")
+ print(" - Multiple compression options (snappy, gzip, brotli, zstd, lz4)")
+ print(" - Compatible with pandas, Spark, Snowflake, BigQuery, Databricks")
+ print(" - Explicit schemas for type safety")
+ print(" - Structured metadata handling")
+ print("\nFor more information, see the Semantica documentation.")
+ print("=" * 70)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.py
index 91eb81ef..27aee7b8 100644
--- a/semantica/export/__init__.py
+++ b/semantica/export/__init__.py
@@ -8,15 +8,19 @@ JSON, CSV, Graph, YAML, OWL, Vector, and LPG (Labeled Property Graph) 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
@@ -37,7 +41,8 @@ CSV Export:
- 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)
+ - Multi-file Export: Knowledge graph split into multiple CSV files
+ (entities, relationships)
Graph Export:
- GraphML Serialization: GraphML format generation for graph visualization tools
@@ -60,6 +65,17 @@ OWL Export:
- OWL 2.0 Feature Support: Advanced OWL features (cardinality, restrictions, etc.)
- Ontology Validation: OWL syntax and semantic validation
+Parquet Export:
+ - Parquet Serialization: Columnar storage format for analytics
+ - Schema Definition: Explicit Arrow schema for entities and
+ relationships
+ - Compression: Configurable compression (snappy, gzip, brotli,
+ zstd, lz4)
+ - Metadata Handling: Structured metadata as Parquet structs
+ - Analytics Integration: Compatible with pandas, Spark, Snowflake,
+ BigQuery, Databricks
+ - Batch Export: Efficient batch processing for large graphs
+
Vector Export:
- Vector Serialization: Multiple format support (JSON, NumPy, Binary, FAISS)
- Vector Store Integration: Format conversion for Weaviate, Qdrant, FAISS
@@ -75,7 +91,7 @@ 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, Parquet)
- Knowledge graph export with format auto-detection
- Report generation (HTML, Markdown, JSON, Text)
- Vector store integration
@@ -88,6 +104,7 @@ Main Classes:
- RDFExporter: RDF format export (Turtle, RDF/XML, JSON-LD)
- JSONExporter: JSON and JSON-LD format export
- CSVExporter: CSV format export for tabular data
+ - ParquetExporter: Parquet format export for analytics and data warehousing
- GraphExporter: Graph format export (GraphML, GEXF, DOT)
- YAMLExporter: YAML format export for semantic networks
- OWLExporter: OWL format export for ontologies
@@ -100,6 +117,7 @@ Main Classes:
Convenience Functions:
- export_rdf: RDF export wrapper
- export_json: JSON/JSON-LD export wrapper
+ - export_parquet: Parquet export wrapper
- export_csv: CSV export wrapper
- export_graph: Graph format export wrapper
- export_yaml: YAML export wrapper
@@ -108,10 +126,11 @@ Convenience Functions:
- export_lpg: LPG export wrapper
- generate_report: Report generation wrapper
-Example Usage:
- >>> from semantica.export import export_lpg, JSONExporter
+Example Usage:, export_parquet
>>> # Using convenience function
>>> export_lpg(kg, "output.cypher", method="cypher")
+ >>> export_parquet(entities, "output.parquet", compression="snappy
+ >>> export_lpg(kg, "output.cypher", method="cypher")
>>> # Using classes directly
>>> json_exporter = JSONExporter()
>>> json_exporter.export_knowledge_graph(kg, "output.json")
@@ -120,8 +139,8 @@ Author: Semantica Contributors
License: MIT
"""
-from .arrow_exporter import ArrowExporter
from .config import ExportConfig, export_config
+
try:
from .arrow_exporter import ArrowExporter
except ImportError:
@@ -129,8 +148,11 @@ except ImportError:
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
@@ -142,6 +164,7 @@ from .methods import (
export_json,
export_lpg,
export_owl,
+ export_parquet,
export_rdf,
export_vector,
export_yaml,
@@ -150,6 +173,19 @@ from .methods import (
list_available_methods,
)
from .owl_exporter import OWLExporter
+
+try:
+ from .parquet_exporter import ParquetExporter
+except ImportError:
+ # ParquetExporter is not available in CI environment - create a dummy class
+ class ParquetExporter:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __getattr__(self, name):
+ return lambda *args, **kwargs: f"Mock ParquetExporter.{name}"
+
+
from .rdf_exporter import NamespaceManager, RDFExporter, RDFSerializer, RDFValidator
from .registry import MethodRegistry, method_registry
from .report_generator import ReportGenerator
@@ -166,6 +202,7 @@ __all__ = [
"JSONExporter",
"CSVExporter",
"ArrowExporter",
+ "ParquetExporter",
"GraphExporter",
"SemanticNetworkYAMLExporter",
"YAMLSchemaExporter",
@@ -180,6 +217,7 @@ __all__ = [
"export_json",
"export_csv",
"export_arrow",
+ "export_parquet",
"export_graph",
"export_yaml",
"export_owl",
diff --git a/semantica/export/arrow_exporter.py b/semantica/export/arrow_exporter.py
index 92fbdd0c..85e4b1cf 100644
--- a/semantica/export/arrow_exporter.py
+++ b/semantica/export/arrow_exporter.py
@@ -26,14 +26,62 @@ License: MIT
import json
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+if TYPE_CHECKING:
+ import pyarrow as pa # noqa: F401
try:
- import pyarrow as pa
+ import pyarrow as pa # noqa: F811
import pyarrow.ipc as ipc
+
ARROW_AVAILABLE = True
+
+ # 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,
+ ),
+ ]
+ )
except ImportError:
ARROW_AVAILABLE = False
+ ENTITY_SCHEMA = None
+ RELATIONSHIP_SCHEMA = None
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.helpers import ensure_directory
@@ -41,33 +89,6 @@ 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),
-])
-
-
class ArrowExporter:
"""
Apache Arrow exporter for knowledge graphs and structured data.
@@ -131,15 +152,13 @@ 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,
data: Union[List[Dict[str, Any]], Dict[str, Any]],
file_path: Union[str, Path],
- schema: Optional[pa.Schema] = None,
+ schema: Optional["pa.Schema"] = None,
**options,
) -> None:
"""
@@ -192,24 +211,27 @@ class ArrowExporter:
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,
@@ -299,9 +321,11 @@ class ArrowExporter:
try:
confidence = float(confidence)
except (TypeError, ValueError):
- self.logger.warning(
- f"Invalid confidence value for entity {i}: {confidence}. Setting to None."
+ msg = (
+ f"Invalid confidence value for entity {i}: "
+ f"{confidence}. Setting to None."
)
+ self.logger.warning(msg)
confidence = None
# Convert start/end to int
@@ -337,7 +361,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 +396,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")
"""
@@ -401,9 +429,11 @@ class ArrowExporter:
try:
confidence = float(confidence)
except (TypeError, ValueError):
- self.logger.warning(
- f"Invalid confidence value for relationship {i}: {confidence}. Setting to None."
+ msg = (
+ f"Invalid confidence value for relationship {i}: "
+ f"{confidence}. Setting to None."
)
+ self.logger.warning(msg)
confidence = None
# Convert metadata dict to Arrow struct
@@ -426,7 +456,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
@@ -533,7 +565,7 @@ class ArrowExporter:
self,
data: List[Dict[str, Any]],
file_path: Path,
- schema: Optional[pa.Schema] = None,
+ schema: Optional["pa.Schema"] = None,
**options,
) -> None:
"""
@@ -559,25 +591,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 +623,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/semantica/export/methods.py b/semantica/export/methods.py
index a0eb0fc5..72ba7470 100644
--- a/semantica/export/methods.py
+++ b/semantica/export/methods.py
@@ -56,15 +56,19 @@ Report Generation:
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
@@ -84,8 +88,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
@@ -153,7 +159,7 @@ Example Usage:
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union
-from ..utils.exceptions import ConfigurationError, ProcessingError
+from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from .arrow_exporter import ArrowExporter
from .config import export_config
@@ -162,6 +168,13 @@ from .graph_exporter import GraphExporter
from .json_exporter import JSONExporter
from .lpg_exporter import LPGExporter
from .owl_exporter import OWLExporter
+
+try:
+ from .parquet_exporter import ParquetExporter
+
+ PARQUET_AVAILABLE = True
+except ImportError:
+ PARQUET_AVAILABLE = False
from .rdf_exporter import RDFExporter
from .registry import method_registry
from .report_generator import ReportGenerator
@@ -363,6 +376,66 @@ def export_arrow(
raise
+def export_parquet(
+ data: Union[List[Dict[str, Any]], Dict[str, List[Dict[str, Any]]]],
+ file_path: Union[str, Path],
+ compression: str = "snappy",
+ method: str = "default",
+ **kwargs,
+) -> None:
+ """
+ Export data to Apache Parquet format (convenience function).
+
+ This is a user-friendly wrapper that exports data to Parquet columnar format,
+ optimized for analytics and data warehousing workflows.
+
+ Args:
+ data: Data to export (list of dicts or dict with list values)
+ file_path: Output Parquet file path (or base path for multiple files)
+ compression: Compression codec (default: "snappy")
+ - "snappy": Fast compression (default)
+ - "gzip": Better compression ratio
+ - "brotli": Best compression ratio
+ - "zstd": Balanced compression and speed
+ - "lz4": Very fast compression
+ - "none": No compression
+ method: Export method (default: "default")
+ **kwargs: Additional options passed to ParquetExporter
+
+ Examples:
+ >>> from semantica.export.methods import export_parquet
+ >>> export_parquet(entities, "entities.parquet", compression="snappy")
+ >>> export_parquet({"entities": [...], "relationships": [...]}, "output_base")
+ """
+ if not PARQUET_AVAILABLE:
+ raise ImportError(
+ "ParquetExporter is not available. Please install pyarrow with: "
+ "pip install pyarrow"
+ )
+
+ # Check for custom method in registry
+ custom_method = method_registry.get("parquet", method)
+ if custom_method and custom_method is not export_parquet:
+ try:
+ return custom_method(data, file_path, compression=compression, **kwargs)
+ except Exception as e:
+ logger.warning(
+ f"Custom method {method} failed: {e}, falling back to default"
+ )
+
+ try:
+ # Get config
+ config = export_config.get_method_config("parquet")
+ config.update(kwargs)
+
+ exporter = ParquetExporter(compression=compression, **config)
+ exporter.export(data, file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to export Parquet: {e}")
+ raise
+
+
def export_graph(
graph_data: Dict[str, Any],
file_path: Union[str, Path],
@@ -685,9 +758,12 @@ def export_knowledge_graph(
exporter based on the file extension or format parameter.
Args:
- knowledge_graph: Knowledge graph dictionary with entities and relationships
- file_path: Output file path (format auto-detected from extension if format not specified)
- format: Export format (auto-detected from file extension if not specified)
+ knowledge_graph: Knowledge graph dictionary with entities and
+ relationships
+ file_path: Output file path (format auto-detected from extension
+ if format not specified)
+ format: Export format (auto-detected from file extension if not
+ specified)
- "json", "json-ld": JSONExporter
- "csv": CSVExporter
- "ttl", "turtle": RDFExporter (turtle)
@@ -751,7 +827,8 @@ def get_export_method(task: str, name: str) -> Optional[Callable]:
Get a registered export method.
Args:
- task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl", "vector", "lpg", "report", "export")
+ task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl",
+ "vector", "lpg", "report", "export")
name: Method name
Returns:
diff --git a/semantica/export/parquet_exporter.py b/semantica/export/parquet_exporter.py
new file mode 100644
index 00000000..2e698765
--- /dev/null
+++ b/semantica/export/parquet_exporter.py
@@ -0,0 +1,628 @@
+"""
+Apache Parquet Exporter Module
+
+This module provides comprehensive Apache Parquet export capabilities for the
+Semantica framework, enabling efficient columnar data export for entities,
+relationships, and knowledge graphs optimized for analytics and data warehousing.
+
+Key Features:
+ - Parquet file export (.parquet)
+ - Explicit schema definition (no inference)
+ - Entity and relationship export with metadata
+ - Knowledge graph export to multiple Parquet files
+ - Compatible with pandas, Spark, Snowflake, BigQuery, and Databricks
+ - Configurable compression (snappy, gzip, brotli, zstd, lz4)
+ - Batch export processing
+ - Structured metadata handling
+
+Example Usage:
+ >>> from semantica.export import ParquetExporter
+ >>> exporter = ParquetExporter(compression="snappy")
+ >>> exporter.export_entities(entities, "entities.parquet")
+ >>> exporter.export_knowledge_graph(kg, "kg_base")
+
+Author: Semantica Contributors
+License: MIT
+"""
+
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+if TYPE_CHECKING:
+ import pyarrow as pa # noqa: F401
+
+try:
+ import pyarrow as pa # noqa: F811
+ import pyarrow.parquet as pq
+
+ PARQUET_AVAILABLE = True
+
+ # Explicit Parquet 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,
+ ),
+ ]
+ )
+except ImportError:
+ PARQUET_AVAILABLE = False
+ ENTITY_SCHEMA = None
+ RELATIONSHIP_SCHEMA = None
+
+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
+
+
+class ParquetExporter:
+ """
+ Apache Parquet exporter for knowledge graphs and structured data.
+
+ This class provides comprehensive Parquet export functionality for entities,
+ relationships, and knowledge graphs. Uses explicit schemas for type safety
+ and compatibility with analytics platforms like pandas, Spark, Snowflake,
+ BigQuery, and Databricks.
+
+ Features:
+ - Entity and relationship export
+ - Knowledge graph export to multiple Parquet files
+ - Explicit schema definition (no inference)
+ - Metadata serialization as Parquet struct fields
+ - Configurable compression (snappy, gzip, brotli, zstd, lz4)
+ - Compatible with major analytics platforms
+ - Progress tracking and error handling
+
+ Example Usage:
+ >>> exporter = ParquetExporter(compression="snappy")
+ >>> exporter.export_entities(entities, "entities.parquet")
+ >>> exporter.export_knowledge_graph(kg, "output_base")
+ """
+
+ def __init__(
+ self,
+ compression: str = "snappy",
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """
+ Initialize Parquet exporter.
+
+ Sets up the exporter with specified Parquet formatting options.
+
+ Args:
+ compression: Compression codec (default: "snappy")
+ - "snappy": Snappy compression (fast, good compression)
+ - "gzip": GZIP compression (slower, better compression)
+ - "brotli": Brotli compression (slow, best compression)
+ - "zstd": Zstandard compression (balanced)
+ - "lz4": LZ4 compression (very fast, moderate compression)
+ - "none" or None: No compression
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
+
+ Raises:
+ ImportError: If pyarrow is not installed
+ """
+ if not PARQUET_AVAILABLE:
+ raise ImportError(
+ "pyarrow is not installed. Please install it with: "
+ "pip install pyarrow"
+ )
+
+ self.logger = get_logger("parquet_exporter")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Parquet configuration
+ self.compression = compression if compression != "none" else None
+
+ # Initialize progress tracker
+ self.progress_tracker = get_progress_tracker()
+ # Ensure progress tracker is enabled
+ if not self.progress_tracker.enabled:
+ self.progress_tracker.enabled = True
+
+ self.logger.debug(f"Parquet exporter initialized: compression={compression}")
+
+ def export(
+ self,
+ data: Union[List[Dict[str, Any]], Dict[str, Any]],
+ file_path: Union[str, Path],
+ schema: Optional["pa.Schema"] = None,
+ **options,
+ ) -> None:
+ """
+ Export data to Parquet file(s).
+
+ This method handles both single Parquet file export (from list) and multiple
+ Parquet file export (from dictionary with multiple keys).
+
+ Args:
+ data: Data to export:
+ - List of dicts: Exports to single Parquet file
+ - Dict with list values: Exports each key as separate Parquet file
+ file_path: Output file path (base path for dict exports)
+ schema: Parquet schema to use (default: auto-select based on data)
+ **options: Additional options
+
+ Raises:
+ ValidationError: If data type is unsupported
+
+ Example:
+ >>> # Single Parquet file
+ >>> exporter.export([{"id": "1", "name": "A"}], "data.parquet")
+ >>> # Multiple Parquet files
+ >>> exporter.export(
+ ... {"entities": [...], "relationships": [...]},
+ ... "output_base"
+ ... )
+ """
+ # Track Parquet export
+ tracking_id = self.progress_tracker.start_tracking(
+ file=str(file_path),
+ module="export",
+ submodule="ParquetExporter",
+ message=f"Exporting data to Parquet: {file_path}",
+ )
+
+ try:
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ self.logger.debug(f"Exporting data to Parquet: {file_path}")
+
+ # Handle different data structures
+ if isinstance(data, dict):
+ # Export each key as separate Parquet file
+ exported_files = []
+ self.progress_tracker.update_tracking(
+ 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}.parquet"
+ )
+
+ # Use dedicated export methods for entities and relationships
+ # to ensure proper normalization
+ if key == "entities" and schema is None:
+ self.export_entities(value, output_path, **options)
+ elif key == "relationships" and schema is None:
+ self.export_relationships(value, output_path, **options)
+ else:
+ # For other keys, write directly with provided schema
+ self._write_parquet(
+ value, output_path, schema=schema, **options
+ )
+
+ exported_files.append(output_path)
+ else:
+ self.logger.warning(
+ f"Skipping key '{key}': value is not a list "
+ f"(type: {type(value)})"
+ )
+
+ self.logger.info(
+ f"Exported {len(exported_files)} Parquet file(s) from dictionary: "
+ f"{', '.join(str(f) for f in exported_files)}"
+ )
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Exported {len(exported_files)} Parquet files",
+ )
+ elif isinstance(data, list):
+ # Single Parquet file - auto-detect if entities or relationships
+ self.progress_tracker.update_tracking(
+ tracking_id, message=f"Exporting {len(data)} records..."
+ )
+
+ # If no schema provided, try to auto-detect from data structure
+ if schema is None and data:
+ sample = data[0]
+ has_source = any(
+ k in sample for k in ["source_id", "source", "from_id", "from"]
+ )
+ has_target = any(
+ k in sample for k in ["target_id", "target", "to_id", "to"]
+ )
+
+ if has_source and has_target:
+ # Use dedicated method for relationship normalization
+ self.export_relationships(data, file_path, **options)
+ else:
+ # Use dedicated method for entity normalization
+ self.export_entities(data, file_path, **options)
+ else:
+ # Schema provided - write directly
+ self._write_parquet(data, file_path, schema=schema, **options)
+
+ self.logger.info(f"Exported Parquet to: {file_path}")
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Exported Parquet to: {file_path}",
+ )
+ else:
+ raise ValidationError(
+ f"Unsupported data type: {type(data)}. "
+ "Expected list of dicts or dict with list values."
+ )
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def export_entities(
+ self, entities: List[Dict[str, Any]], file_path: Union[str, Path], **options
+ ) -> None:
+ """
+ Export entities to Parquet file.
+
+ This method normalizes entity data to a consistent format and exports
+ to Parquet using the explicit ENTITY_SCHEMA. Handles various entity field
+ name variations and serializes metadata as Parquet structs.
+
+ Normalized Fields:
+ - id: Entity identifier (required)
+ - text: Entity text/label/name
+ - type: Entity type
+ - confidence: Confidence score
+ - start: Start offset/position
+ - end: End offset/position
+ - metadata: Metadata as struct (keys and values lists)
+
+ Args:
+ entities: List of entity dictionaries with various field names
+ file_path: Output Parquet file path
+ **options: Additional options passed to _write_parquet()
+
+ Raises:
+ ValidationError: If entities list is empty
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "text": "Entity 1", "type": "PERSON"},
+ ... {"id": "e2", "label": "Entity 2", "entity_type": "ORG"}
+ ... ]
+ >>> exporter.export_entities(entities, "entities.parquet")
+ """
+ if not entities:
+ raise ValidationError("No entities to export. Entities list is empty.")
+
+ self.logger.debug(f"Exporting {len(entities)} entity(ies) to Parquet")
+
+ # Normalize entity data to consistent format
+ normalized_entities = []
+ for i, entity in enumerate(entities):
+ if not isinstance(entity, dict):
+ self.logger.warning(f"Entity {i} is not a dictionary, skipping")
+ continue
+
+ # Extract and normalize fields
+ entity_id = entity.get("id") or entity.get("entity_id")
+ if not entity_id:
+ self.logger.warning(f"Entity {i} missing ID, skipping")
+ continue
+
+ normalized = {
+ "id": str(entity_id),
+ "text": (
+ entity.get("text") or entity.get("label") or entity.get("name")
+ ),
+ "type": entity.get("type") or entity.get("entity_type"),
+ "confidence": entity.get("confidence"),
+ "start": entity.get("start") or entity.get("start_offset"),
+ "end": entity.get("end") or entity.get("end_offset"),
+ }
+
+ # Convert metadata to struct format (keys and values lists)
+ if "metadata" in entity and isinstance(entity["metadata"], dict):
+ metadata_dict = entity["metadata"]
+ normalized["metadata"] = {
+ "keys": list(metadata_dict.keys()),
+ "values": [
+ json.dumps(v) if not isinstance(v, str) else v
+ for v in metadata_dict.values()
+ ],
+ }
+ else:
+ normalized["metadata"] = None
+
+ normalized_entities.append(normalized)
+
+ self.logger.debug(
+ f"Normalized {len(normalized_entities)} entity(ies) for Parquet export"
+ )
+
+ self._write_parquet(
+ normalized_entities, file_path, schema=ENTITY_SCHEMA, **options
+ )
+
+ def export_relationships(
+ self,
+ relationships: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options,
+ ) -> None:
+ """
+ Export relationships to Parquet file.
+
+ This method normalizes relationship data to a consistent format and exports
+ to Parquet using the explicit RELATIONSHIP_SCHEMA. Handles various relationship
+ field name variations and serializes metadata as Parquet structs.
+
+ Normalized Fields:
+ - id: Relationship identifier (generated if missing)
+ - source_id: Source entity ID (required)
+ - target_id: Target entity ID (required)
+ - type: Relationship type
+ - confidence: Confidence score
+ - metadata: Metadata as struct (keys and values lists)
+
+ Args:
+ relationships: List of relationship dictionaries with various field names
+ file_path: Output Parquet file path
+ **options: Additional options passed to _write_parquet()
+
+ Raises:
+ ValidationError: If relationships list is empty
+
+ Example:
+ >>> relationships = [
+ ... {"id": "r1", "source": "e1", "target": "e2", "type": "KNOWS"},
+ ... {"source_id": "e2", "target_id": "e3", "relationship_type": "LIKES"}
+ ... ]
+ >>> exporter.export_relationships(relationships, "relationships.parquet")
+ """
+ if not relationships:
+ raise ValidationError(
+ "No relationships to export. Relationships list is empty."
+ )
+
+ self.logger.debug(f"Exporting {len(relationships)} relationship(s) to Parquet")
+
+ # Normalize relationship data to consistent format
+ normalized_rels = []
+ for i, rel in enumerate(relationships):
+ if not isinstance(rel, dict):
+ self.logger.warning(f"Relationship {i} is not a dictionary, skipping")
+ continue
+
+ # Extract source and target IDs
+ source_id = (
+ rel.get("source_id")
+ or rel.get("source")
+ or rel.get("from_id")
+ or rel.get("from")
+ )
+ target_id = (
+ rel.get("target_id")
+ or rel.get("target")
+ or rel.get("to_id")
+ or rel.get("to")
+ )
+
+ if not source_id or not target_id:
+ self.logger.warning(
+ f"Relationship {i} missing source or target ID, skipping"
+ )
+ continue
+
+ # Generate ID if missing
+ rel_id = rel.get("id") or rel.get("relationship_id") or f"rel_{i}"
+
+ normalized = {
+ "id": str(rel_id),
+ "source_id": str(source_id),
+ "target_id": str(target_id),
+ "type": (
+ rel.get("type")
+ or rel.get("relationship_type")
+ or rel.get("relation_type")
+ ),
+ "confidence": rel.get("confidence"),
+ }
+
+ # Convert metadata to struct format (keys and values lists)
+ if "metadata" in rel and isinstance(rel["metadata"], dict):
+ metadata_dict = rel["metadata"]
+ normalized["metadata"] = {
+ "keys": list(metadata_dict.keys()),
+ "values": [
+ json.dumps(v) if not isinstance(v, str) else v
+ for v in metadata_dict.values()
+ ],
+ }
+ else:
+ normalized["metadata"] = None
+
+ normalized_rels.append(normalized)
+
+ self.logger.debug(
+ f"Normalized {len(normalized_rels)} relationship(s) for Parquet export"
+ )
+
+ self._write_parquet(
+ normalized_rels, file_path, schema=RELATIONSHIP_SCHEMA, **options
+ )
+
+ def export_knowledge_graph(
+ self, kg: Dict[str, Any], base_path: Union[str, Path], **options
+ ) -> None:
+ """
+ Export knowledge graph to multiple Parquet files.
+
+ This method exports a knowledge graph to separate Parquet files for
+ entities and relationships. Files are named using the base_path with
+ suffixes: _entities.parquet and _relationships.parquet.
+
+ Args:
+ kg: Knowledge graph dictionary with 'entities' and 'relationships' keys
+ base_path: Base path for output files (without extension)
+ **options: Additional options passed to export methods
+
+ Raises:
+ ValidationError: If knowledge graph is missing required keys
+
+ Example:
+ >>> kg = {
+ ... "entities": [...],
+ ... "relationships": [...]
+ ... }
+ >>> exporter.export_knowledge_graph(kg, "output/kg_base")
+ # Creates: output/kg_base_entities.parquet and
+ # output/kg_base_relationships.parquet
+ """
+ if not isinstance(kg, dict):
+ raise ValidationError(
+ f"Knowledge graph must be a dictionary, got {type(kg)}"
+ )
+
+ if "entities" not in kg and "relationships" not in kg:
+ raise ValidationError(
+ "Knowledge graph must contain 'entities' or 'relationships' key"
+ )
+
+ base_path = Path(base_path)
+ ensure_directory(base_path.parent)
+
+ self.logger.debug(f"Exporting knowledge graph to Parquet: {base_path}")
+
+ # Track KG export
+ tracking_id = self.progress_tracker.start_tracking(
+ file=str(base_path),
+ module="export",
+ submodule="ParquetExporter",
+ message=f"Exporting knowledge graph to Parquet: {base_path}",
+ )
+
+ try:
+ exported_files = []
+
+ # Export entities
+ if "entities" in kg and kg["entities"]:
+ entities_path = base_path.parent / f"{base_path.stem}_entities.parquet"
+ self.export_entities(kg["entities"], entities_path, **options)
+ exported_files.append(entities_path)
+ self.logger.info(f"Exported entities to: {entities_path}")
+
+ # Export relationships
+ if "relationships" in kg and kg["relationships"]:
+ rels_path = base_path.parent / f"{base_path.stem}_relationships.parquet"
+ self.export_relationships(kg["relationships"], rels_path, **options)
+ exported_files.append(rels_path)
+ self.logger.info(f"Exported relationships to: {rels_path}")
+
+ self.logger.info(
+ f"Exported knowledge graph to {len(exported_files)} Parquet file(s)"
+ )
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Exported {len(exported_files)} Parquet files",
+ )
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def _write_parquet(
+ self,
+ data: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ schema: Optional["pa.Schema"] = None,
+ **options,
+ ) -> None:
+ """
+ Write data to Parquet file.
+
+ Internal method that handles the actual Parquet file writing using pyarrow.
+
+ Args:
+ data: List of dictionaries to write
+ file_path: Output Parquet file path
+ schema: Parquet schema to use (required for type safety)
+ **options: Additional parquet write options
+
+ Raises:
+ ProcessingError: If Parquet writing fails
+ ValidationError: If schema is not provided
+ """
+ if not schema:
+ raise ValidationError("Schema is required for Parquet export")
+
+ # Ensure file_path is a Path object
+ file_path = Path(file_path)
+
+ if not data:
+ self.logger.warning(f"No data to write to {file_path}")
+ # Write empty Parquet file with schema
+ empty_table = pa.table({field.name: [] for field in schema}, schema=schema)
+ pq.write_table(
+ empty_table, str(file_path), compression=self.compression, **options
+ )
+ return
+
+ try:
+ # Create PyArrow table from data using explicit schema
+ table = pa.Table.from_pylist(data, schema=schema)
+
+ # Write to Parquet file
+ pq.write_table(
+ table, str(file_path), compression=self.compression, **options
+ )
+
+ file_size = file_path.stat().st_size
+ self.logger.debug(
+ f"Wrote {len(data)} row(s) to {file_path} ({file_size} bytes)"
+ )
+
+ except pa.ArrowInvalid as e:
+ raise ProcessingError(
+ f"Failed to create Parquet table: {e}. "
+ "Check that data matches schema."
+ )
+ except Exception as e:
+ raise ProcessingError(f"Failed to write Parquet file: {e}")
diff --git a/tests/test_parquet_exporter.py b/tests/test_parquet_exporter.py
new file mode 100644
index 00000000..0ae37bf8
--- /dev/null
+++ b/tests/test_parquet_exporter.py
@@ -0,0 +1,441 @@
+"""
+Unit tests for Apache Parquet exporter module.
+
+Tests schema validation, data export, pandas conversion, empty inputs,
+and minimal graph structures.
+"""
+
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+
+# Try to import pyarrow
+try:
+ import pyarrow.parquet as pq
+
+ PARQUET_AVAILABLE = True
+except ImportError:
+ PARQUET_AVAILABLE = False
+
+from semantica.export import ParquetExporter
+from semantica.utils.exceptions import ValidationError
+
+
[email protected](not PARQUET_AVAILABLE, "pyarrow not installed")
+class TestParquetExporter(unittest.TestCase):
+ """Test cases for ParquetExporter class."""
+
+ def setUp(self):
+ """Set up test fixtures."""
+ self.test_dir = tempfile.mkdtemp()
+
+ # Sample entities with various field names
+ self.entities = [
+ {
+ "id": "e1",
+ "type": "Person",
+ "name": "Alice",
+ "label": "Alice",
+ "confidence": 0.95,
+ "start": 0,
+ "end": 5,
+ "metadata": {"age": 30, "city": "NYC"},
+ },
+ {
+ "id": "e2",
+ "type": "Organization",
+ "text": "Acme Corp",
+ "entity_type": "ORG",
+ "confidence": 0.88,
+ "start_offset": 10,
+ "end_offset": 19,
+ "metadata": {"location": "NY", "employees": 100},
+ },
+ ]
+
+ # Sample relationships
+ self.relationships = [
+ {
+ "id": "r1",
+ "source": "e1",
+ "target": "e2",
+ "type": "WORKS_FOR",
+ "confidence": 0.92,
+ "metadata": {"role": "Engineer", "since": 2020},
+ },
+ {
+ "source_id": "e2",
+ "target_id": "e1",
+ "relationship_type": "EMPLOYS",
+ "confidence": 0.90,
+ },
+ ]
+
+ # Knowledge graph
+ self.kg = {
+ "entities": self.entities,
+ "relationships": self.relationships,
+ "metadata": {"version": "1.0", "created": "2024-01-01"},
+ }
+
+ def tearDown(self):
+ """Clean up test directory."""
+ shutil.rmtree(self.test_dir)
+
+ def test_initialization(self):
+ """Test ParquetExporter initialization."""
+ exporter = ParquetExporter()
+ self.assertIsNotNone(exporter)
+ self.assertEqual(exporter.compression, "snappy")
+
+ # Test with different compression
+ exporter_gzip = ParquetExporter(compression="gzip")
+ self.assertEqual(exporter_gzip.compression, "gzip")
+
+ exporter_none = ParquetExporter(compression="none")
+ self.assertIsNone(exporter_none.compression)
+
+ def test_initialization_without_pyarrow(self):
+ """Test initialization fails gracefully without pyarrow."""
+ # This test verifies the constant is correctly set
+ if not PARQUET_AVAILABLE:
+ self.assertFalse(PARQUET_AVAILABLE)
+
+ def test_export_entities_basic(self):
+ """Test basic entity export to Parquet."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "entities.parquet"
+
+ exporter.export_entities(self.entities, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Read and verify Parquet file
+ table = pq.read_table(str(output_path))
+
+ # Verify schema
+ from semantica.export.parquet_exporter import ENTITY_SCHEMA
+
+ self.assertEqual(table.schema, ENTITY_SCHEMA)
+
+ # Verify data
+ self.assertEqual(table.num_rows, 2)
+ self.assertEqual(table.column("id")[0].as_py(), "e1")
+ self.assertEqual(table.column("type")[0].as_py(), "Person")
+ self.assertEqual(table.column("confidence")[0].as_py(), 0.95)
+
+ def test_export_entities_field_normalization(self):
+ """Test entity field name normalization."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "entities_normalized.parquet"
+
+ # Entities with various field name variations
+ varied_entities = [
+ {"id": "e1", "text": "Entity 1", "type": "TYPE1"},
+ {"entity_id": "e2", "label": "Entity 2", "entity_type": "TYPE2"},
+ {"id": "e3", "name": "Entity 3", "type": "TYPE3"},
+ ]
+
+ exporter.export_entities(varied_entities, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Read and verify normalization
+ table = pq.read_table(str(output_path))
+
+ self.assertEqual(table.num_rows, 3)
+ self.assertEqual(table.column("id")[0].as_py(), "e1")
+ self.assertEqual(table.column("text")[0].as_py(), "Entity 1")
+ self.assertEqual(table.column("text")[1].as_py(), "Entity 2")
+ self.assertEqual(table.column("text")[2].as_py(), "Entity 3")
+
+ def test_export_entities_with_compression(self):
+ """Test entity export with different compression codecs."""
+ for compression in ["snappy", "gzip", "brotli", "zstd", "lz4", "none"]:
+ with self.subTest(compression=compression):
+ exporter = ParquetExporter(compression=compression)
+ output_path = Path(self.test_dir) / f"entities_{compression}.parquet"
+
+ exporter.export_entities(self.entities, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Verify file can be read
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+
+ def test_export_entities_empty(self):
+ """Test exporting empty entities list raises ValidationError."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "empty_entities.parquet"
+
+ with self.assertRaises(ValidationError):
+ exporter.export_entities([], str(output_path))
+
+ def test_export_entities_metadata_handling(self):
+ """Test entity metadata is correctly serialized."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "entities_metadata.parquet"
+
+ exporter.export_entities(self.entities, str(output_path))
+
+ # Read and verify metadata
+ table = pq.read_table(str(output_path))
+ metadata_col = table.column("metadata")
+
+ # First entity should have metadata
+ first_metadata = metadata_col[0].as_py()
+ self.assertIsNotNone(first_metadata)
+ self.assertIn("keys", first_metadata)
+ self.assertIn("values", first_metadata)
+ self.assertEqual(set(first_metadata["keys"]), {"age", "city"})
+
+ def test_export_relationships_basic(self):
+ """Test basic relationship export to Parquet."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "relationships.parquet"
+
+ exporter.export_relationships(self.relationships, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Read and verify Parquet file
+ table = pq.read_table(str(output_path))
+
+ # Verify schema
+ from semantica.export.parquet_exporter import RELATIONSHIP_SCHEMA
+
+ self.assertEqual(table.schema, RELATIONSHIP_SCHEMA)
+
+ # Verify data
+ self.assertEqual(table.num_rows, 2)
+ self.assertEqual(table.column("id")[0].as_py(), "r1")
+ self.assertEqual(table.column("source_id")[0].as_py(), "e1")
+ self.assertEqual(table.column("target_id")[0].as_py(), "e2")
+ self.assertEqual(table.column("type")[0].as_py(), "WORKS_FOR")
+
+ def test_export_relationships_field_normalization(self):
+ """Test relationship field name normalization."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "relationships_normalized.parquet"
+
+ # Relationships with various field name variations
+ varied_rels = [
+ {"id": "r1", "source": "e1", "target": "e2", "type": "TYPE1"},
+ {"source_id": "e2", "target_id": "e3", "relationship_type": "TYPE2"},
+ {"from_id": "e3", "to_id": "e1", "relation_type": "TYPE3"},
+ ]
+
+ exporter.export_relationships(varied_rels, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Read and verify normalization
+ table = pq.read_table(str(output_path))
+
+ self.assertEqual(table.num_rows, 3)
+ self.assertEqual(table.column("source_id")[0].as_py(), "e1")
+ self.assertEqual(table.column("target_id")[0].as_py(), "e2")
+
+ def test_export_relationships_empty(self):
+ """Test exporting empty relationships list raises ValidationError."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "empty_relationships.parquet"
+
+ with self.assertRaises(ValidationError):
+ exporter.export_relationships([], str(output_path))
+
+ def test_export_relationships_auto_id_generation(self):
+ """Test relationship ID is auto-generated when missing."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "relationships_auto_id.parquet"
+
+ # Relationships without IDs
+ rels_no_id = [
+ {"source_id": "e1", "target_id": "e2", "type": "REL1"},
+ {"source_id": "e2", "target_id": "e3", "type": "REL2"},
+ ]
+
+ exporter.export_relationships(rels_no_id, str(output_path))
+
+ # Read and verify IDs were generated
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+ self.assertIsNotNone(table.column("id")[0].as_py())
+ self.assertIsNotNone(table.column("id")[1].as_py())
+
+ def test_export_knowledge_graph_basic(self):
+ """Test basic knowledge graph export to multiple Parquet files."""
+ exporter = ParquetExporter()
+ base_path = Path(self.test_dir) / "kg"
+
+ exporter.export_knowledge_graph(self.kg, str(base_path))
+
+ # Verify files were created
+ entities_path = Path(self.test_dir) / "kg_entities.parquet"
+ rels_path = Path(self.test_dir) / "kg_relationships.parquet"
+
+ self.assertTrue(entities_path.exists())
+ self.assertTrue(rels_path.exists())
+
+ # Verify entities
+ entities_table = pq.read_table(str(entities_path))
+ self.assertEqual(entities_table.num_rows, 2)
+
+ # Verify relationships
+ rels_table = pq.read_table(str(rels_path))
+ self.assertEqual(rels_table.num_rows, 2)
+
+ def test_export_knowledge_graph_invalid_input(self):
+ """Test knowledge graph export with invalid input raises ValidationError."""
+ exporter = ParquetExporter()
+ base_path = Path(self.test_dir) / "kg_invalid"
+
+ # Not a dictionary
+ with self.assertRaises(ValidationError):
+ exporter.export_knowledge_graph("not a dict", str(base_path))
+
+ # Missing both entities and relationships
+ with self.assertRaises(ValidationError):
+ exporter.export_knowledge_graph({"metadata": {}}, str(base_path))
+
+ def test_export_knowledge_graph_partial(self):
+ """Test knowledge graph export with only entities or relationships."""
+ exporter = ParquetExporter()
+
+ # Only entities
+ kg_entities_only = {"entities": self.entities}
+ base_path_ent = Path(self.test_dir) / "kg_entities_only"
+ exporter.export_knowledge_graph(kg_entities_only, str(base_path_ent))
+
+ entities_path = Path(self.test_dir) / "kg_entities_only_entities.parquet"
+ self.assertTrue(entities_path.exists())
+
+ # Only relationships
+ kg_rels_only = {"relationships": self.relationships}
+ base_path_rel = Path(self.test_dir) / "kg_rels_only"
+ exporter.export_knowledge_graph(kg_rels_only, str(base_path_rel))
+
+ rels_path = Path(self.test_dir) / "kg_rels_only_relationships.parquet"
+ self.assertTrue(rels_path.exists())
+
+ def test_export_generic_list(self):
+ """Test generic export with list of dictionaries."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "generic_list.parquet"
+
+ exporter.export(self.entities, str(output_path), schema=None)
+ self.assertTrue(output_path.exists())
+
+ # Verify file can be read (schema auto-selected based on data structure)
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+
+ def test_export_generic_dict(self):
+ """Test generic export with dictionary (multiple files)."""
+ exporter = ParquetExporter()
+ base_path = Path(self.test_dir) / "generic_dict"
+
+ data_dict = {"entities": self.entities, "relationships": self.relationships}
+
+ exporter.export(data_dict, str(base_path))
+
+ # Verify both files were created
+ entities_path = Path(self.test_dir) / "generic_dict_entities.parquet"
+ rels_path = Path(self.test_dir) / "generic_dict_relationships.parquet"
+
+ self.assertTrue(entities_path.exists())
+ self.assertTrue(rels_path.exists())
+
+ def test_export_invalid_data_type(self):
+ """Test export with invalid data type raises ValidationError."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "invalid.parquet"
+
+ with self.assertRaises(ValidationError):
+ exporter.export("invalid string data", str(output_path))
+
+ def test_pandas_compatibility(self):
+ """Test exported Parquet files can be read by pandas."""
+ try:
+ import pandas as pd
+ except ImportError:
+ self.skipTest("pandas not installed")
+
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "pandas_test.parquet"
+
+ exporter.export_entities(self.entities, str(output_path))
+
+ # Read with pandas
+ df = pd.read_parquet(str(output_path))
+
+ self.assertEqual(len(df), 2)
+ self.assertIn("id", df.columns)
+ self.assertIn("text", df.columns)
+ self.assertIn("type", df.columns)
+
+ def test_file_size_comparison(self):
+ """Test Parquet file sizes with different compression."""
+ exporter_snappy = ParquetExporter(compression="snappy")
+ exporter_gzip = ParquetExporter(compression="gzip")
+ exporter_none = ParquetExporter(compression="none")
+
+ path_snappy = Path(self.test_dir) / "size_snappy.parquet"
+ path_gzip = Path(self.test_dir) / "size_gzip.parquet"
+ path_none = Path(self.test_dir) / "size_none.parquet"
+
+ # Create larger dataset for meaningful comparison
+ large_entities = self.entities * 100
+
+ exporter_snappy.export_entities(large_entities, str(path_snappy))
+ exporter_gzip.export_entities(large_entities, str(path_gzip))
+ exporter_none.export_entities(large_entities, str(path_none))
+
+ size_snappy = path_snappy.stat().st_size
+ size_none = path_none.stat().st_size
+
+ # Uncompressed should be largest
+ self.assertGreater(size_none, size_snappy)
+
+ # All files should be readable
+ for path in [path_snappy, path_gzip, path_none]:
+ table = pq.read_table(str(path))
+ self.assertEqual(table.num_rows, 200)
+
+ def test_entity_missing_id_skipped(self):
+ """Test entities without IDs are skipped with warning."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "entities_missing_id.parquet"
+
+ # Mix of entities with and without IDs
+ entities_mixed = [
+ {"id": "e1", "text": "Valid Entity"},
+ {"text": "Missing ID"}, # No ID
+ {"id": "e2", "text": "Another Valid"},
+ ]
+
+ exporter.export_entities(entities_mixed, str(output_path))
+
+ # Only 2 entities should be exported (one without ID is skipped)
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+
+ def test_relationship_missing_source_target_skipped(self):
+ """Test relationships without source/target are skipped with warning."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "rels_missing.parquet"
+
+ # Mix of valid and invalid relationships
+ rels_mixed = [
+ {"id": "r1", "source_id": "e1", "target_id": "e2"},
+ {"id": "r2", "target_id": "e2"}, # Missing source
+ {"id": "r3", "source_id": "e1"}, # Missing target
+ {"id": "r4", "source_id": "e3", "target_id": "e4"},
+ ]
+
+ exporter.export_relationships(rels_mixed, str(output_path))
+
+ # Only 2 valid relationships should be exported
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()