Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Remove KuzuDB backend support and cleanup references

KaifAhmad1afc94ad059af
diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.md
index f65603af..41e7a8c8 100644
--- a/PR_DESCRIPTION.md
+++ b/PR_DESCRIPTION.md
@@ -1,54 +1,34 @@
-# PR: Dynamic Embedding Model Switching & Enhanced Testing
+# Enhanced Export Module Testing, Bug Fixes & Notebook Updates
## Summary
-This PR introduces dynamic model switching capabilities to the Semantica embeddings module, allowing users to switch between `sentence_transformers` and `fastembed` providers at runtime. It also includes comprehensive updates to documentation, cookbooks, and a robust new test suite to validate all core features.
+This PR significantly hardens the `semantica.export` module by adding comprehensive unit tests, fixing critical bugs in export wrappers and logic, and updating documentation and cookbooks to match current API signatures.
## Key Changes
-### 1. Dynamic Model Switching
-- **Added** `set_model()` and `set_text_model()` methods to `EmbeddingGenerator` and `TextEmbedder`.
-- **Feature**: Users can now change the underlying embedding model and provider without re-instantiating the classes.
-- **Validation**: Added checks to ensure the requested provider (e.g., `fastembed`) is installed before switching.
-
-### 2. Documentation Updates
-- **`semantica/embeddings/embeddings_usage.md`**: Added a new section **"Dynamic Model Switching"** with code examples.
-- **`docs/reference/embeddings.md`**: Updated API reference tables to include the new model selection methods.
-
-### 3. Cookbook Refactoring
-- **`12_Embedding_Generation.ipynb`**: Added **"Step 3: Model Selection & Dynamic Switching"** to demonstrate the new API.
-- **`13_Vector_Store.ipynb`**: Replaced random vector generation with **real embeddings** using `TextEmbedder`, ensuring the tutorial reflects real-world usage.
-- **`Advanced_Vector_Store_and_Search.ipynb`**: Added an embedding setup section and dynamically updated vector dimensions.
-
-### 4. Testing Framework
-- **New Test File**: `tests/test_all_features.py` - A comprehensive test suite covering 8 critical areas:
- 1. Embedding Generation
- 2. Provider Selection
- 3. **Dynamic Model Switching** (New)
- 4. Vector Store Operations
- 5. Metadata Filtering
- 6. Hybrid Search
- 7. Convenience Functions
- 8. Error Handling
-- **Existing Tests**: Verified compatibility with existing tests (`tests/test_model_selection.py`, etc.).
-- **CI/CD**: `pytest` passes all tests with Exit Code 0.
-
-## How to Test
-1. Checkout the branch:
- ```bash
- git checkout embeddings
- ```
-2. Run the comprehensive test suite:
- ```bash
- python tests/test_all_features.py
- ```
-3. Run the full regression suite:
- ```bash
- pytest tests/
- ```
-
-## Checklist
-- [x] Code follows the style guidelines of this project
-- [x] Documentation has been updated
-- [x] Jupyter Notebooks (Cookbooks) have been tested and updated
-- [x] New unit tests have been added
-- [x] All existing tests pass
+### 1. Bug Fixes & Logic Improvements
+- **`semantica/export/methods.py`**:
+ - Fixed `export_yaml(method="schema")` to correctly call `export_ontology_schema` and handle file writing (previously failed as the underlying method returns a string).
+ - Added safeguards to all convenience functions (`export_rdf`, `export_json`, etc.) to prevent infinite recursion if the registry returns the wrapper function itself.
+- **`semantica/kg/graph_builder.py`**: Fixed a critical bug where `ConflictDetector` was receiving the entire graph dictionary instead of the entity list.
+- **`semantica/export/rdf_exporter.py`**: Fixed `export_to_rdf` to correctly return serialized data for all formats.
+
+### 2. Comprehensive Testing (`tests/`)
+- **`tests/test_export_module.py`**: A full suite of unit tests covering all 11 export classes (`JSON`, `CSV`, `RDF`, `GraphML`, `YAML`, `OWL`, `Vector`, `LPG`, etc.).
+- **`tests/test_export_methods_wrapper.py`**: Added specific tests for convenience wrapper functions in `methods.py`, verifying the fix for schema export.
+- **`tests/test_notebook_15_export.py`** & **`tests/test_notebooks_simulation.py`**: Simulation tests that replicate cookbook logic to ensure end-to-end functionality.
+
+### 3. Documentation & Notebook Updates
+- **`docs/reference/export.md`** & **`semantica/export/export_usage.md`**: Updated to correctly document `YAMLSchemaExporter.export_ontology_schema` instead of the deprecated `export` method.
+- **Cookbooks** (`15_Export.ipynb`, `05_Multi_Format_Export.ipynb`):
+ - Updated `GraphBuilder.build()` calls to pass combined lists (fixing API mismatch).
+ - Corrected `YAMLSchemaExporter` usage.
+ - Fixed `VectorExporter` data preparation.
+ - Adjusted `CSVExporter` paths.
+
+## Verification
+All tests passed successfully:
+```bash
+$ pytest tests/test_export_module.py tests/test_notebooks_simulation.py tests/test_notebook_15_export.py tests/test_export_methods_wrapper.py
+...
+13 passed in 3.82s
+```
diff --git a/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb b/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
index 904246ce..9e41667c 100644
--- a/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
+++ b/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb
@@ -22,7 +22,7 @@
"- Use CommunityDetector for community detection\n",
"- Use ConnectivityAnalyzer for connectivity analysis\n",
"- Use GraphValidator and Deduplicator for graph quality\n",
- "- **Use GraphStore to persist graphs to Neo4j, KuzuDB, or FalkorDB**\n",
+ "- **Use GraphStore to persist graphs to Neo4j or FalkorDB**\n",
"\n",
"## Installation\n",
"\n",
@@ -193,8 +193,8 @@
"source": [
"from semantica.graph_store import GraphStore\n",
"\n",
- "# Initialize graph store (using KuzuDB for embedded storage)\n",
- "graph_store = GraphStore(backend=\"kuzu\", database_path=\"./analytics_graph_db\")\n",
+ "# Option 1: Neo4j (requires Neo4j server running)\n",
+ "graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"graph_store.connect()\n",
"\n",
"# Store entities as nodes and track node ID mapping\n",
@@ -251,7 +251,7 @@
"- **ConnectivityAnalyzer**: Connectivity analysis\n",
"- **GraphValidator**: Graph validation\n",
"- **Deduplicator**: Graph deduplication\n",
- "- **GraphStore**: Persist graphs to Neo4j, KuzuDB, or FalkorDB\n"
+ "- **GraphStore**: Persist graphs to Neo4j or FalkorDB\n",
]
}
],
diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
index e09467f5..534d9857 100644
--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb
+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
@@ -234,17 +234,16 @@
"```\n",
"\n",
"### 8. GRAPH_STORE MODULE - Persistent Graph Database Operations\n",
- "**Purpose**: Store and query property graphs in Neo4j, KuzuDB, or FalkorDB\n",
- "**Components**:\n",
- "- `GraphStore`: Main graph store interface\n",
- "- `Neo4jAdapter`: Neo4j integration (enterprise features)\n",
- "- `KuzuAdapter`: KuzuDB integration (embedded, no server)\n",
- "- `FalkorDBAdapter`: FalkorDB integration (Redis-based, ultra-fast)\n",
- "\n",
- "**Example**:\n",
- "```python\n",
- "from semantica.graph_store import GraphStore\n",
- "store = GraphStore(backend=\"kuzu\", database_path=\"./my_graph_db\")\n",
+ "**Purpose**: Store and query property graphs in Neo4j or FalkorDB\n",
+ "**Components**:\n",
+ "- `GraphStore`: Main graph store interface\n",
+ "- `Neo4jAdapter`: Neo4j integration (enterprise features)\n",
+ "- `FalkorDBAdapter`: FalkorDB integration (Redis-based, ultra-fast)\n",
+ "\n",
+ "**Example**:\n",
+ "```python\n",
+ "from semantica.graph_store import GraphStore\n",
+ "store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"store.connect()\n",
"node1 = store.create_node(\n",
" labels=[\"Person\"],\n",
diff --git a/cookbook/introduction/09_Graph_Store.ipynb b/cookbook/introduction/09_Graph_Store.ipynb
index 2746076d..313cbad9 100644
--- a/cookbook/introduction/09_Graph_Store.ipynb
+++ b/cookbook/introduction/09_Graph_Store.ipynb
@@ -8,11 +8,11 @@
"\n",
"## Overview\n",
"\n",
- "The Graph Store module provides a unified interface for working with property graph databases. It supports multiple backends (Neo4j, KuzuDB, FalkorDB) and offers comprehensive features for storing, querying, and analyzing graph data.\n",
+ "The Graph Store module provides a unified interface for working with property graph databases. It supports multiple backends (Neo4j, FalkorDB) and offers comprehensive features for storing, querying, and analyzing graph data.\n",
"\n",
"### Key Features\n",
"\n",
- "- **Multi-Backend Support**: Neo4j (Enterprise), KuzuDB (Embedded), FalkorDB (Redis-based)\n",
+ "- **Multi-Backend Support**: Neo4j (Enterprise), FalkorDB (Redis-based)\n",
"- **Full CRUD Operations**: Create, read, update, delete nodes and relationships\n",
"- **Cypher Query Language**: Execute complex graph queries with OpenCypher support\n",
"- **Graph Analytics**: Built-in algorithms for centrality, community detection, path finding\n",
@@ -54,9 +54,7 @@
"# For Neo4j (requires Neo4j server)\n",
"pip install neo4j\n",
"\n",
- "# For KuzuDB (embedded - no server required)\n",
- "pip install kuzu\n",
- "\n",
+
"# For FalkorDB (requires Redis/FalkorDB server)\n",
"pip install falkordb\n",
"```\n",
@@ -78,10 +76,9 @@
"| Backend | Best For | Deployment | Features |\n",
"|---------|----------|------------|----------|\n",
"| **Neo4j** | Enterprise applications, production systems | Server/Cloud | Full Cypher, APOC procedures, multi-database |\n",
- "| **KuzuDB** | Analytics, embedded applications, development | Embedded (no server) | Fast analytical queries, zero-config |\n",
"| **FalkorDB** | LLM applications, real-time systems, high performance | Redis-based | Ultra-fast, sparse matrix operations |\n",
"\n",
- "**Recommendation**: Start with **KuzuDB** for development and learning (no setup required), then move to **Neo4j** or **FalkorDB** for production.\n"
+ "**Recommendation**: Use **Neo4j** for enterprise production systems or **FalkorDB** for high-performance real-time applications.\n"
]
},
{
@@ -90,7 +87,7 @@
"source": [
"## Step 1: Initialize Graph Store\n",
"\n",
- "Initialize a `GraphStore` instance with your preferred backend. For this tutorial, we'll use **KuzuDB** (embedded, no server setup required).\n"
+ "Initialize a `GraphStore` instance with your preferred backend. For this tutorial, we'll use **Neo4j** (requires a running server).\n"
]
},
{
@@ -102,20 +99,14 @@
"from semantica.graph_store import GraphStore\n",
"\n",
"# Option 1: Neo4j (requires Neo4j server running)\n",
- "# store = GraphStore(\n",
- "# backend=\"neo4j\",\n",
- "# uri=\"bolt://localhost:7687\",\n",
- "# user=\"neo4j\",\n",
- "# password=\"password\"\n",
- "# )\n",
- "\n",
- "# Option 2: KuzuDB (embedded - no server required) - Recommended for learning\n",
"store = GraphStore(\n",
- " backend=\"kuzu\",\n",
- " database_path=\"./demo_graph_db\"\n",
+ " backend=\"neo4j\",\n",
+ " uri=\"bolt://localhost:7687\",\n",
+ " user=\"neo4j\",\n",
+ " password=\"password\"\n",
")\n",
"\n",
- "# Option 3: FalkorDB (requires Redis/FalkorDB server)\n",
+ "# Option 2: FalkorDB (requires Redis/FalkorDB server)\n",
"# store = GraphStore(\n",
"# backend=\"falkordb\",\n",
"# host=\"localhost\",\n",
@@ -553,7 +544,6 @@
"\n",
"# Note: Index creation support varies by backend\n",
"# Neo4j: Full support for various index types\n",
- "# KuzuDB: Automatic indexing on primary keys\n",
"# FalkorDB: Limited index support\n"
]
},
@@ -583,7 +573,7 @@
"source": [
"## Summary\n",
"\n",
- "This notebook covered the Graph Store module, a unified interface for property graph databases supporting Neo4j, KuzuDB, and FalkorDB.\n",
+ "This notebook covered the Graph Store module, a unified interface for property graph databases supporting Neo4j and FalkorDB.\n",
"\n",
"### What You Learned\n",
"\n",
@@ -595,7 +585,7 @@
"\n",
"### Key Takeaways\n",
"\n",
- "- **Backend Selection**: Use KuzuDB for development, Neo4j for production, FalkorDB for high-performance applications\n",
+ "- **Backend Selection**: Use Neo4j for production, FalkorDB for high-performance applications\n",
"- **Best Practices**: Use batch operations, parameterized queries, and proper connection management\n",
"- **Next Steps**: Explore advanced analytics, graph quality, and visualization modules\n"
]
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 6223c6b1..442a6c26 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -644,8 +644,8 @@
"outputs": [],
"source": [
"# Optional: Store graph in persistent graph database\n",
- "# Uncomment to use KuzuDB (embedded, no server required)\n",
- "# graph_store = GraphStore(backend=\"kuzu\", database_path=\"./graphrag_db\")\n",
+ "# Uncomment to use Neo4j\n",
+ "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"# graph_store.connect()\n",
"# \n",
"# # Store nodes and track node ID mapping\n",
@@ -813,7 +813,8 @@
" print(\"No vectors to store\")\n",
"\n",
"print(\"\\nStoring graph-aware chunks in graph store...\")\n",
- "graph_store = GraphStore(backend=\"kuzu\", database_path=\"./graphrag_db\")\n",
+ "# Option 1: Neo4j (requires Neo4j server running)\n",
+ "graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"graph_store.connect()\n",
"\n",
"for i, chunk in enumerate(graph_store_chunks):\n",
diff --git a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
index 35c55857..38c03d5a 100644
--- a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
+++ b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
@@ -402,8 +402,8 @@
"# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"blockchain_graph\")\n",
"\n",
- "# For this demo, use embedded KuzuDB\n",
- "graph_store = GraphStore(backend=\"kuzu\", database_path=\"./blockchain_tx_db\")\n",
+ "# Option 1: Neo4j (requires Neo4j server running)\n",
+ " graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
"graph_store.connect()\n",
"\n",
"# Store wallet nodes\n",
diff --git a/cookbook/use_cases/finance/03_Fraud_Detection.ipynb b/cookbook/use_cases/finance/03_Fraud_Detection.ipynb
index e998c893..619e5a1e 100644
--- a/cookbook/use_cases/finance/03_Fraud_Detection.ipynb
+++ b/cookbook/use_cases/finance/03_Fraud_Detection.ipynb
@@ -234,9 +234,9 @@
"# For production: use FalkorDB with Redis for ultra-fast queries\n",
"# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"fraud_graph\")\n",
"\n",
- "# For this demo, use embedded KuzuDB\n",
- "graph_store = GraphStore(backend=\"kuzu\", database_path=\"./fraud_detection_db\")\n",
- "graph_store.connect()\n",
+ "# Option 1: Neo4j (requires Neo4j server running)\n",
+ " graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
+ " graph_store.connect()\n",
"\n",
"# Store transaction entities in graph database\n",
"node_id_map = {}\n",
diff --git a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
index 6d354424..d06a7e3e 100644
--- a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
+++ b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
@@ -488,11 +488,13 @@
"\n",
"# Initialize graph store for persistent criminal network storage\n",
"# For production: use Neo4j for enterprise features or FalkorDB for real-time queries\n",
- "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
+ "\n",
+ "# Option 1: Neo4j\n",
+ "graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
+ "\n",
+ "# Option 2: FalkorDB\n",
"# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"criminal_network\")\n",
"\n",
- "# For this demo, use embedded KuzuDB\n",
- "graph_store = GraphStore(backend=\"kuzu\", database_path=\"./criminal_network_db\")\n",
"graph_store.connect()\n",
"\n",
"# Store entities as nodes\n",
diff --git a/docs/CodeExamples.md b/docs/CodeExamples.md
index 01e07302..e98ed609 100644
--- a/docs/CodeExamples.md
+++ b/docs/CodeExamples.md
@@ -14,7 +14,6 @@ pip install "semantica[pdf,web,feeds,office]"
# Graph store backends
pip install "semantica[graph-neo4j]" # Neo4j support
-pip install "semantica[graph-kuzu]" # KuzuDB (embedded)
pip install "semantica[graph-falkordb]" # FalkorDB (Redis-based)
pip install "semantica[graph-all]" # All graph backends
@@ -286,7 +285,7 @@ ontology.save_to_triple_store("http://localhost:9999/blazegraph/sparql")
### πŸ“Š Graph Store - Persistent Property Graph Storage
-Store and query knowledge graphs in Neo4j, KuzuDB, or FalkorDB:
+Store and query knowledge graphs in Neo4j or FalkorDB:
```python
from semantica.graph_store import GraphStore
@@ -299,9 +298,6 @@ store = GraphStore(
password="password"
)
-# Option 2: KuzuDB for embedded (no server required)
-store = GraphStore(backend="kuzu", database_path="./my_graph_db")
-
# Option 3: FalkorDB for ultra-fast LLM applications
store = GraphStore(backend="falkordb", host="localhost", port=6379, graph_name="kg")
diff --git a/docs/architecture.md b/docs/architecture.md
index 67184ca6..61b6b7c6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -68,7 +68,7 @@ graph TB
- **`semantica.kg`** - Knowledge graph construction
- **`semantica.vector_store`** - Vector storage (Pinecone, Weaviate, FAISS)
- **`semantica.triple_store`** - RDF triple storage (Jena, Blazegraph)
-- **`semantica.graph_store`** - Property graphs (Neo4j, KuzuDB, FalkorDB)
+- **`semantica.graph_store`** - Property graphs (Neo4j, FalkorDB)
### Quality Assurance
- **`semantica.deduplication`** - Entity deduplication
diff --git a/docs/community-projects.md b/docs/community-projects.md
index 30e859a7..4a806efa 100644
--- a/docs/community-projects.md
+++ b/docs/community-projects.md
@@ -33,7 +33,6 @@ Projects and integrations from the Semantica community.
### Graph Databases
- Neo4j
-- KuzuDB
- FalkorDB
### LLM Providers
diff --git a/docs/concepts.md b/docs/concepts.md
index 02bb6991..12dd4938 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -2830,7 +2830,6 @@ flowchart LR
| :--- | :--- | :--- | :--- | :--- | :--- |
| **NetworkX**| In-memory | Fast | Small-medium | Python API | Development, small graphs |
| **Neo4j** | Database | Medium | Large | Cypher | Production, complex queries |
-| **KuzuDB** | Embedded | Fast | Medium | Cypher | Embedded applications |
| **FalkorDB**| Redis-based| Very Fast | Large | Cypher | Real-time, high throughput |
---
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 128caee8..1c2c1a82 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -154,7 +154,7 @@ Essential guides to master the Semantica framework.
- :material-database-settings: **Graph Store**
---
- Persisting knowledge graphs in Neo4j, KuzuDB, or FalkorDB.
+ Persisting knowledge graphs in Neo4j or FalkorDB.
**Topics**: Neo4j, Cypher, Persistence
diff --git a/docs/faq.md b/docs/faq.md
index ce8ffd9f..28891192 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -165,7 +165,7 @@ Yes, Semantica can be integrated with LangChain for RAG applications.
### Can I connect to databases?
-Yes, Semantica supports connections to Neo4j, KuzuDB, FalkorDB, and other graph databases.
+Yes, Semantica supports connections to Neo4j, FalkorDB, and other graph databases.
---
diff --git a/docs/getting-started.md b/docs/getting-started.md
index ddd092d5..4165aec6 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -106,7 +106,7 @@ knowledge_graph:
temporal: true
graph_store:
- backend: neo4j # or kuzu, falkordb
+ backend: neo4j # or falkordb
neo4j_uri: bolt://localhost:7687
neo4j_user: neo4j
neo4j_password: password
diff --git a/docs/learning-more.md b/docs/learning-more.md
index 179e5d1d..2151349e 100644
--- a/docs/learning-more.md
+++ b/docs/learning-more.md
@@ -183,11 +183,11 @@ result = semantica.build_knowledge_base(
### 3. Backend Selection
-| Operation | NetworkX | Neo4j | KuzuDB |
-| :--- | :--- | :--- | :--- |
-| **Graph Construction** | ⚑⚑⚑ | ⚑⚑ | ⚑⚑⚑ |
-| **Query Performance** | ⚑⚑ | ⚑⚑⚑ | ⚑⚑⚑ |
-| **Scalability** | Low | High | Medium |
+| Operation | NetworkX | Neo4j |
+| :--- | :--- | :--- |
+| **Graph Construction** | ⚑⚑⚑ | ⚑⚑ |
+| **Query Performance** | ⚑⚑ | ⚑⚑⚑ |
+| **Scalability** | Low | High |
---
diff --git a/docs/modules.md b/docs/modules.md
index 41a7dc08..e7c99271 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -277,7 +277,7 @@ for rel in relationships[:5]:
**Key Features:**
- Graph construction from entities/relationships
-- Multiple backend support (NetworkX, Neo4j, KuzuDB)
+- Multiple backend support (NetworkX, Neo4j)
- Temporal graph support
- Graph analytics and metrics
- Entity resolution and deduplication
@@ -513,7 +513,7 @@ results = hybrid_search.search(
**Key Features:**
-- Multiple backend support (Neo4j, KuzuDB, FalkorDB)
+- Multiple backend support (Neo4j, FalkorDB)
- Cypher query language
- Graph algorithms and analytics
- Transaction support
@@ -525,7 +525,6 @@ results = hybrid_search.search(
- `GraphStore` β€” Main graph store interface
- `Neo4jAdapter` β€” Neo4j database integration
-- `KuzuAdapter` β€” KuzuDB embedded database integration
- `FalkorDBAdapter` β€” FalkorDB (Redis-based) integration
- `NodeManager` β€” Node CRUD operations
- `RelationshipManager` β€” Relationship CRUD operations
diff --git a/docs/reference/graph_store.md b/docs/reference/graph_store.md
index e9c78827..589f5661 100644
--- a/docs/reference/graph_store.md
+++ b/docs/reference/graph_store.md
@@ -1,6 +1,6 @@
# Graph Store
-> **Unified interface for Property Graph Databases (Neo4j, KuzuDB, FalkorDB).**
+> **Unified interface for Property Graph Databases (Neo4j, FalkorDB).**
---
@@ -12,7 +12,7 @@
---
- Support for Neo4j (Enterprise), KuzuDB (Embedded), and FalkorDB (Redis-based)
+ Support for Neo4j (Enterprise) and FalkorDB (Redis-based)
- :material-code-braces:{ .lg .middle } **Cypher Support**
@@ -187,26 +187,6 @@ Enterprise-grade Neo4j backend adapter.
- `Neo4jSession` - Session management wrapper
- `Neo4jTransaction` - Transaction wrapper
-#### KuzuAdapter
-
-Embedded, in-process KuzuDB backend adapter.
-
-**Features:**
-- No external server required
-- Columnar storage for speed
-- Zero-copy integration with Arrow
-- Schema-based node and relationship tables
-- High-performance analytical queries
-
-**Related Classes:**
-- `KuzuDatabase` - Database wrapper
-- `KuzuConnection` - Connection wrapper
-- `KuzuQuery` - Query execution wrapper
-
-**Special Methods:**
-- `create_node_table(table_name, properties, primary_key, **options)` - Create node table with schema
-- `create_rel_table(table_name, from_table, to_table, properties, **options)` - Create relationship table
-- `bulk_load_nodes(table_name, file_path, **options)` - Bulk load nodes from CSV
#### FalkorDBAdapter
@@ -243,7 +223,6 @@ Configuration manager for graph store module. Supports environment variables, co
- `set_method_config(method_name, config)` - Set method-specific configuration
- `get_all()` - Get all configuration
- `get_neo4j_config()` - Get Neo4j-specific configuration
-- `get_kuzu_config()` - Get KuzuDB-specific configuration
- `get_falkordb_config()` - Get FalkorDB-specific configuration
- `reset()` - Reset configuration to defaults
@@ -394,9 +373,6 @@ graph_store:
uri: bolt://localhost:7687
pool_size: 50
- kuzu:
- path: ./data/kuzu_db
- buffer_pool_size: 1024 # MB
```
---
diff --git a/pyproject.toml b/pyproject.toml
index a5281b95..6af89586 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -65,6 +65,7 @@ dependencies = [
"weaviate-client>=3.15.0",
"qdrant-client>=1.3.0",
"neo4j>=5.0.0",
+ "falkordb>=1.0.0",
"pymongo>=4.2.0",
"sqlalchemy>=1.4.0",
"psycopg2-binary>=2.9.0",
@@ -186,15 +187,12 @@ split-all = [
graph-neo4j = [
"neo4j>=5.0.0"
]
-graph-kuzu = [
- "kuzu>=0.4.0"
-]
graph-falkordb = [
"falkordb>=1.0.0",
"redis>=4.3.0"
]
graph-all = [
- "semantica[graph-neo4j,graph-kuzu,graph-falkordb]"
+ "semantica[graph-neo4j,graph-falkordb]"
]
all = [
"semantica[dev,viz,gpu,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all]"
diff --git a/semantica/embeddings/embeddings_usage.md b/semantica/embeddings/embeddings_usage.md
index 791db03f..41e2edee 100644
--- a/semantica/embeddings/embeddings_usage.md
+++ b/semantica/embeddings/embeddings_usage.md
@@ -645,13 +645,6 @@ networkx_result = manager.prepare_for_graph_db(
graph_type="DiGraph"
)
-# Prepare for KuzuDB
-kuzu_result = manager.prepare_for_graph_db(
- entities,
- backend="kuzu",
- database_path="./kuzu_db"
-)
-
# Prepare for FalkorDB
falkordb_result = manager.prepare_for_graph_db(
entities,
diff --git a/semantica/embeddings/graph_embedding_manager.py b/semantica/embeddings/graph_embedding_manager.py
index 27808e8e..da5e5140 100644
--- a/semantica/embeddings/graph_embedding_manager.py
+++ b/semantica/embeddings/graph_embedding_manager.py
@@ -9,7 +9,7 @@ Key Features:
- Generate embeddings for graph entities (nodes)
- Generate embeddings for graph relationships (edges)
- Format embeddings for graph DB storage
- - Integration helpers for Neo4j, NetworkX, KuzuDB, FalkorDB
+ - Integration helpers for Neo4j, NetworkX, FalkorDB
Example Usage:
>>> from semantica.embeddings import GraphEmbeddingManager
@@ -37,7 +37,6 @@ class GraphEmbeddingManager:
Supported Backends:
- Neo4j: Graph database with Cypher query language
- NetworkX: Python graph library
- - KuzuDB: Embedded graph database
- FalkorDB: Redis-based graph database
Example Usage:
@@ -82,7 +81,7 @@ class GraphEmbeddingManager:
entities: List of entity dictionaries with at least "id" and "text" or "content"
relationships: Optional list of relationship dictionaries with
"source", "target", and optionally "text" or "type"
- backend: Graph DB backend ("neo4j", "networkx", "kuzu", "falkordb")
+ backend: Graph DB backend ("neo4j", "networkx", "falkordb")
**options: Additional backend-specific options
Returns:
@@ -108,10 +107,10 @@ class GraphEmbeddingManager:
... entities, relationships, backend="neo4j"
... )
"""
- if backend.lower() not in ["neo4j", "networkx", "kuzu", "falkordb"]:
+ if backend.lower() not in ["neo4j", "networkx", "falkordb"]:
raise ProcessingError(
f"Unsupported backend: {backend}. "
- f"Supported: neo4j, networkx, kuzu, falkordb"
+ f"Supported: neo4j, networkx, falkordb"
)
# Generate node embeddings
@@ -396,8 +395,6 @@ class GraphEmbeddingManager:
info["label"] = options.get("label", "Node")
elif backend.lower() == "networkx":
info["graph_type"] = options.get("graph_type", "DiGraph")
- elif backend.lower() == "kuzu":
- info["database_path"] = options.get("database_path", "default")
elif backend.lower() == "falkordb":
info["graph_name"] = options.get("graph_name", "default")
diff --git a/semantica/graph_store/__init__.py b/semantica/graph_store/__init__.py
index e8627fc3..aea23f77 100644
--- a/semantica/graph_store/__init__.py
+++ b/semantica/graph_store/__init__.py
@@ -2,14 +2,14 @@
Graph Store Module
This module provides comprehensive property graph database integration for the
-Semantica framework, supporting multiple graph database backends including Neo4j,
-KuzuDB, and FalkorDB for storing and querying knowledge graphs.
+Semantica framework, supporting multiple graph database backends including Neo4j
+and FalkorDB for storing and querying knowledge graphs.
Algorithms Used:
Graph Store Management:
- Store Registration: Store type detection, adapter factory pattern, configuration management, default store selection
- - Adapter Pattern: Unified interface for multiple backends (Neo4j, KuzuDB, FalkorDB), adapter instantiation, backend-specific operation delegation
+ - Adapter Pattern: Unified interface for multiple backends (Neo4j, FalkorDB), adapter instantiation, backend-specific operation delegation
- Store Selection: Default store resolution, store ID lookup, store validation
Node and Relationship Operations:
@@ -37,7 +37,6 @@ Graph Analytics:
Store Adapters:
- Neo4j Adapter: Official Neo4j Python driver, Bolt protocol communication, transaction support, multi-database support, APOC procedures
- - KuzuDB Adapter: Embedded graph database, in-memory and persistent storage, Cypher support, high-performance analytical queries
- FalkorDB Adapter: Redis-based graph database, sparse matrix representation, linear algebra queries, OpenCypher support, ultra-fast performance
Bulk Operations:
@@ -46,7 +45,7 @@ Bulk Operations:
- Progress Tracking: Load progress calculation, elapsed time tracking, throughput calculation
Key Features:
- - Multi-backend property graph support (Neo4j, KuzuDB, FalkorDB)
+ - Multi-backend property graph support (Neo4j, FalkorDB)
- Full Cypher/OpenCypher query language support
- Node and relationship CRUD operations
- Graph traversal and path finding
@@ -61,7 +60,6 @@ Main Classes:
- GraphStore: Main graph store interface
- GraphManager: Graph store management and operations
- Neo4jAdapter: Neo4j integration adapter
- - KuzuAdapter: KuzuDB integration adapter
- FalkorDBAdapter: FalkorDB integration adapter
- NodeManager: Node CRUD operations
- RelationshipManager: Relationship CRUD operations
@@ -110,7 +108,6 @@ from .graph_store import (
QueryEngine,
RelationshipManager,
)
-from .kuzu_adapter import KuzuAdapter, KuzuConnection, KuzuDatabase, KuzuQuery
from .methods import (
create_node,
create_nodes,
@@ -145,11 +142,6 @@ __all__ = [
"Neo4jDriver",
"Neo4jSession",
"Neo4jTransaction",
- # KuzuDB
- "KuzuAdapter",
- "KuzuDatabase",
- "KuzuConnection",
- "KuzuQuery",
# FalkorDB
"FalkorDBAdapter",
"FalkorDBClient",
diff --git a/semantica/graph_store/config.py b/semantica/graph_store/config.py
index 550816b3..d779027f 100644
--- a/semantica/graph_store/config.py
+++ b/semantica/graph_store/config.py
@@ -119,10 +119,6 @@ class GraphStoreConfig:
"GRAPH_STORE_NEO4J_PASSWORD": "neo4j_password",
"GRAPH_STORE_NEO4J_DATABASE": "neo4j_database",
"GRAPH_STORE_NEO4J_ENCRYPTED": "neo4j_encrypted",
- # KuzuDB settings
- "GRAPH_STORE_KUZU_DATABASE_PATH": "kuzu_database_path",
- "GRAPH_STORE_KUZU_BUFFER_POOL_SIZE": "kuzu_buffer_pool_size",
- "GRAPH_STORE_KUZU_MAX_NUM_THREADS": "kuzu_max_num_threads",
# FalkorDB settings
"GRAPH_STORE_FALKORDB_HOST": "falkordb_host",
"GRAPH_STORE_FALKORDB_PORT": "falkordb_port",
@@ -139,8 +135,6 @@ class GraphStoreConfig:
"timeout",
"max_retries",
"falkordb_port",
- "kuzu_buffer_pool_size",
- "kuzu_max_num_threads",
]:
try:
self._config[config_key] = int(value)
@@ -172,10 +166,6 @@ class GraphStoreConfig:
"neo4j_password": "password",
"neo4j_database": "neo4j",
"neo4j_encrypted": False,
- # KuzuDB defaults
- "kuzu_database_path": "./kuzu_db",
- "kuzu_buffer_pool_size": 268435456, # 256MB
- "kuzu_max_num_threads": 0, # 0 = auto
# FalkorDB defaults
"falkordb_host": "localhost",
"falkordb_port": 6379,
@@ -265,19 +255,6 @@ class GraphStoreConfig:
"encrypted": self._config.get("neo4j_encrypted"),
}
- def get_kuzu_config(self) -> Dict[str, Any]:
- """
- Get KuzuDB-specific configuration.
-
- Returns:
- KuzuDB configuration dictionary
- """
- return {
- "database_path": self._config.get("kuzu_database_path"),
- "buffer_pool_size": self._config.get("kuzu_buffer_pool_size"),
- "max_num_threads": self._config.get("kuzu_max_num_threads"),
- }
-
def get_falkordb_config(self) -> Dict[str, Any]:
"""
Get FalkorDB-specific configuration.
diff --git a/semantica/graph_store/graph_store.py b/semantica/graph_store/graph_store.py
index 4b6f28ae..13d28019 100644
--- a/semantica/graph_store/graph_store.py
+++ b/semantica/graph_store/graph_store.py
@@ -3,7 +3,7 @@ Graph Store Core Module
This module provides the core graph store interface and management classes,
providing a unified interface across multiple graph database backends
-(Neo4j, KuzuDB, FalkorDB).
+(Neo4j, FalkorDB).
Key Features:
- Unified graph store interface
@@ -507,7 +507,7 @@ class GraphStore:
Main graph store interface.
Provides a unified interface for working with property graph databases,
- supporting Neo4j, KuzuDB, and FalkorDB backends.
+ supporting Neo4j and FalkorDB backends.
"""
def __init__(
@@ -519,7 +519,7 @@ class GraphStore:
Initialize graph store.
Args:
- backend: Backend type ("neo4j", "kuzu", "falkordb")
+ backend: Backend type ("neo4j", "falkordb")
**config: Backend-specific configuration
"""
self.logger = get_logger("graph_store")
@@ -542,12 +542,6 @@ class GraphStore:
neo4j_config.update(self.config)
self._adapter = Neo4jAdapter(**neo4j_config)
- elif self.backend == "kuzu":
- from .kuzu_adapter import KuzuAdapter
- kuzu_config = graph_store_config.get_kuzu_config()
- kuzu_config.update(self.config)
- self._adapter = KuzuAdapter(**kuzu_config)
-
elif self.backend == "falkordb":
from .falkordb_adapter import FalkorDBAdapter
falkordb_config = graph_store_config.get_falkordb_config()
diff --git a/semantica/graph_store/graph_store_usage.md b/semantica/graph_store/graph_store_usage.md
index 3988f7fa..875eb735 100644
--- a/semantica/graph_store/graph_store_usage.md
+++ b/semantica/graph_store/graph_store_usage.md
@@ -1,6 +1,6 @@
# Graph Store Module Usage Guide
-The Graph Store module provides comprehensive property graph database integration for the Semantica framework, supporting multiple backends including **Neo4j**, **KuzuDB**, and **FalkorDB**.
+The Graph Store module provides comprehensive property graph database integration for the Semantica framework, supporting multiple backends including **Neo4j** and **FalkorDB**.
## Table of Contents
@@ -28,9 +28,6 @@ pip install semantica
# Neo4j
pip install neo4j
-# KuzuDB
-pip install kuzu
-
# FalkorDB
pip install falkordb
```
@@ -136,47 +133,6 @@ store = GraphStore(
)
```
-### KuzuDB Configuration
-
-```python
-from semantica.graph_store import GraphStore
-
-store = GraphStore(
- backend="kuzu",
- database_path="./my_kuzu_db",
- buffer_pool_size=268435456, # 256MB
- max_num_threads=4
-)
-
-# Connect (creates database if not exists)
-store.connect()
-
-# For KuzuDB, you need to create node/relationship tables first
-from semantica.graph_store import KuzuAdapter
-
-adapter = KuzuAdapter(database_path="./my_kuzu_db")
-adapter.connect()
-
-# Create node table with schema
-adapter.create_node_table(
- "Person",
- properties={
- "id": "SERIAL",
- "name": "STRING",
- "age": "INT64"
- },
- primary_key="id"
-)
-
-# Create relationship table
-adapter.create_rel_table(
- "KNOWS",
- from_table="Person",
- to_table="Person",
- properties={"since": "INT64"}
-)
-```
-
### FalkorDB Configuration
```python
@@ -209,9 +165,6 @@ export GRAPH_STORE_NEO4J_URI=bolt://localhost:7687
export GRAPH_STORE_NEO4J_USER=neo4j
export GRAPH_STORE_NEO4J_PASSWORD=password
-# KuzuDB
-export GRAPH_STORE_KUZU_DATABASE_PATH=./kuzu_db
-
# FalkorDB
export GRAPH_STORE_FALKORDB_HOST=localhost
export GRAPH_STORE_FALKORDB_PORT=6379
@@ -478,7 +431,6 @@ graph_store_config.update({
# Get backend-specific configuration
neo4j_config = graph_store_config.get_neo4j_config()
-kuzu_config = graph_store_config.get_kuzu_config()
falkordb_config = graph_store_config.get_falkordb_config()
# Get all configuration
@@ -598,14 +550,14 @@ print(f"Labels: {stats.get('label_counts')}")
## Backend Comparison
-| Feature | Neo4j | KuzuDB | FalkorDB |
-|---------|-------|--------|----------|
-| Query Language | Cypher | Cypher | OpenCypher |
-| Deployment | Server/Cloud | Embedded | Server (Redis) |
-| Schema | Schema-optional | Schema-required | Schema-optional |
-| Transactions | ACID | ACID | ACID |
-| Performance | Good | Excellent (Analytics) | Ultra-fast |
-| Use Case | General purpose | Analytics | Real-time, LLM |
+| Feature | Neo4j | FalkorDB |
+|---------|-------|----------|
+| Query Language | Cypher | OpenCypher |
+| Deployment | Server/Cloud | Server (Redis) |
+| Schema | Schema-optional | Schema-optional |
+| Transactions | ACID | ACID |
+| Performance | Good | Ultra-fast |
+| Use Case | General purpose | Real-time, LLM |
## Best Practices
diff --git a/semantica/graph_store/kuzu_adapter.py b/semantica/graph_store/kuzu_adapter.py
deleted file mode 100644
index 66cf89a9..00000000
--- a/semantica/graph_store/kuzu_adapter.py
+++ /dev/null
@@ -1,917 +0,0 @@
-"""
-KuzuDB Adapter Module
-
-This module provides KuzuDB embedded graph database integration for property graph
-storage and Cypher querying in the Semantica framework, supporting high-performance
-analytical queries with in-memory and persistent storage.
-
-Key Features:
- - Embedded graph database (no server required)
- - Full Cypher query language support
- - High-performance analytical queries
- - In-memory and persistent storage modes
- - Node table and relationship table management
- - Schema-based property graph model
- - COPY FROM for bulk data loading
- - Optional dependency handling
-
-Main Classes:
- - KuzuAdapter: Main KuzuDB adapter for graph operations
- - KuzuDatabase: Database wrapper
- - KuzuConnection: Connection wrapper
- - KuzuQuery: Query execution wrapper
-
-Example Usage:
- >>> from semantica.graph_store import KuzuAdapter
- >>> adapter = KuzuAdapter(database_path="./kuzu_db")
- >>> adapter.connect()
- >>> adapter.create_node_table("Person", {"name": "STRING", "age": "INT64"})
- >>> node_id = adapter.create_node("Person", {"name": "Alice", "age": 30})
- >>> results = adapter.execute_query("MATCH (p:Person) RETURN p.name")
- >>> adapter.close()
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-import os
-from typing import Any, Dict, List, Optional, Union
-
-from ..utils.exceptions import ProcessingError, ValidationError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-# Optional KuzuDB import
-try:
- import kuzu
-
- KUZU_AVAILABLE = True
-except ImportError:
- KUZU_AVAILABLE = False
- kuzu = None
-
-
-class KuzuDatabase:
- """KuzuDB database wrapper."""
-
- def __init__(self, database: Any):
- """Initialize KuzuDB database wrapper."""
- self.database = database
- self.logger = get_logger("kuzu_database")
-
- def get_connection(self) -> "KuzuConnection":
- """
- Get a connection to the database.
-
- Returns:
- KuzuConnection instance
- """
- if not KUZU_AVAILABLE:
- raise ProcessingError("KuzuDB not available")
-
- try:
- conn = kuzu.Connection(self.database)
- return KuzuConnection(conn)
- except Exception as e:
- raise ProcessingError(f"Failed to create connection: {str(e)}")
-
-
-class KuzuConnection:
- """KuzuDB connection wrapper."""
-
- def __init__(self, connection: Any):
- """Initialize KuzuDB connection wrapper."""
- self.connection = connection
- self.logger = get_logger("kuzu_connection")
-
- def execute(self, query: str, parameters: Optional[Dict[str, Any]] = None) -> "KuzuQuery":
- """
- Execute a Cypher query.
-
- Args:
- query: Cypher query string
- parameters: Query parameters
-
- Returns:
- KuzuQuery result wrapper
- """
- if not KUZU_AVAILABLE:
- raise ProcessingError("KuzuDB not available")
-
- try:
- if parameters:
- result = self.connection.execute(query, parameters)
- else:
- result = self.connection.execute(query)
- return KuzuQuery(result)
- except Exception as e:
- raise ProcessingError(f"Query execution failed: {str(e)}")
-
- def set_max_threads(self, num_threads: int) -> None:
- """Set maximum number of threads for query execution."""
- if self.connection and hasattr(self.connection, "set_max_threads_for_exec"):
- self.connection.set_max_threads_for_exec(num_threads)
-
-
-class KuzuQuery:
- """KuzuDB query result wrapper."""
-
- def __init__(self, result: Any):
- """Initialize KuzuDB query result wrapper."""
- self.result = result
- self.logger = get_logger("kuzu_query")
-
- def has_next(self) -> bool:
- """Check if there are more results."""
- if self.result:
- return self.result.has_next()
- return False
-
- def get_next(self) -> List[Any]:
- """Get next result row."""
- if self.result:
- return self.result.get_next()
- return []
-
- def get_all(self) -> List[List[Any]]:
- """Get all results as a list of rows."""
- results = []
- while self.has_next():
- results.append(self.get_next())
- return results
-
- def get_column_names(self) -> List[str]:
- """Get column names from result."""
- if self.result and hasattr(self.result, "get_column_names"):
- return self.result.get_column_names()
- return []
-
- def get_column_types(self) -> List[str]:
- """Get column types from result."""
- if self.result and hasattr(self.result, "get_column_data_types"):
- return [str(t) for t in self.result.get_column_data_types()]
- return []
-
-
-class KuzuAdapter:
- """
- KuzuDB adapter for embedded property graph storage and Cypher querying.
-
- β€’ Embedded database (no server required)
- β€’ Schema-based node and relationship tables
- β€’ High-performance analytical queries
- β€’ In-memory and persistent storage
- β€’ Bulk data loading with COPY FROM
- β€’ Performance optimization
- β€’ Error handling and recovery
- """
-
- def __init__(
- self,
- database_path: Optional[str] = None,
- buffer_pool_size: Optional[int] = None,
- max_num_threads: int = 0,
- **config,
- ):
- """
- Initialize KuzuDB adapter.
-
- Args:
- database_path: Path to database directory
- buffer_pool_size: Buffer pool size in bytes
- max_num_threads: Maximum number of threads (0 = auto)
- **config: Additional configuration options
- """
- self.logger = get_logger("kuzu_adapter")
- self.config = config
- self.progress_tracker = get_progress_tracker()
-
- self.database_path = database_path or config.get("database_path", "./kuzu_db")
- self.buffer_pool_size = buffer_pool_size or config.get("buffer_pool_size", 268435456)
- self.max_num_threads = max_num_threads or config.get("max_num_threads", 0)
-
- self._database: Optional[KuzuDatabase] = None
- self._connection: Optional[KuzuConnection] = None
-
- # Track created tables for schema management
- self._node_tables: Dict[str, Dict[str, str]] = {}
- self._rel_tables: Dict[str, Dict[str, Any]] = {}
-
- # Check KuzuDB availability
- if not KUZU_AVAILABLE:
- self.logger.warning(
- "KuzuDB not available. Install with: pip install kuzu"
- )
-
- def connect(self, database_path: Optional[str] = None, **options) -> bool:
- """
- Connect to (or create) KuzuDB database.
-
- Args:
- database_path: Path to database directory
- **options: Connection options
-
- Returns:
- True if connected successfully
- """
- if not KUZU_AVAILABLE:
- raise ProcessingError(
- "KuzuDB is not available. Install it with: pip install kuzu"
- )
-
- database_path = database_path or self.database_path
-
- try:
- # Create directory if it doesn't exist
- os.makedirs(database_path, exist_ok=True)
-
- # Create database
- db = kuzu.Database(database_path, buffer_pool_size=self.buffer_pool_size)
- self._database = KuzuDatabase(db)
-
- # Create connection
- self._connection = self._database.get_connection()
-
- if self.max_num_threads > 0:
- self._connection.set_max_threads(self.max_num_threads)
-
- self.logger.info(f"Connected to KuzuDB at {database_path}")
- return True
-
- except Exception as e:
- raise ProcessingError(f"Failed to connect to KuzuDB: {str(e)}")
-
- def close(self) -> None:
- """Close connection to KuzuDB."""
- self._connection = None
- self._database = None
- self.logger.info("Disconnected from KuzuDB")
-
- def _ensure_connection(self) -> KuzuConnection:
- """Ensure connection is established."""
- if self._connection is None:
- self.connect()
- return self._connection
-
- def create_node_table(
- self,
- table_name: str,
- properties: Dict[str, str],
- primary_key: str = "id",
- **options,
- ) -> bool:
- """
- Create a node table with schema.
-
- Args:
- table_name: Name of the node table
- properties: Property schema {property_name: type}
- Types: STRING, INT64, INT32, DOUBLE, FLOAT, BOOLEAN, DATE, TIMESTAMP
- primary_key: Primary key property name
- **options: Additional options
-
- Returns:
- True if created successfully
- """
- try:
- conn = self._ensure_connection()
-
- # Build property list with primary key
- prop_list = []
- for prop_name, prop_type in properties.items():
- if prop_name == primary_key:
- prop_list.insert(0, f"{prop_name} {prop_type} PRIMARY KEY")
- else:
- prop_list.append(f"{prop_name} {prop_type}")
-
- # Ensure primary key is in properties
- if primary_key not in properties:
- prop_list.insert(0, f"{primary_key} SERIAL PRIMARY KEY")
-
- schema_def = ", ".join(prop_list)
- query = f"CREATE NODE TABLE IF NOT EXISTS {table_name}({schema_def})"
-
- conn.execute(query)
- self._node_tables[table_name] = properties
- self.logger.info(f"Created node table: {table_name}")
- return True
-
- except Exception as e:
- raise ProcessingError(f"Failed to create node table: {str(e)}")
-
- def create_rel_table(
- self,
- table_name: str,
- from_table: str,
- to_table: str,
- properties: Optional[Dict[str, str]] = None,
- **options,
- ) -> bool:
- """
- Create a relationship table.
-
- Args:
- table_name: Name of the relationship table
- from_table: Source node table name
- to_table: Target node table name
- properties: Property schema {property_name: type}
- **options: Additional options
-
- Returns:
- True if created successfully
- """
- try:
- conn = self._ensure_connection()
-
- # Build property list
- if properties:
- prop_list = [f"{name} {ptype}" for name, ptype in properties.items()]
- schema_def = ", " + ", ".join(prop_list)
- else:
- schema_def = ""
-
- query = f"CREATE REL TABLE IF NOT EXISTS {table_name}(FROM {from_table} TO {to_table}{schema_def})"
-
- conn.execute(query)
- self._rel_tables[table_name] = {
- "from": from_table,
- "to": to_table,
- "properties": properties or {},
- }
- self.logger.info(f"Created relationship table: {table_name}")
- return True
-
- except Exception as e:
- raise ProcessingError(f"Failed to create relationship table: {str(e)}")
-
- def create_node(
- self,
- table_name: str,
- properties: Dict[str, Any],
- **options,
- ) -> Dict[str, Any]:
- """
- Create a node in a table.
-
- Args:
- table_name: Node table name
- properties: Node properties
- **options: Additional options
-
- Returns:
- Created node information
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="graph_store",
- submodule="KuzuAdapter",
- message=f"Creating node in table {table_name}",
- )
-
- try:
- conn = self._ensure_connection()
-
- # Build property assignment
- prop_names = list(properties.keys())
- prop_values = []
- for value in properties.values():
- if isinstance(value, str):
- prop_values.append(f"'{value}'")
- elif value is None:
- prop_values.append("NULL")
- else:
- prop_values.append(str(value))
-
- names_str = ", ".join(prop_names)
- values_str = ", ".join(prop_values)
-
- query = f"CREATE (n:{table_name} {{{names_str}: [{values_str}]}}) RETURN n"
- # Alternative simpler syntax
- query = f"CREATE (:{table_name} {{{', '.join(f'{k}: {repr(v) if isinstance(v, str) else v}' for k, v in properties.items())}}})"
-
- conn.execute(query)
-
- # Get the created node (KuzuDB uses SERIAL for auto-incrementing IDs)
- result = conn.execute(f"MATCH (n:{table_name}) WHERE n.{list(properties.keys())[0]} = {repr(list(properties.values())[0]) if isinstance(list(properties.values())[0], str) else list(properties.values())[0]} RETURN n")
-
- node_data = {
- "table": table_name,
- "properties": properties,
- }
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Created node in {table_name}",
- )
- return node_data
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Failed to create node: {str(e)}")
-
- def create_nodes(
- self,
- table_name: str,
- nodes: List[Dict[str, Any]],
- **options,
- ) -> List[Dict[str, Any]]:
- """
- Create multiple nodes in batch.
-
- Args:
- table_name: Node table name
- nodes: List of node property dictionaries
- **options: Additional options
-
- Returns:
- List of created node information
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="graph_store",
- submodule="KuzuAdapter",
- message=f"Creating {len(nodes)} nodes in table {table_name}",
- )
-
- try:
- conn = self._ensure_connection()
- created_nodes = []
-
- for node_props in nodes:
- props_str = ", ".join(
- f"{k}: {repr(v) if isinstance(v, str) else v}"
- for k, v in node_props.items()
- )
- query = f"CREATE (:{table_name} {{{props_str}}})"
- conn.execute(query)
- created_nodes.append({
- "table": table_name,
- "properties": node_props,
- })
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Created {len(created_nodes)} nodes",
- )
- return created_nodes
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Failed to create nodes: {str(e)}")
-
- def get_nodes(
- self,
- table_name: str,
- filters: Optional[Dict[str, Any]] = None,
- limit: int = 100,
- **options,
- ) -> List[Dict[str, Any]]:
- """
- Get nodes from a table.
-
- Args:
- table_name: Node table name
- filters: Property filters
- limit: Maximum number of nodes
- **options: Additional options
-
- Returns:
- List of nodes
- """
- try:
- conn = self._ensure_connection()
-
- query = f"MATCH (n:{table_name})"
-
- if filters:
- conditions = []
- for key, value in filters.items():
- if isinstance(value, str):
- conditions.append(f"n.{key} = '{value}'")
- else:
- conditions.append(f"n.{key} = {value}")
- query += " WHERE " + " AND ".join(conditions)
-
- query += f" RETURN n LIMIT {limit}"
-
- result = conn.execute(query)
- nodes = []
-
- while result.has_next():
- row = result.get_next()
- if row and len(row) > 0:
- node = row[0]
- if isinstance(node, dict):
- nodes.append({
- "table": table_name,
- "properties": node,
- })
- else:
- # Handle node object
- nodes.append({
- "table": table_name,
- "properties": dict(node) if hasattr(node, "__iter__") else {"_raw": str(node)},
- })
-
- return nodes
-
- except Exception as e:
- raise ProcessingError(f"Failed to get nodes: {str(e)}")
-
- def update_node(
- self,
- table_name: str,
- filters: Dict[str, Any],
- properties: Dict[str, Any],
- **options,
- ) -> bool:
- """
- Update node properties.
-
- Args:
- table_name: Node table name
- filters: Filters to identify node(s)
- properties: Properties to update
- **options: Additional options
-
- Returns:
- True if updated successfully
- """
- try:
- conn = self._ensure_connection()
-
- # Build WHERE clause
- conditions = []
- for key, value in filters.items():
- if isinstance(value, str):
- conditions.append(f"n.{key} = '{value}'")
- else:
- conditions.append(f"n.{key} = {value}")
-
- # Build SET clause
- updates = []
- for key, value in properties.items():
- if isinstance(value, str):
- updates.append(f"n.{key} = '{value}'")
- else:
- updates.append(f"n.{key} = {value}")
-
- query = f"MATCH (n:{table_name}) WHERE {' AND '.join(conditions)} SET {', '.join(updates)}"
- conn.execute(query)
- return True
-
- except Exception as e:
- raise ProcessingError(f"Failed to update node: {str(e)}")
-
- def delete_node(
- self,
- table_name: str,
- filters: Dict[str, Any],
- **options,
- ) -> bool:
- """
- Delete node(s).
-
- Args:
- table_name: Node table name
- filters: Filters to identify node(s)
- **options: Additional options
-
- Returns:
- True if deleted successfully
- """
- try:
- conn = self._ensure_connection()
-
- # Build WHERE clause
- conditions = []
- for key, value in filters.items():
- if isinstance(value, str):
- conditions.append(f"n.{key} = '{value}'")
- else:
- conditions.append(f"n.{key} = {value}")
-
- query = f"MATCH (n:{table_name}) WHERE {' AND '.join(conditions)} DETACH DELETE n"
- conn.execute(query)
- return True
-
- except Exception as e:
- raise ProcessingError(f"Failed to delete node: {str(e)}")
-
- def create_relationship(
- self,
- rel_table: str,
- from_table: str,
- from_filters: Dict[str, Any],
- to_table: str,
- to_filters: Dict[str, Any],
- properties: Optional[Dict[str, Any]] = None,
- **options,
- ) -> Dict[str, Any]:
- """
- Create a relationship between nodes.
-
- Args:
- rel_table: Relationship table name
- from_table: Source node table name
- from_filters: Filters to identify source node
- to_table: Target node table name
- to_filters: Filters to identify target node
- properties: Relationship properties
- **options: Additional options
-
- Returns:
- Created relationship information
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="graph_store",
- submodule="KuzuAdapter",
- message=f"Creating relationship [{rel_table}]",
- )
-
- try:
- conn = self._ensure_connection()
-
- # Build WHERE clauses
- from_conditions = []
- for key, value in from_filters.items():
- if isinstance(value, str):
- from_conditions.append(f"a.{key} = '{value}'")
- else:
- from_conditions.append(f"a.{key} = {value}")
-
- to_conditions = []
- for key, value in to_filters.items():
- if isinstance(value, str):
- to_conditions.append(f"b.{key} = '{value}'")
- else:
- to_conditions.append(f"b.{key} = {value}")
-
- # Build property string
- if properties:
- props_str = "{" + ", ".join(
- f"{k}: {repr(v) if isinstance(v, str) else v}"
- for k, v in properties.items()
- ) + "}"
- else:
- props_str = ""
-
- query = f"""
- MATCH (a:{from_table}), (b:{to_table})
- WHERE {' AND '.join(from_conditions)} AND {' AND '.join(to_conditions)}
- CREATE (a)-[:{rel_table} {props_str}]->(b)
- """
-
- conn.execute(query)
-
- rel_data = {
- "type": rel_table,
- "from_table": from_table,
- "to_table": to_table,
- "properties": properties or {},
- }
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Created relationship [{rel_table}]",
- )
- return rel_data
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Failed to create relationship: {str(e)}")
-
- def get_relationships(
- self,
- rel_table: Optional[str] = None,
- from_table: Optional[str] = None,
- to_table: Optional[str] = None,
- limit: int = 100,
- **options,
- ) -> List[Dict[str, Any]]:
- """
- Get relationships.
-
- Args:
- rel_table: Relationship table name
- from_table: Source node table filter
- to_table: Target node table filter
- limit: Maximum number of relationships
- **options: Additional options
-
- Returns:
- List of relationships
- """
- try:
- conn = self._ensure_connection()
-
- from_pattern = f":{from_table}" if from_table else ""
- to_pattern = f":{to_table}" if to_table else ""
- rel_pattern = f":{rel_table}" if rel_table else ""
-
- query = f"MATCH (a{from_pattern})-[r{rel_pattern}]->(b{to_pattern}) RETURN a, r, b LIMIT {limit}"
-
- result = conn.execute(query)
- relationships = []
-
- while result.has_next():
- row = result.get_next()
- if row and len(row) >= 3:
- relationships.append({
- "from_node": row[0],
- "relationship": row[1],
- "to_node": row[2],
- })
-
- return relationships
-
- except Exception as e:
- raise ProcessingError(f"Failed to get relationships: {str(e)}")
-
- def execute_query(
- self,
- query: str,
- parameters: Optional[Dict[str, Any]] = None,
- **options,
- ) -> Dict[str, Any]:
- """
- Execute a Cypher query.
-
- Args:
- query: Cypher query string
- parameters: Query parameters
- **options: Additional options
-
- Returns:
- Query results
- """
- tracking_id = self.progress_tracker.start_tracking(
- module="graph_store",
- submodule="KuzuAdapter",
- message="Executing Cypher query",
- )
-
- try:
- conn = self._ensure_connection()
- result = conn.execute(query, parameters)
-
- records = result.get_all()
- column_names = result.get_column_names()
- column_types = result.get_column_types()
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Query returned {len(records)} records",
- )
-
- return {
- "success": True,
- "records": records,
- "column_names": column_names,
- "column_types": column_types,
- "metadata": {"query": query},
- }
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise ProcessingError(f"Query execution failed: {str(e)}")
-
- def shortest_path(
- self,
- from_table: str,
- from_filters: Dict[str, Any],
- to_table: str,
- to_filters: Dict[str, Any],
- rel_table: Optional[str] = None,
- max_depth: int = 10,
- **options,
- ) -> Optional[Dict[str, Any]]:
- """
- Find shortest path between two nodes.
-
- Args:
- from_table: Source node table
- from_filters: Filters to identify source node
- to_table: Target node table
- to_filters: Filters to identify target node
- rel_table: Relationship table filter
- max_depth: Maximum path length
- **options: Additional options
-
- Returns:
- Shortest path information or None
- """
- try:
- conn = self._ensure_connection()
-
- # Build WHERE clauses
- from_conditions = []
- for key, value in from_filters.items():
- if isinstance(value, str):
- from_conditions.append(f"a.{key} = '{value}'")
- else:
- from_conditions.append(f"a.{key} = {value}")
-
- to_conditions = []
- for key, value in to_filters.items():
- if isinstance(value, str):
- to_conditions.append(f"b.{key} = '{value}'")
- else:
- to_conditions.append(f"b.{key} = {value}")
-
- rel_pattern = f":{rel_table}" if rel_table else ""
-
- query = f"""
- MATCH (a:{from_table}), (b:{to_table}),
- path = SHORTEST 1 GROUPS (a)-[r{rel_pattern}*..{max_depth}]-(b)
- WHERE {' AND '.join(from_conditions)} AND {' AND '.join(to_conditions)}
- RETURN path, length(path) as length
- """
-
- result = conn.execute(query)
-
- if result.has_next():
- row = result.get_next()
- return {
- "path": row[0],
- "length": row[1] if len(row) > 1 else 0,
- }
-
- return None
-
- except Exception as e:
- # Kuzu might not support all path queries, try simpler query
- self.logger.warning(f"Shortest path query failed: {str(e)}")
- return None
-
- def bulk_load_nodes(
- self,
- table_name: str,
- file_path: str,
- **options,
- ) -> Dict[str, Any]:
- """
- Bulk load nodes from CSV file.
-
- Args:
- table_name: Node table name
- file_path: Path to CSV file
- **options: Additional options (header, delimiter, etc.)
-
- Returns:
- Load result information
- """
- try:
- conn = self._ensure_connection()
-
- header = options.get("header", True)
- delimiter = options.get("delimiter", ",")
-
- query = f"COPY {table_name} FROM '{file_path}' (HEADER={str(header).lower()}, DELIM='{delimiter}')"
- conn.execute(query)
-
- return {
- "success": True,
- "table": table_name,
- "file": file_path,
- }
-
- except Exception as e:
- raise ProcessingError(f"Bulk load failed: {str(e)}")
-
- def get_stats(self) -> Dict[str, Any]:
- """Get database statistics."""
- try:
- conn = self._ensure_connection()
- stats = {
- "node_tables": list(self._node_tables.keys()),
- "rel_tables": list(self._rel_tables.keys()),
- "database_path": self.database_path,
- }
-
- # Get node counts per table
- for table_name in self._node_tables.keys():
- try:
- result = conn.execute(f"MATCH (n:{table_name}) RETURN count(n) as count")
- if result.has_next():
- row = result.get_next()
- stats[f"{table_name}_count"] = row[0] if row else 0
- except Exception:
- pass
-
- return stats
-
- except Exception as e:
- self.logger.warning(f"Failed to get stats: {str(e)}")
- return {"status": "error", "message": str(e)}
-
diff --git a/tests/test_graph_store.py b/tests/test_graph_store.py
new file mode 100644
index 00000000..0d0e564a
--- /dev/null
+++ b/tests/test_graph_store.py
@@ -0,0 +1,231 @@
+import unittest
+from unittest.mock import MagicMock, patch
+from typing import Any, Dict, List, Optional
+from semantica.graph_store.graph_store import GraphStore
+
+class MockGraphAdapter:
+ def __init__(self, **config):
+ self.config = config
+ self.nodes = {}
+ self.relationships = {}
+ self.node_counter = 0
+ self.rel_counter = 0
+ self.connected = False
+
+ def connect(self, **options):
+ self.connected = True
+ return True
+
+ def close(self):
+ self.connected = False
+
+ def create_node(self, labels: List[str], properties: Dict[str, Any], **options) -> Dict[str, Any]:
+ self.node_counter += 1
+ node_id = self.node_counter
+ node = {
+ "id": node_id,
+ "labels": labels,
+ "properties": properties
+ }
+ self.nodes[node_id] = node
+ return node
+
+ def create_nodes(self, nodes: List[Dict[str, Any]], **options) -> List[Dict[str, Any]]:
+ created = []
+ for node_data in nodes:
+ created.append(self.create_node(node_data.get("labels", []), node_data.get("properties", {})))
+ return created
+
+ def get_node(self, node_id: int, **options) -> Optional[Dict[str, Any]]:
+ return self.nodes.get(node_id)
+
+ def get_nodes(self, labels: Optional[List[str]] = None, properties: Optional[Dict[str, Any]] = None, limit: int = 100, **options) -> List[Dict[str, Any]]:
+ result = []
+ for node in self.nodes.values():
+ if labels:
+ if not any(label in node["labels"] for label in labels):
+ continue
+ if properties:
+ match = True
+ for k, v in properties.items():
+ if node["properties"].get(k) != v:
+ match = False
+ break
+ if not match:
+ continue
+ result.append(node)
+ if len(result) >= limit:
+ break
+ return result
+
+ def update_node(self, node_id: int, properties: Dict[str, Any], merge: bool = True, **options) -> Dict[str, Any]:
+ if node_id not in self.nodes:
+ raise Exception(f"Node {node_id} not found")
+
+ if merge:
+ self.nodes[node_id]["properties"].update(properties)
+ else:
+ self.nodes[node_id]["properties"] = properties
+ return self.nodes[node_id]
+
+ def delete_node(self, node_id: int, detach: bool = True, **options) -> bool:
+ if node_id in self.nodes:
+ del self.nodes[node_id]
+ # Handle detach (delete relationships) if needed
+ if detach:
+ to_delete = []
+ for rel_id, rel in self.relationships.items():
+ if rel["start_node_id"] == node_id or rel["end_node_id"] == node_id:
+ to_delete.append(rel_id)
+ for rel_id in to_delete:
+ del self.relationships[rel_id]
+ return True
+ return False
+
+ def create_relationship(self, start_node_id: int, end_node_id: int, rel_type: str, properties: Optional[Dict[str, Any]] = None, **options) -> Dict[str, Any]:
+ if start_node_id not in self.nodes or end_node_id not in self.nodes:
+ raise Exception("Nodes not found")
+
+ self.rel_counter += 1
+ rel_id = self.rel_counter
+ rel = {
+ "id": rel_id,
+ "start_node_id": start_node_id,
+ "end_node_id": end_node_id,
+ "type": rel_type,
+ "properties": properties or {}
+ }
+ self.relationships[rel_id] = rel
+ return rel
+
+ def get_relationships(self, node_id: Optional[int] = None, rel_type: Optional[str] = None, direction: str = "both", limit: int = 100, **options) -> List[Dict[str, Any]]:
+ result = []
+ for rel in self.relationships.values():
+ if node_id is not None:
+ if direction == "out" and rel["start_node_id"] != node_id:
+ continue
+ elif direction == "in" and rel["end_node_id"] != node_id:
+ continue
+ elif direction == "both" and rel["start_node_id"] != node_id and rel["end_node_id"] != node_id:
+ continue
+
+ if rel_type and rel["type"] != rel_type:
+ continue
+
+ result.append(rel)
+ if len(result) >= limit:
+ break
+ return result
+
+ def delete_relationship(self, rel_id: int, **options) -> bool:
+ if rel_id in self.relationships:
+ del self.relationships[rel_id]
+ return True
+ return False
+
+ def execute_query(self, query: str, parameters: Optional[Dict[str, Any]] = None, **options) -> Dict[str, Any]:
+ return {"records": [], "summary": "Mock query executed"}
+
+ def get_stats(self) -> Dict[str, Any]:
+ return {"nodes": len(self.nodes), "relationships": len(self.relationships)}
+
+ def create_index(self, label: str, property_name: str, index_type: str = "btree", **options) -> bool:
+ return True
+
+ def shortest_path(self, start_node_id: int, end_node_id: int, rel_type: Optional[str] = None, max_depth: int = 10, **options) -> Optional[Dict[str, Any]]:
+ return None # Simplified
+
+ def get_neighbors(self, node_id: int, rel_type: Optional[str] = None, direction: str = "both", depth: int = 1, **options) -> List[Dict[str, Any]]:
+ return [] # Simplified
+
+class TestGraphStore(unittest.TestCase):
+ def setUp(self):
+ # Patch Neo4jAdapter to return our MockGraphAdapter
+ self.patcher = patch('semantica.graph_store.neo4j_adapter.Neo4jAdapter', side_effect=MockGraphAdapter)
+ self.mock_adapter_class = self.patcher.start()
+
+ # Initialize GraphStore with 'neo4j' backend (which will use our mock)
+ self.store = GraphStore(backend="neo4j")
+ self.store.connect()
+
+ def tearDown(self):
+ self.store.close()
+ self.patcher.stop()
+
+ def test_node_operations(self):
+ # Create
+ node = self.store.create_node(labels=["Person"], properties={"name": "Alice", "age": 30})
+ self.assertIsNotNone(node)
+ self.assertEqual(node["properties"]["name"], "Alice")
+ node_id = node["id"]
+
+ # Get
+ fetched_node = self.store.get_node(node_id)
+ self.assertEqual(fetched_node["id"], node_id)
+ self.assertEqual(fetched_node["properties"]["name"], "Alice")
+
+ # Get with filters
+ nodes = self.store.get_nodes(labels=["Person"], properties={"name": "Alice"})
+ self.assertEqual(len(nodes), 1)
+ self.assertEqual(nodes[0]["id"], node_id)
+
+ # Update
+ updated_node = self.store.update_node(node_id, properties={"age": 31})
+ self.assertEqual(updated_node["properties"]["age"], 31)
+ self.assertEqual(updated_node["properties"]["name"], "Alice") # Merge behavior
+
+ # Delete
+ result = self.store.delete_node(node_id)
+ self.assertTrue(result)
+ self.assertIsNone(self.store.get_node(node_id))
+
+ def test_relationship_operations(self):
+ node1 = self.store.create_node(["Person"], {"name": "Alice"})
+ node2 = self.store.create_node(["Person"], {"name": "Bob"})
+
+ # Create
+ rel = self.store.create_relationship(node1["id"], node2["id"], "KNOWS", {"since": 2023})
+ self.assertIsNotNone(rel)
+ self.assertEqual(rel["type"], "KNOWS")
+ rel_id = rel["id"]
+
+ # Get
+ rels = self.store.get_relationships(node_id=node1["id"], direction="out")
+ self.assertEqual(len(rels), 1)
+ self.assertEqual(rels[0]["id"], rel_id)
+
+ # Delete
+ result = self.store.delete_relationship(rel_id)
+ self.assertTrue(result)
+ rels = self.store.get_relationships(node_id=node1["id"])
+ self.assertEqual(len(rels), 0)
+
+ def test_batch_node_creation(self):
+ nodes_data = [
+ {"labels": ["Person"], "properties": {"name": "User1"}},
+ {"labels": ["Person"], "properties": {"name": "User2"}}
+ ]
+ created_nodes = self.store.create_nodes(nodes_data)
+ self.assertEqual(len(created_nodes), 2)
+ self.assertEqual(created_nodes[0]["properties"]["name"], "User1")
+ self.assertEqual(created_nodes[1]["properties"]["name"], "User2")
+
+ def test_query_execution(self):
+ # Since MockGraphAdapter returns a fixed response
+ result = self.store.execute_query("MATCH (n) RETURN n")
+ self.assertEqual(result["summary"], "Mock query executed")
+
+class TestGraphStoreInitialization(unittest.TestCase):
+ def test_falkordb_initialization(self):
+ with patch('semantica.graph_store.falkordb_adapter.FalkorDBAdapter', side_effect=MockGraphAdapter) as mock_falkor:
+ store = GraphStore(backend="falkordb")
+ self.assertIsInstance(store._adapter, MockGraphAdapter)
+ mock_falkor.assert_called_once()
+
+ def test_invalid_backend(self):
+ from semantica.utils.exceptions import ValidationError
+ with self.assertRaises(ValidationError):
+ GraphStore(backend="invalid_backend")
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_graph_store_methods.py b/tests/test_graph_store_methods.py
new file mode 100644
index 00000000..23cadfe1
--- /dev/null
+++ b/tests/test_graph_store_methods.py
@@ -0,0 +1,61 @@
+import unittest
+from unittest.mock import MagicMock, patch
+from semantica.graph_store import methods
+from semantica.graph_store.registry import method_registry
+
+class TestGraphStoreMethods(unittest.TestCase):
+ def setUp(self):
+ # Reset global store
+ methods._reset_store()
+
+ # Mock GraphStore
+ self.mock_store = MagicMock()
+ self.mock_store_patcher = patch('semantica.graph_store.methods.GraphStore', return_value=self.mock_store)
+ self.MockGraphStore = self.mock_store_patcher.start()
+
+ def tearDown(self):
+ self.mock_store_patcher.stop()
+ methods._reset_store()
+
+ # Unregister custom methods if any
+ method_registry.unregister("node", "custom_create")
+
+ def test_create_node_default(self):
+ # Setup
+ labels = ["Person"]
+ props = {"name": "Alice"}
+ self.mock_store.create_node.return_value = {"id": 1, "labels": labels, "properties": props}
+
+ # Execute
+ result = methods.create_node(labels, props)
+
+ # Verify
+ self.mock_store.create_node.assert_called_once_with(labels, props)
+ self.assertEqual(result["id"], 1)
+
+ def test_create_node_custom(self):
+ # Register custom method
+ mock_custom = MagicMock(return_value={"id": 99, "custom": True})
+ method_registry.register("node", "custom_create", mock_custom)
+
+ # Execute
+ result = methods.create_node(["Person"], {"name": "Bob"}, method="custom_create")
+
+ # Verify
+ mock_custom.assert_called_once()
+ self.mock_store.create_node.assert_not_called()
+ self.assertEqual(result["id"], 99)
+
+ def test_execute_query_default(self):
+ # Setup
+ query = "MATCH (n) RETURN n"
+ self.mock_store.execute_query.return_value = {"records": []}
+
+ # Execute
+ result = methods.execute_query(query)
+
+ # Verify
+ self.mock_store.execute_query.assert_called_once_with(query, None)
+
+if __name__ == '__main__':
+ unittest.main()
\ No newline at end of file
diff --git a/tests/test_import.py b/tests/test_import.py
new file mode 100644
index 00000000..d3bb4aa8
--- /dev/null
+++ b/tests/test_import.py
@@ -0,0 +1,11 @@
+
+import sys
+import os
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+
+try:
+ from semantica.export.methods import export_yaml
+ from semantica.graph_store.graph_store import GraphStore
+ print("Imported successfully")
+except Exception as e:
+ print(f"Error: {e}")
diff --git a/tests/verify_backends.py b/tests/verify_backends.py
new file mode 100644
index 00000000..b04168fd
--- /dev/null
+++ b/tests/verify_backends.py
@@ -0,0 +1,136 @@
+import os
+import shutil
+import tempfile
+import traceback
+import logging
+from typing import Any, Dict, List, Optional
+
+# Configure logging
+logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
+logger = logging.getLogger("verify_backends")
+
+try:
+ from semantica.graph_store.graph_store import GraphStore
+except ImportError:
+ logger.error("Failed to import semantica. Make sure you are in the project root or semantica is installed.")
+ exit(1)
+
+def verify_backend(backend_name: str, config: Dict[str, Any]) -> bool:
+ logger.info(f"\n{'='*20} Verifying {backend_name.upper()} {'='*20}")
+ store = None
+ try:
+ # Initialize
+ logger.info(f"Initializing GraphStore with backend='{backend_name}'...")
+ store = GraphStore(backend=backend_name, **config)
+
+ # Connect
+ logger.info(f"Connecting to {backend_name}...")
+ try:
+ store.connect()
+ logger.info("Connection successful.")
+ except Exception as e:
+ logger.error(f"Connection failed: {e}")
+ logger.info(f"Skipping operations for {backend_name} due to connection failure.")
+ return False
+
+ # Create Node
+ logger.info("Creating test node...")
+ node_props = {"name": "TestNode", "test_id": "123"}
+ node = store.create_node(labels=["TestLabel"], properties=node_props)
+ logger.info(f"Node created: {node}")
+
+ node_id = node.get("id")
+ if not node_id:
+ raise Exception("Node created but returned no ID")
+
+ # Get Node
+ logger.info(f"Retrieving node {node_id}...")
+ fetched_node = store.get_node(node_id)
+ if not fetched_node:
+ raise Exception("Failed to retrieve created node")
+ if fetched_node.get("properties", {}).get("name") != "TestNode":
+ raise Exception("Retrieved node properties do not match")
+ logger.info("Node retrieved successfully.")
+
+ # Update Node
+ logger.info("Updating node...")
+ store.update_node(node_id, properties={"updated": True})
+ updated_node = store.get_node(node_id)
+ if not updated_node.get("properties", {}).get("updated"):
+ raise Exception("Update failed")
+ logger.info("Node updated successfully.")
+
+ # Create Relationship
+ # We need a second node
+ node2 = store.create_node(labels=["TestLabel"], properties={"name": "TestNode2"})
+ logger.info("Creating relationship...")
+ rel = store.create_relationship(node_id, node2["id"], "TEST_REL", {"since": 2024})
+ logger.info(f"Relationship created: {rel}")
+ rel_id = rel.get("id")
+
+ # Get Relationship
+ # Note: Implementation details of get_relationships vary, assume standard interface
+ logger.info("Retrieving relationship...")
+ rels = store.get_relationships(node_id=node_id, direction="out")
+ found = False
+ for r in rels:
+ if r.get("id") == rel_id:
+ found = True
+ break
+ if not found:
+ logger.warning("Relationship not found in list (could be eventual consistency or implementation nuance)")
+ else:
+ logger.info("Relationship retrieved successfully.")
+
+ # Delete Relationship
+ if rel_id:
+ logger.info("Deleting relationship...")
+ store.delete_relationship(rel_id)
+ logger.info("Relationship deleted.")
+
+ # Delete Nodes
+ logger.info("Deleting nodes...")
+ store.delete_node(node_id)
+ store.delete_node(node2["id"])
+
+ check = store.get_node(node_id)
+ if check:
+ logger.warning("Node still exists after deletion (could be eventual consistency)")
+ else:
+ logger.info("Node deletion verified.")
+
+ logger.info(f"SUCCESS: {backend_name} passed all verification steps.")
+ return True
+
+ except Exception as e:
+ logger.error(f"FAILURE: {backend_name} encountered an error: {str(e)}")
+ # traceback.print_exc()
+ return False
+ finally:
+ if store:
+ try:
+ store.close()
+ except:
+ pass
+
+def main():
+ results = {}
+
+ # 2. Neo4j (Requires Server)
+ # Using defaults or env vars. If not running, this will fail connection, which is expected.
+ # To test properly, user needs to set GRAPH_STORE_NEO4J_URI etc.
+ results['neo4j'] = verify_backend('neo4j', {})
+
+ # 3. FalkorDB (Requires Redis)
+ results['falkordb'] = verify_backend('falkordb', {})
+
+ print("\n" + "="*50)
+ print("VERIFICATION SUMMARY")
+ print("="*50)
+ for backend, result in results.items():
+ status = "PASSED" if result else "FAILED (or Skipped)"
+ print(f"{backend.ljust(15)}: {status}")
+ print("="*50)
+
+if __name__ == "__main__":
+ main()