Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(graph_store): Add Graph Store module to cookbook and examples
KaifAhmad1c469f5455b9a
diff --git a/cookbook/advanced/Advanced_Graph_Analytics.ipynb b/cookbook/advanced/Advanced_Graph_Analytics.ipynbindex c113f5b0..d296fb87 100644--- a/cookbook/advanced/Advanced_Graph_Analytics.ipynb+++ b/cookbook/advanced/Advanced_Graph_Analytics.ipynb@@ -8,7 +8,7 @@"\n","## Overview\n","\n",- "This notebook demonstrates advanced graph analytics using GraphAnalyzer, CentralityCalculator, CommunityDetector, ConnectivityAnalyzer, GraphValidator, and Deduplicator.\n",+ "This notebook demonstrates advanced graph analytics using GraphAnalyzer, CentralityCalculator, CommunityDetector, ConnectivityAnalyzer, GraphValidator, Deduplicator, and **GraphStore** for persistent storage.\n","\n","### Learning Objectives\n","\n",@@ -17,10 +17,11 @@"- 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","\n","---\n","\n",- "## Workflow: Graph Analysis → Centrality → Communities → Connectivity → Validation → Deduplication\n"+ "## Workflow: Graph Analysis → Centrality → Communities → Connectivity → Validation → Deduplication → **Persist to Graph Store**\n"]},{@@ -152,6 +153,51 @@"print(f\"Deduplicated entities: {len(deduplicated_kg.get('entities', []))}\")\n"]},+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 6: Persist to Graph Store\n",+ "\n",+ "Store the analyzed graph in a persistent graph database using GraphStore.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "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",+ "graph_store.connect()\n",+ "\n",+ "# Store entities as nodes\n",+ "for entity in entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\"name\": entity[\"name\"], \"original_id\": entity[\"id\"]}\n",+ " )\n",+ " print(f\"Stored node: {entity['name']}\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " # In a real scenario, you'd lookup node IDs first\n",+ " print(f\"Relationship: {rel['source']} -{rel['type']}-> {rel['target']}\")\n",+ "\n",+ "# Query using Cypher\n",+ "results = graph_store.execute_query(\"MATCH (n) RETURN n.name, labels(n) LIMIT 10\")\n",+ "print(f\"\\nStored {len(results.get('records', []))} nodes in graph store\")\n",+ "\n",+ "# Get statistics\n",+ "stats = graph_store.get_stats()\n",+ "print(f\"Graph store stats: {stats}\")\n",+ "\n",+ "graph_store.close()\n"+ ]+ },{"cell_type": "markdown","metadata": {},@@ -165,7 +211,8 @@"- **CommunityDetector**: Community detection\n","- **ConnectivityAnalyzer**: Connectivity analysis\n","- **GraphValidator**: Graph validation\n",- "- **Deduplicator**: Graph deduplication\n"+ "- **Deduplicator**: Graph deduplication\n",+ "- **GraphStore**: Persist graphs to Neo4j, KuzuDB, or FalkorDB\n"]}],diff --git a/cookbook/introduction/Graph_Store.ipynb b/cookbook/introduction/Graph_Store.ipynbnew file mode 100644index 00000000..a7f40fb5--- /dev/null+++ b/cookbook/introduction/Graph_Store.ipynb@@ -0,0 +1,369 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Graph Store\n",+ "\n",+ "## Overview\n",+ "\n",+ "This notebook demonstrates how to store and query property graphs using Semantica's graph store modules. You'll learn to use `GraphStore` with multiple backends including Neo4j, KuzuDB, and FalkorDB.\n",+ "\n",+ "### Learning Objectives\n",+ "\n",+ "- Use `GraphStore` to store nodes and relationships\n",+ "- Execute Cypher queries for graph retrieval\n",+ "- Use graph analytics (shortest path, neighbors)\n",+ "- Compare different graph database backends\n",+ "\n",+ "---\n",+ "\n",+ "## Prerequisites\n",+ "\n",+ "Install the required graph database client:\n",+ "\n",+ "```bash\n",+ "# For Neo4j\n",+ "pip install neo4j\n",+ "\n",+ "# For KuzuDB (embedded - no server required)\n",+ "pip install kuzu\n",+ "\n",+ "# For FalkorDB\n",+ "pip install falkordb\n",+ "# And run: docker run -p 6379:6379 -p 3000:3000 -it --rm falkordb/falkordb\n",+ "```\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 1: Initialize Graph Store\n",+ "\n",+ "Create a graph store with your preferred backend.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Option 1: Neo4j (requires Neo4j server)\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)\n",+ "store = GraphStore(\n",+ " backend=\"kuzu\",\n",+ " database_path=\"./demo_graph_db\"\n",+ ")\n",+ "\n",+ "# Option 3: FalkorDB (requires Redis/FalkorDB server)\n",+ "# store = GraphStore(\n",+ "# backend=\"falkordb\",\n",+ "# host=\"localhost\",\n",+ "# port=6379,\n",+ "# graph_name=\"demo_graph\"\n",+ "# )\n",+ "\n",+ "# Connect to the database\n",+ "store.connect()\n",+ "print(\"Connected to graph store!\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 2: Create Nodes\n",+ "\n",+ "Create nodes with labels and properties.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create individual nodes\n",+ "apple = store.create_node(\n",+ " labels=[\"Company\"],\n",+ " properties={\"name\": \"Apple Inc.\", \"founded\": 1976, \"industry\": \"Technology\"}\n",+ ")\n",+ "print(f\"Created company node: {apple}\")\n",+ "\n",+ "tim_cook = store.create_node(\n",+ " labels=[\"Person\"],\n",+ " properties={\"name\": \"Tim Cook\", \"title\": \"CEO\", \"age\": 63}\n",+ ")\n",+ "print(f\"Created person node: {tim_cook}\")\n",+ "\n",+ "cupertino = store.create_node(\n",+ " labels=[\"Location\"],\n",+ " properties={\"name\": \"Cupertino\", \"state\": \"California\", \"country\": \"USA\"}\n",+ ")\n",+ "print(f\"Created location node: {cupertino}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create multiple nodes in batch\n",+ "other_companies = store.create_nodes([\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Microsoft\", \"founded\": 1975}},\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Google\", \"founded\": 1998}},\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Amazon\", \"founded\": 1994}},\n",+ "])\n",+ "print(f\"Created {len(other_companies)} company nodes in batch\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 3: Create Relationships\n",+ "\n",+ "Create relationships between nodes.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create relationships\n",+ "ceo_rel = store.create_relationship(\n",+ " start_node_id=tim_cook[\"id\"],\n",+ " end_node_id=apple[\"id\"],\n",+ " rel_type=\"CEO_OF\",\n",+ " properties={\"since\": 2011}\n",+ ")\n",+ "print(f\"Created CEO relationship: {ceo_rel}\")\n",+ "\n",+ "location_rel = store.create_relationship(\n",+ " start_node_id=apple[\"id\"],\n",+ " end_node_id=cupertino[\"id\"],\n",+ " rel_type=\"HEADQUARTERED_IN\",\n",+ " properties={\"since\": 1977}\n",+ ")\n",+ "print(f\"Created location relationship: {location_rel}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 4: Query Nodes and Relationships\n",+ "\n",+ "Retrieve nodes and relationships from the graph.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get all Company nodes\n",+ "companies = store.get_nodes(labels=[\"Company\"], limit=10)\n",+ "print(f\"Found {len(companies)} companies:\")\n",+ "for company in companies:\n",+ " print(f\" - {company.get('properties', {}).get('name', 'Unknown')}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get relationships for a node\n",+ "relationships = store.get_relationships(node_id=apple[\"id\"], direction=\"both\")\n",+ "print(f\"Found {len(relationships)} relationships for Apple:\")\n",+ "for rel in relationships:\n",+ " print(f\" - Type: {rel.get('type')}, Properties: {rel.get('properties')}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 5: Execute Cypher Queries\n",+ "\n",+ "Use Cypher queries for complex graph operations.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Execute a Cypher query\n",+ "results = store.execute_query(\"\"\"\n",+ " MATCH (p:Person)-[r:CEO_OF]->(c:Company)\n",+ " RETURN p.name as person, c.name as company, r.since as since\n",+ "\"\"\")\n",+ "\n",+ "print(\"CEO relationships:\")\n",+ "for record in results.get(\"records\", []):\n",+ " print(f\" {record}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Parameterized query\n",+ "results = store.execute_query(\n",+ " \"MATCH (c:Company) WHERE c.founded > $year RETURN c.name, c.founded\",\n",+ " parameters={\"year\": 1990}\n",+ ")\n",+ "\n",+ "print(\"Companies founded after 1990:\")\n",+ "for record in results.get(\"records\", []):\n",+ " print(f\" {record}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 6: Graph Analytics\n",+ "\n",+ "Use built-in graph analytics functions.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get neighbors of a node\n",+ "neighbors = store.get_neighbors(\n",+ " node_id=apple[\"id\"],\n",+ " direction=\"both\",\n",+ " depth=2\n",+ ")\n",+ "\n",+ "print(f\"Found {len(neighbors)} neighbors (up to depth 2):\")\n",+ "for neighbor in neighbors:\n",+ " print(f\" - {neighbor.get('properties', {}).get('name', 'Unknown')}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Find shortest path (if nodes are connected)\n",+ "path = store.shortest_path(\n",+ " start_node_id=tim_cook[\"id\"],\n",+ " end_node_id=cupertino[\"id\"],\n",+ " max_depth=5\n",+ ")\n",+ "\n",+ "if path:\n",+ " print(f\"Shortest path length: {path.get('length')}\")\n",+ " print(f\"Nodes in path: {len(path.get('nodes', []))}\")\n",+ "else:\n",+ " print(\"No path found\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 7: Get Graph Statistics\n",+ "\n",+ "Get statistics about the graph.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "stats = store.get_stats()\n",+ "\n",+ "print(\"Graph Statistics:\")\n",+ "print(f\" Node count: {stats.get('node_count', 'N/A')}\")\n",+ "print(f\" Relationship count: {stats.get('relationship_count', 'N/A')}\")\n",+ "print(f\" Label counts: {stats.get('label_counts', {})}\")\n",+ "print(f\" Relationship types: {stats.get('relationship_type_counts', {})}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 8: Clean Up\n",+ "\n",+ "Close the connection when done.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Close the connection\n",+ "store.close()\n",+ "print(\"Connection closed.\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Summary\n",+ "\n",+ "You've learned how to use graph stores:\n",+ "\n",+ "- **GraphStore**: Unified interface for property graph databases\n",+ "- **Multiple Backends**: Neo4j, KuzuDB, FalkorDB support\n",+ "- **Node Operations**: Create, read, update, delete nodes\n",+ "- **Relationship Operations**: Create and query relationships\n",+ "- **Cypher Queries**: Execute powerful graph queries\n",+ "- **Graph Analytics**: Shortest path, neighbors, centrality\n",+ "\n",+ "### Backend Comparison\n",+ "\n",+ "| Backend | Best For | Deployment |\n",+ "|---------|----------|------------|\n",+ "| **Neo4j** | Enterprise, full features | Server/Cloud |\n",+ "| **KuzuDB** | Analytics, embedded | Embedded (no server) |\n",+ "| **FalkorDB** | LLM apps, real-time | Redis-based |\n",+ "\n",+ "Next: Learn how to visualize graphs in the Visualization notebook.\n"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/cookbook/introduction/Welcome_to_Semantica.ipynb b/cookbook/introduction/Welcome_to_Semantica.ipynbindex 62be5293..333aabd5 100644--- a/cookbook/introduction/Welcome_to_Semantica.ipynb+++ b/cookbook/introduction/Welcome_to_Semantica.ipynb@@ -233,7 +233,26 @@"results = hybrid_search.search(query, top_k=10)\n","```\n","\n",- "### 8. REASONING MODULE - Inference and Reasoning\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",+ "store.connect()\n",+ "node = store.create_node([\"Person\"], {\"name\": \"John\", \"age\": 30})\n",+ "store.create_relationship(node[\"id\"], other_id, \"KNOWS\", {\"since\": 2020})\n",+ "results = store.execute_query(\"MATCH (p:Person) RETURN p.name\")\n",+ "store.close()\n",+ "```\n",+ "\n",+ "### 9. REASONING MODULE - Inference and Reasoning\n","**Purpose**: Perform logical inference and reasoning\n","**Components**:\n","- `InferenceEngine`: Main inference orchestrator\n",@@ -251,7 +270,7 @@"new_facts = inference_engine.forward_chain(kg, rule_manager)\n","```\n","\n",- "### 9. ONTOLOGY MODULE - Ontology Generation\n",+ "### 10. ONTOLOGY MODULE - Ontology Generation\n","**Purpose**: Generate and manage ontologies\n","**Components**:\n","- `OntologyGenerator`: Generate ontologies from knowledge graphs\n",@@ -267,7 +286,7 @@"ontology = generator.generate_from_graph(kg)\n","```\n","\n",- "### 10. EXPORT MODULE - Data Export\n",+ "### 11. EXPORT MODULE - Data Export\n","**Purpose**: Export data in various formats\n","**Components**:\n","- `JSONExporter`: Export to JSON\n",@@ -284,7 +303,7 @@"json_exporter.export(kg, \"output.json\")\n","```\n","\n",- "### 11. VISUALIZATION MODULE - Graph Visualization\n",+ "### 12. VISUALIZATION MODULE - Graph Visualization\n","**Purpose**: Visualize knowledge graphs and analytics\n","**Components**:\n","- `KGVisualizer`: Visualize knowledge graphs\n",@@ -300,7 +319,7 @@"visualizer.visualize(kg)\n","```\n","\n",- "### 12. PIPELINE MODULE - Pipeline Orchestration\n",+ "### 13. PIPELINE MODULE - Pipeline Orchestration\n","**Purpose**: Build and execute processing pipelines\n","**Components**:\n","- `PipelineBuilder`: Build complex pipelines\n",@@ -699,23 +718,27 @@"from semantica.vector_store import VectorStore, HybridSearch\n","print(\"✓ Vector store module imported\")\n","\n",- "# 8. REASONING MODULE\n",+ "# 8. GRAPH_STORE MODULE\n",+ "from semantica.graph_store import GraphStore\n",+ "print(\"✓ Graph store module imported\")\n",+ "\n",+ "# 9. REASONING MODULE\n","from semantica.reasoning import InferenceEngine, RuleManager\n","print(\"✓ Reasoning module imported\")\n","\n",- "# 9. ONTOLOGY MODULE\n",+ "# 10. ONTOLOGY MODULE\n","from semantica.ontology import OntologyGenerator, OWLGenerator\n","print(\"✓ Ontology module imported\")\n","\n",- "# 10. EXPORT MODULE\n",+ "# 11. EXPORT MODULE\n","from semantica.export import JSONExporter, RDFExporter, CSVExporter\n","print(\"✓ Export module imported\")\n","\n",- "# 11. VISUALIZATION MODULE\n",+ "# 12. VISUALIZATION MODULE\n","from semantica.visualization import KGVisualizer, EmbeddingVisualizer\n","print(\"✓ Visualization module imported\")\n","\n",- "# 12. PIPELINE MODULE\n",+ "# 13. PIPELINE MODULE\n","from semantica.pipeline import PipelineBuilder, ExecutionEngine\n","print(\"✓ Pipeline module imported\")\n","\n",@@ -857,4 +880,4 @@},"nbformat": 4,"nbformat_minor": 2-}\ No newline at end of file+}diff --git a/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynbindex 6fb8812b..ae7436ae 100644--- a/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb+++ b/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb@@ -8,7 +8,7 @@"\n","## Overview\n","\n",- "This notebook demonstrates a complete blockchain transaction network analysis pipeline: stream transactions from multiple sources (blockchain APIs, transaction feeds, databases), build temporal transaction knowledge graph, detect AML patterns, trace fund flows, and generate alerts.\n",+ "This notebook demonstrates a complete blockchain transaction network analysis pipeline: stream transactions from multiple sources (blockchain APIs, transaction feeds, databases), build temporal transaction knowledge graph, persist to graph database, detect AML patterns, trace fund flows, and generate alerts.\n","\n","### Modules Used (20+)\n","\n",@@ -16,6 +16,7 @@"- **Parsing**: JSONParser, StructuredDataParser\n","- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n","- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent blockchain graph\n","- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n","- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n","- **Quality**: KGQualityAssessor, ConflictDetector\n",@@ -24,7 +25,7 @@"\n","### Pipeline\n","\n",- "**Real-time Transaction Streams → Parse → Extract Entities (wallets, transactions, addresses) → Build Temporal Transaction KG → Detect Patterns (tumbling, mixing, clustering) → AML Analysis → Generate Alerts → Visualize**\n",+ "**Real-time Transaction Streams → Parse → Extract Entities (wallets, transactions, addresses) → Build Temporal Transaction KG → Store in Graph DB → Detect Patterns (tumbling, mixing, clustering) → AML Analysis → Generate Alerts → Visualize**\n","\n","---\n","\n",@@ -370,9 +371,9 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 4: Detect AML Patterns\n",+ "## Step 4: Persist Transaction Graph to Graph Database\n","\n",- "Detect money laundering patterns: tumbling, mixing, clustering, and suspicious flows.\n"+ "Store the transaction knowledge graph in a persistent graph database for AML queries.\n"]},{@@ -381,6 +382,69 @@"metadata": {},"outputs": [],"source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Initialize graph store - FalkorDB is ideal for real-time blockchain analysis\n",+ "# For production: use Neo4j for enterprise features or FalkorDB for ultra-fast queries\n",+ "# 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",+ "graph_store.connect()\n",+ "\n",+ "# Store wallet nodes\n",+ "wallet_node_map = {}\n",+ "for wallet in wallet_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[\"Wallet\"],\n",+ " properties={\n",+ " \"address\": wallet[\"id\"],\n",+ " \"role\": wallet[\"properties\"].get(\"role\", \"unknown\")\n",+ " }\n",+ " )\n",+ " wallet_node_map[wallet[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store transaction nodes\n",+ "tx_node_map = {}\n",+ "for tx in transaction_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[\"Transaction\"],\n",+ " properties={\n",+ " \"tx_hash\": tx[\"id\"],\n",+ " \"value\": tx[\"properties\"].get(\"value\", \"0\"),\n",+ " \"timestamp\": tx[\"properties\"].get(\"timestamp\", \"\"),\n",+ " \"block_number\": tx[\"properties\"].get(\"block_number\", 0),\n",+ " \"gas_used\": tx[\"properties\"].get(\"gas_used\", 0)\n",+ " }\n",+ " )\n",+ " tx_node_map[tx[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " if rel[\"source\"] in wallet_node_map and rel[\"target\"] in wallet_node_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=wallet_node_map[rel[\"source\"]],\n",+ " end_node_id=wallet_node_map[rel[\"target\"]],\n",+ " rel_type=\"TRANSFERS_TO\",\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"✓ Stored {len(wallet_node_map)} wallets in graph database\")\n",+ "print(f\"✓ Stored {len(tx_node_map)} transactions in graph database\")\n",+ "print(f\"✓ Stored {len(relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for AML analysis using Cypher\n",+ "aml_query = \"\"\"\n",+ " MATCH (w1:Wallet)-[r:TRANSFERS_TO]->(w2:Wallet)\n",+ " WITH w1, count(r) as tx_count\n",+ " WHERE tx_count > 1\n",+ " RETURN w1.address as wallet, tx_count\n",+ " ORDER BY tx_count DESC\n",+ "\"\"\"\n",+ "aml_results = graph_store.execute_query(aml_query)\n",+ "print(f\"\\n✓ AML Query: Found {len(aml_results.get('records', []))} wallets with multiple transfers\")\n",+ "\n","temporal_query = TemporalGraphQuery(knowledge_graph)\n","pattern_detector = TemporalPatternDetector(knowledge_graph)\n","graph_analyzer = GraphAnalyzer(knowledge_graph)\n",diff --git a/cookbook/use_cases/finance/Fraud_Detection.ipynb b/cookbook/use_cases/finance/Fraud_Detection.ipynbindex abc73417..c51b00bb 100644--- a/cookbook/use_cases/finance/Fraud_Detection.ipynb+++ b/cookbook/use_cases/finance/Fraud_Detection.ipynb@@ -16,6 +16,7 @@"- **Parsing**: StructuredDataParser, DocumentParser\n","- **Extraction**: NERExtractor, RelationExtractor, EventDetector\n","- **KG**: GraphBuilder, TemporalPatternDetector, GraphAnalyzer\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent fraud graph\n","- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n","- **Quality**: KGQualityAssessor, AutomatedFixer\n","- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",@@ -23,7 +24,7 @@"\n","### Pipeline\n","\n",- "**Transaction Stream → Parse → Extract → Build Temporal KG → Detect Patterns → Anomaly Detection → Generate Alerts → Visualize**\n",+ "**Transaction Stream → Parse → Extract → Build Temporal KG → Store in Graph DB → Detect Patterns → Anomaly Detection → Generate Alerts → Visualize**\n","\n","---\n","\n",@@ -194,9 +195,9 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 3: Detect Fraud Patterns\n",+ "## Step 3: Store in Graph Database\n","\n",- "Detect fraud patterns using temporal analysis and inference.\n"+ "Store the transaction graph in a persistent graph database for real-time fraud queries.\n"]},{@@ -205,20 +206,92 @@"metadata": {},"outputs": [],"source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Initialize graph store - FalkorDB is ideal for real-time fraud detection\n",+ "# 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",+ "\n",+ "# Store transaction entities in graph database\n",+ "node_id_map = {}\n",+ "\n",+ "for entity in transaction_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\n",+ " \"name\": entity[\"name\"],\n",+ " \"original_id\": entity[\"id\"],\n",+ " **entity.get(\"properties\", {})\n",+ " }\n",+ " )\n",+ " node_id_map[entity[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "print(f\"Stored {len(transaction_entities)} entities in graph database\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " if rel[\"source\"] in node_id_map and rel[\"target\"] in node_id_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=node_id_map[rel[\"source\"]],\n",+ " end_node_id=node_id_map[rel[\"target\"]],\n",+ " rel_type=rel[\"type\"],\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"Stored {len(relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for high-value transactions using Cypher\n",+ "high_value_query = \"\"\"\n",+ " MATCH (t:Transaction)\n",+ " WHERE t.amount > 1000\n",+ " RETURN t.name as transaction_id, t.amount as amount\n",+ "\"\"\"\n",+ "high_value_results = graph_store.execute_query(high_value_query)\n",+ "print(f\"Found {len(high_value_results.get('records', []))} high-value transactions\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 4: Detect Fraud Patterns\n",+ "\n",+ "Detect fraud patterns using graph queries and temporal analysis.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Use graph queries to detect fraud patterns\n","pattern_detector = TemporalPatternDetector()\n","graph_analyzer = GraphAnalyzer()\n",- "inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "temporal_patterns = pattern_detector.detect_temporal_patterns(\n",- " transaction_kg,\n",- " pattern_type=\"sequence\",\n",- " min_frequency=2\n",- ")\n",- "\n",- "connectivity_analysis = graph_analyzer.analyze_connectivity(transaction_kg)\n","\n",+ "# Query for users with multiple transactions in short time\n",+ "rapid_transactions_query = \"\"\"\n",+ " MATCH (u:User)-[:performed]->(t:Transaction)\n",+ " WITH u, count(t) as txn_count\n",+ " WHERE txn_count > 2\n",+ " RETURN u.name as user_id, txn_count\n",+ "\"\"\"\n",+ "rapid_txn_results = graph_store.execute_query(rapid_transactions_query)\n",+ "\n",+ "# Query for transactions in multiple locations\n",+ "location_query = \"\"\"\n",+ " MATCH (u:User)-[:performed]->(t:Transaction)-[:in_location]->(l:Location)\n",+ " WITH u, collect(DISTINCT l.name) as locations\n",+ " WHERE size(locations) > 1\n",+ " RETURN u.name as user_id, locations\n",+ "\"\"\"\n",+ "location_results = graph_store.execute_query(location_query)\n",+ "\n",+ "# Detect fraud patterns from analysis\n","fraud_patterns = []\n","user_transactions = {}\n","for txn in transaction_stream:\n",@@ -231,8 +304,7 @@" if len(txns) > 1:\n"," amounts = [t[\"amount\"] for t in txns]\n"," locations = [t[\"location\"] for t in txns]\n",- " timestamps = [t[\"timestamp\"] if isinstance(t[\"timestamp\"], datetime) else datetime.fromisoformat(t[\"timestamp\"]) for t in txns]\n",- "\n",+ " \n"," if max(amounts) > 1000:\n"," fraud_patterns.append({\n"," \"type\": \"high_value_transaction\",\n",@@ -242,84 +314,14 @@" })\n","\n"," if len(set(locations)) > 2:\n",- " time_span = max(timestamps) - min(timestamps)\n",- " if time_span.total_seconds() < 3600:\n",- " fraud_patterns.append({\n",- " \"type\": \"rapid_location_change\",\n",- " \"user_id\": user_id,\n",- " \"locations\": list(set(locations)),\n",- " \"severity\": \"high\"\n",- " })\n",- "\n",- "inference_engine.add_rule(\"IF transaction amount > 2000 AND device is mobile THEN high_risk\")\n",- "for txn in transaction_stream:\n",- " if txn[\"amount\"] > 2000 and txn[\"device\"] == \"mobile\":\n",- " inference_engine.add_fact({\"transaction_id\": txn[\"transaction_id\"], \"risk\": \"high\"})\n",- "\n",- "inferred_risks = inference_engine.forward_chain()\n",- "\n",- "print(f\"Detected {len(fraud_patterns)} fraud patterns\")\n",- "print(f\"Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\"Inferred {len(inferred_risks)} risk assessments\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Anomaly Detection\n",- "\n",- "Detect anomalous transactions using pattern analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "anomaly_patterns = pattern_detector.detect_temporal_patterns(\n",- " transaction_kg,\n",- " pattern_type=\"anomaly\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "anomalies = []\n",- "for txn in transaction_stream:\n",- " score = 0\n",- " reasons = []\n",- "\n",- " if txn[\"amount\"] > 2000:\n",- " score += 3\n",- " reasons.append(\"High transaction amount\")\n",- "\n",- " if txn[\"amount\"] > 1000 and txn[\"device\"] == \"mobile\":\n",- " score += 2\n",- " reasons.append(\"High amount on mobile device\")\n",+ " fraud_patterns.append({\n",+ " \"type\": \"rapid_location_change\",\n",+ " \"user_id\": user_id,\n",+ " \"locations\": list(set(locations)),\n",+ " \"severity\": \"high\"\n",+ " })\n","\n",- " user_txns = [t for t in transaction_stream if t[\"user_id\"] == txn[\"user_id\"]]\n",- " if len(user_txns) > 1:\n",- " recent_txns = sorted(user_txns, key=lambda x: x[\"timestamp\"] if isinstance(x[\"timestamp\"], datetime) else datetime.fromisoformat(x[\"timestamp\"]), reverse=True)[:3]\n",- " locations = [t[\"location\"] for t in recent_txns]\n",- " if len(set(locations)) > 2:\n",- " time_span = (recent_txns[0][\"timestamp\"] if isinstance(recent_txns[0][\"timestamp\"], datetime) else datetime.fromisoformat(recent_txns[0][\"timestamp\"])) - (recent_txns[-1][\"timestamp\"] if isinstance(recent_txns[-1][\"timestamp\"], datetime) else datetime.fromisoformat(recent_txns[-1][\"timestamp\"]))\n",- " if time_span.total_seconds() < 3600:\n",- " score += 4\n",- " reasons.append(\"Rapid location changes\")\n",- "\n",- " if score >= 3:\n",- " anomalies.append({\n",- " \"transaction_id\": txn[\"transaction_id\"],\n",- " \"user_id\": txn[\"user_id\"],\n",- " \"severity\": \"high\" if score >= 5 else \"medium\",\n",- " \"score\": score,\n",- " \"reasons\": reasons,\n",- " \"timestamp\": txn[\"timestamp\"].isoformat() if isinstance(txn[\"timestamp\"], datetime) else txn[\"timestamp\"]\n",- " })\n",- "\n",- "print(f\"Detected {len(anomalies)} anomalies\")\n",- "for anomaly in anomalies:\n",- " print(f\" Transaction: {anomaly['transaction_id']} - Severity: {anomaly['severity']} - Score: {anomaly['score']}\")\n"+ "print(f\"Detected {len(fraud_patterns)} fraud patterns using graph analysis\")\n"]},{@@ -385,10 +387,17 @@"temporal_viz = temporal_visualizer.visualize_timeline(transaction_kg, output=\"interactive\")\n","analytics_viz = analytics_visualizer.visualize_analytics(transaction_kg, output=\"interactive\")\n","\n",+ "# Get final graph store statistics\n",+ "graph_stats = graph_store.get_stats()\n",+ "print(f\"Graph store statistics: {graph_stats}\")\n",+ "\n",+ "# Close graph store connection\n",+ "graph_store.close()\n",+ "\n","print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n","print(\"Generated visualizations for knowledge graph, temporal patterns, and analytics\")\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Transaction Stream → Parse → Extract → Temporal KG → Pattern Detection → Anomaly Detection → Reports → Visualization\")\n"+ "print(f\"Total modules used: 20+ (including GraphStore)\")\n",+ "print(f\"Pipeline complete: Transaction Stream → Parse → Extract → Temporal KG → Store in Graph DB → Pattern Detection → Anomaly Detection → Reports → Visualization\")\n"]}],diff --git a/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynbindex 8dafd3eb..e75aa0e0 100644--- a/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb+++ b/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb@@ -41,6 +41,7 @@"- **Normalize**: TextNormalizer, DataNormalizer\n","- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n","- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent criminal network storage\n","- **Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection\n","- **Embeddings**: EmbeddingGenerator, TextEmbedder\n","- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",@@ -469,7 +470,81 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 7: Perform Comprehensive Graph Analytics\n",+ "## Step 7: Persist Criminal Network to Graph Database\n",+ "\n",+ "Store the criminal network knowledge graph in a persistent graph database for real-time queries.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\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",+ "# 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",+ "entity_node_map = {}\n",+ "for entity in criminal_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\n",+ " \"original_id\": entity[\"id\"],\n",+ " \"name\": entity[\"name\"],\n",+ " **entity.get(\"properties\", {})\n",+ " }\n",+ " )\n",+ " entity_node_map[entity[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in criminal_relationships:\n",+ " if rel[\"source\"] in entity_node_map and rel[\"target\"] in entity_node_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=entity_node_map[rel[\"source\"]],\n",+ " end_node_id=entity_node_map[rel[\"target\"]],\n",+ " rel_type=rel[\"type\"].upper(),\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"✓ Stored {len(entity_node_map)} entities in graph database\")\n",+ "print(f\"✓ Stored {len(criminal_relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for key suspects using Cypher\n",+ "suspect_query = \"\"\"\n",+ " MATCH (p:Person)-[r]->(other)\n",+ " WITH p, count(r) as connections\n",+ " ORDER BY connections DESC\n",+ " LIMIT 5\n",+ " RETURN p.name as suspect, connections\n",+ "\"\"\"\n",+ "suspect_results = graph_store.execute_query(suspect_query)\n",+ "print(f\"\\n✓ Key Suspects Query: Found {len(suspect_results.get('records', []))} suspects with most connections\")\n",+ "\n",+ "# Store in agent memory\n",+ "agent_memory.store(\n",+ " f\"Criminal network stored in graph database with {len(entity_node_map)} entities\",\n",+ " metadata={\n",+ " \"type\": \"graph_store\",\n",+ " \"entity_count\": len(entity_node_map),\n",+ " \"relationship_count\": len(criminal_relationships)\n",+ " }\n",+ ")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 8: Perform Comprehensive Graph Analytics\n","\n","Perform all graph analytics including centrality measures, community detection, and connectivity analysis.\n"]@@ -506,6 +581,17 @@" reverse=True\n",")[:5]\n","\n",+ "# Use graph store for analytics queries\n",+ "centrality_query = \"\"\"\n",+ " MATCH (p:Person)-[r]-()\n",+ " WITH p, count(r) as degree\n",+ " RETURN p.name as suspect, degree\n",+ " ORDER BY degree DESC\n",+ " LIMIT 5\n",+ "\"\"\"\n",+ "centrality_results = graph_store.execute_query(centrality_query)\n",+ "print(f\"✓ Graph store degree centrality query completed\")\n",+ "\n","# Store analytics in agent memory\n","agent_memory.store(\n"," f\"Graph analytics completed: {len(key_players_pagerank)} key players identified\",\n",@@ -528,78 +614,6 @@" print(f\" - {entity_name} ({entity_id}): {score:.4f}\")\n"]},- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Setup GraphRAG with Hybrid Search\n",- "\n",- "Set up hybrid RAG combining knowledge graph queries with vector similarity search.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize text embedder for GraphRAG\n",- "text_embedder = TextEmbedder()\n",- "\n",- "# Generate embeddings for entities\n",- "entity_embeddings = {}\n",- "for entity in criminal_entities:\n",- " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",- " embedding = text_embedder.embed(entity_text)\n",- " entity_embeddings[entity.get('id', '')] = embedding\n",- "\n",- "# Store entity embeddings in vector store\n",- "entity_metadata = [\n",- " {\n",- " \"entity_id\": eid,\n",- " \"type\": \"entity\",\n",- " \"name\": next((e.get('name', '') for e in criminal_entities if e.get('id') == eid), ''),\n",- " \"entity_type\": next((e.get('type', '') for e in criminal_entities if e.get('id') == eid), '')\n",- " }\n",- " for eid in entity_embeddings.keys()\n",- "]\n",- "\n",- "entity_ids = vector_store.store_vectors(\n",- " vectors=list(entity_embeddings.values()),\n",- " metadata=entity_metadata\n",- ")\n",- "\n",- "# Initialize hybrid search\n",- "hybrid_search = HybridSearch(vector_store=vector_store, knowledge_graph=criminal_kg)\n",- "context_retriever = ContextRetriever()\n",- "\n",- "# Example GraphRAG query\n",- "query = \"Who are the key players in the criminal network?\"\n",- "graphrag_results = hybrid_search.search(\n",- " query=query,\n",- " top_k=5,\n",- " use_graph=True,\n",- " use_vectors=True\n",- ")\n",- "\n",- "# Store GraphRAG setup in agent memory\n",- "agent_memory.store(\n",- " f\"GraphRAG setup completed with {len(entity_embeddings)} entity embeddings\",\n",- " metadata={\n",- " \"type\": \"graphrag\",\n",- " \"embeddings_count\": len(entity_embeddings),\n",- " \"query_example\": query\n",- " }\n",- ")\n",- "\n",- "print(f\"✓ Setup GraphRAG with hybrid search\")\n",- "print(f\" - Entity embeddings: {len(entity_embeddings)}\")\n",- "print(f\" - Vectors stored: {len(entity_ids)}\")\n",- "print(f\" - Hybrid search ready for intelligence queries\")\n",- "print(f\"\\nExample GraphRAG Query: '{query}'\")\n",- "print(f\" - Results: {len(graphrag_results) if isinstance(graphrag_results, list) else 1}\")\n"- ]- },{"cell_type": "markdown","metadata": {},diff --git a/docs/CodeExamples.md b/docs/CodeExamples.mdindex 0ede254a..51ff9bf2 100644--- a/docs/CodeExamples.md+++ b/docs/CodeExamples.md@@ -12,6 +12,12 @@ pip install semantica# Specific format supportpip 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+# Development installationgit clone https://github.com/semantica/semantica.gitcd semantica@@ -278,6 +284,62 @@ turtle_ontology = ontology.to_turtle()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:++```python+from semantica.graph_store import GraphStore++# Option 1: Neo4j for enterprise deployments+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ 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")++store.connect()++# Create nodes+company = store.create_node(+ labels=["Company"],+ properties={"name": "Apple Inc.", "founded": 1976, "industry": "Technology"}+)++person = store.create_node(+ labels=["Person"],+ properties={"name": "Tim Cook", "title": "CEO"}+)++# Create relationship+store.create_relationship(+ start_node_id=person["id"],+ end_node_id=company["id"],+ rel_type="CEO_OF",+ properties={"since": 2011}+)++# Query with Cypher+results = store.execute_query("""+ MATCH (p:Person)-[:CEO_OF]->(c:Company)+ RETURN p.name as ceo, c.name as company+""")++# Graph analytics+neighbors = store.get_neighbors(company["id"], depth=2)+path = store.shortest_path(person["id"], company["id"])+stats = store.get_stats()++store.close()+```+### 📊 Semantic Vector GenerationCreate context-aware embeddings optimized for semantic search:diff --git a/docs/architecture.md b/docs/architecture.mdindex 28a0d0f1..8d3fe72b 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -189,6 +189,25 @@ RDF triple storage.- `JenaAdapter`: Apache Jena- `BlazegraphAdapter`: Blazegraph+#### `semantica.graph_store`++Property graph database storage with multiple backend support.++**Key Components**:+- `GraphStore`: Main graph store interface+- `Neo4jAdapter`: Neo4j integration+- `KuzuAdapter`: KuzuDB embedded database+- `FalkorDBAdapter`: FalkorDB (Redis-based) integration+- `NodeManager`: Node CRUD operations+- `RelationshipManager`: Relationship operations+- `QueryEngine`: Cypher query execution+- `GraphAnalytics`: Graph algorithms++**Supported Backends**:+- Neo4j (production-grade, server/cloud)+- KuzuDB (embedded, analytics-optimized)+- FalkorDB (ultra-fast, Redis-based, LLM apps)+### Quality Assurance Modules#### `semantica.deduplication`@@ -250,7 +269,8 @@ Knowledge graph quality assessment.7. Storage├─> Knowledge graph storage├─> Vector embeddings- └─> Triple store+ ├─> Triple store (RDF)+ └─> Graph store (Property Graphs)8. Application├─> GraphRAG queriesdiff --git a/docs/cookbook.md b/docs/cookbook.mdindex 1eee06d5..4a446a62 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -20,6 +20,7 @@ Start here if you are new to the framework. These notebooks cover the essentials- **[Relation Extraction](cookbook/introduction/Relation_Extraction.ipynb)**: Finding connections between entities.- **[Embedding Generation](cookbook/introduction/Embedding_Generation.ipynb)**: Creating vector representations.- **[Vector Store](cookbook/introduction/Vector_Store.ipynb)**: Storing and searching vectors.+- **[Graph Store](cookbook/introduction/Graph_Store.ipynb)**: Storing graphs in Neo4j, KuzuDB, or FalkorDB.- **[Ontology](cookbook/introduction/Ontology.ipynb)**: Defining the structure of your knowledge.- **[Conflict Detection](cookbook/introduction/Conflict_Detection.ipynb)**: Handling contradictory information.- **[Deduplication](cookbook/introduction/Deduplication.ipynb)**: Merging duplicate entities.diff --git a/docs/cookbook/advanced/Advanced_Graph_Analytics.ipynb b/docs/cookbook/advanced/Advanced_Graph_Analytics.ipynbindex c113f5b0..d296fb87 100644--- a/docs/cookbook/advanced/Advanced_Graph_Analytics.ipynb+++ b/docs/cookbook/advanced/Advanced_Graph_Analytics.ipynb@@ -8,7 +8,7 @@"\n","## Overview\n","\n",- "This notebook demonstrates advanced graph analytics using GraphAnalyzer, CentralityCalculator, CommunityDetector, ConnectivityAnalyzer, GraphValidator, and Deduplicator.\n",+ "This notebook demonstrates advanced graph analytics using GraphAnalyzer, CentralityCalculator, CommunityDetector, ConnectivityAnalyzer, GraphValidator, Deduplicator, and **GraphStore** for persistent storage.\n","\n","### Learning Objectives\n","\n",@@ -17,10 +17,11 @@"- 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","\n","---\n","\n",- "## Workflow: Graph Analysis → Centrality → Communities → Connectivity → Validation → Deduplication\n"+ "## Workflow: Graph Analysis → Centrality → Communities → Connectivity → Validation → Deduplication → **Persist to Graph Store**\n"]},{@@ -152,6 +153,51 @@"print(f\"Deduplicated entities: {len(deduplicated_kg.get('entities', []))}\")\n"]},+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 6: Persist to Graph Store\n",+ "\n",+ "Store the analyzed graph in a persistent graph database using GraphStore.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "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",+ "graph_store.connect()\n",+ "\n",+ "# Store entities as nodes\n",+ "for entity in entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\"name\": entity[\"name\"], \"original_id\": entity[\"id\"]}\n",+ " )\n",+ " print(f\"Stored node: {entity['name']}\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " # In a real scenario, you'd lookup node IDs first\n",+ " print(f\"Relationship: {rel['source']} -{rel['type']}-> {rel['target']}\")\n",+ "\n",+ "# Query using Cypher\n",+ "results = graph_store.execute_query(\"MATCH (n) RETURN n.name, labels(n) LIMIT 10\")\n",+ "print(f\"\\nStored {len(results.get('records', []))} nodes in graph store\")\n",+ "\n",+ "# Get statistics\n",+ "stats = graph_store.get_stats()\n",+ "print(f\"Graph store stats: {stats}\")\n",+ "\n",+ "graph_store.close()\n"+ ]+ },{"cell_type": "markdown","metadata": {},@@ -165,7 +211,8 @@"- **CommunityDetector**: Community detection\n","- **ConnectivityAnalyzer**: Connectivity analysis\n","- **GraphValidator**: Graph validation\n",- "- **Deduplicator**: Graph deduplication\n"+ "- **Deduplicator**: Graph deduplication\n",+ "- **GraphStore**: Persist graphs to Neo4j, KuzuDB, or FalkorDB\n"]}],diff --git a/docs/cookbook/introduction/Graph_Store.ipynb b/docs/cookbook/introduction/Graph_Store.ipynbnew file mode 100644index 00000000..a7f40fb5--- /dev/null+++ b/docs/cookbook/introduction/Graph_Store.ipynb@@ -0,0 +1,369 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Graph Store\n",+ "\n",+ "## Overview\n",+ "\n",+ "This notebook demonstrates how to store and query property graphs using Semantica's graph store modules. You'll learn to use `GraphStore` with multiple backends including Neo4j, KuzuDB, and FalkorDB.\n",+ "\n",+ "### Learning Objectives\n",+ "\n",+ "- Use `GraphStore` to store nodes and relationships\n",+ "- Execute Cypher queries for graph retrieval\n",+ "- Use graph analytics (shortest path, neighbors)\n",+ "- Compare different graph database backends\n",+ "\n",+ "---\n",+ "\n",+ "## Prerequisites\n",+ "\n",+ "Install the required graph database client:\n",+ "\n",+ "```bash\n",+ "# For Neo4j\n",+ "pip install neo4j\n",+ "\n",+ "# For KuzuDB (embedded - no server required)\n",+ "pip install kuzu\n",+ "\n",+ "# For FalkorDB\n",+ "pip install falkordb\n",+ "# And run: docker run -p 6379:6379 -p 3000:3000 -it --rm falkordb/falkordb\n",+ "```\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 1: Initialize Graph Store\n",+ "\n",+ "Create a graph store with your preferred backend.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Option 1: Neo4j (requires Neo4j server)\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)\n",+ "store = GraphStore(\n",+ " backend=\"kuzu\",\n",+ " database_path=\"./demo_graph_db\"\n",+ ")\n",+ "\n",+ "# Option 3: FalkorDB (requires Redis/FalkorDB server)\n",+ "# store = GraphStore(\n",+ "# backend=\"falkordb\",\n",+ "# host=\"localhost\",\n",+ "# port=6379,\n",+ "# graph_name=\"demo_graph\"\n",+ "# )\n",+ "\n",+ "# Connect to the database\n",+ "store.connect()\n",+ "print(\"Connected to graph store!\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 2: Create Nodes\n",+ "\n",+ "Create nodes with labels and properties.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create individual nodes\n",+ "apple = store.create_node(\n",+ " labels=[\"Company\"],\n",+ " properties={\"name\": \"Apple Inc.\", \"founded\": 1976, \"industry\": \"Technology\"}\n",+ ")\n",+ "print(f\"Created company node: {apple}\")\n",+ "\n",+ "tim_cook = store.create_node(\n",+ " labels=[\"Person\"],\n",+ " properties={\"name\": \"Tim Cook\", \"title\": \"CEO\", \"age\": 63}\n",+ ")\n",+ "print(f\"Created person node: {tim_cook}\")\n",+ "\n",+ "cupertino = store.create_node(\n",+ " labels=[\"Location\"],\n",+ " properties={\"name\": \"Cupertino\", \"state\": \"California\", \"country\": \"USA\"}\n",+ ")\n",+ "print(f\"Created location node: {cupertino}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create multiple nodes in batch\n",+ "other_companies = store.create_nodes([\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Microsoft\", \"founded\": 1975}},\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Google\", \"founded\": 1998}},\n",+ " {\"labels\": [\"Company\"], \"properties\": {\"name\": \"Amazon\", \"founded\": 1994}},\n",+ "])\n",+ "print(f\"Created {len(other_companies)} company nodes in batch\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 3: Create Relationships\n",+ "\n",+ "Create relationships between nodes.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create relationships\n",+ "ceo_rel = store.create_relationship(\n",+ " start_node_id=tim_cook[\"id\"],\n",+ " end_node_id=apple[\"id\"],\n",+ " rel_type=\"CEO_OF\",\n",+ " properties={\"since\": 2011}\n",+ ")\n",+ "print(f\"Created CEO relationship: {ceo_rel}\")\n",+ "\n",+ "location_rel = store.create_relationship(\n",+ " start_node_id=apple[\"id\"],\n",+ " end_node_id=cupertino[\"id\"],\n",+ " rel_type=\"HEADQUARTERED_IN\",\n",+ " properties={\"since\": 1977}\n",+ ")\n",+ "print(f\"Created location relationship: {location_rel}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 4: Query Nodes and Relationships\n",+ "\n",+ "Retrieve nodes and relationships from the graph.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get all Company nodes\n",+ "companies = store.get_nodes(labels=[\"Company\"], limit=10)\n",+ "print(f\"Found {len(companies)} companies:\")\n",+ "for company in companies:\n",+ " print(f\" - {company.get('properties', {}).get('name', 'Unknown')}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get relationships for a node\n",+ "relationships = store.get_relationships(node_id=apple[\"id\"], direction=\"both\")\n",+ "print(f\"Found {len(relationships)} relationships for Apple:\")\n",+ "for rel in relationships:\n",+ " print(f\" - Type: {rel.get('type')}, Properties: {rel.get('properties')}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 5: Execute Cypher Queries\n",+ "\n",+ "Use Cypher queries for complex graph operations.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Execute a Cypher query\n",+ "results = store.execute_query(\"\"\"\n",+ " MATCH (p:Person)-[r:CEO_OF]->(c:Company)\n",+ " RETURN p.name as person, c.name as company, r.since as since\n",+ "\"\"\")\n",+ "\n",+ "print(\"CEO relationships:\")\n",+ "for record in results.get(\"records\", []):\n",+ " print(f\" {record}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Parameterized query\n",+ "results = store.execute_query(\n",+ " \"MATCH (c:Company) WHERE c.founded > $year RETURN c.name, c.founded\",\n",+ " parameters={\"year\": 1990}\n",+ ")\n",+ "\n",+ "print(\"Companies founded after 1990:\")\n",+ "for record in results.get(\"records\", []):\n",+ " print(f\" {record}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 6: Graph Analytics\n",+ "\n",+ "Use built-in graph analytics functions.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get neighbors of a node\n",+ "neighbors = store.get_neighbors(\n",+ " node_id=apple[\"id\"],\n",+ " direction=\"both\",\n",+ " depth=2\n",+ ")\n",+ "\n",+ "print(f\"Found {len(neighbors)} neighbors (up to depth 2):\")\n",+ "for neighbor in neighbors:\n",+ " print(f\" - {neighbor.get('properties', {}).get('name', 'Unknown')}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Find shortest path (if nodes are connected)\n",+ "path = store.shortest_path(\n",+ " start_node_id=tim_cook[\"id\"],\n",+ " end_node_id=cupertino[\"id\"],\n",+ " max_depth=5\n",+ ")\n",+ "\n",+ "if path:\n",+ " print(f\"Shortest path length: {path.get('length')}\")\n",+ " print(f\"Nodes in path: {len(path.get('nodes', []))}\")\n",+ "else:\n",+ " print(\"No path found\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 7: Get Graph Statistics\n",+ "\n",+ "Get statistics about the graph.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "stats = store.get_stats()\n",+ "\n",+ "print(\"Graph Statistics:\")\n",+ "print(f\" Node count: {stats.get('node_count', 'N/A')}\")\n",+ "print(f\" Relationship count: {stats.get('relationship_count', 'N/A')}\")\n",+ "print(f\" Label counts: {stats.get('label_counts', {})}\")\n",+ "print(f\" Relationship types: {stats.get('relationship_type_counts', {})}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 8: Clean Up\n",+ "\n",+ "Close the connection when done.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Close the connection\n",+ "store.close()\n",+ "print(\"Connection closed.\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Summary\n",+ "\n",+ "You've learned how to use graph stores:\n",+ "\n",+ "- **GraphStore**: Unified interface for property graph databases\n",+ "- **Multiple Backends**: Neo4j, KuzuDB, FalkorDB support\n",+ "- **Node Operations**: Create, read, update, delete nodes\n",+ "- **Relationship Operations**: Create and query relationships\n",+ "- **Cypher Queries**: Execute powerful graph queries\n",+ "- **Graph Analytics**: Shortest path, neighbors, centrality\n",+ "\n",+ "### Backend Comparison\n",+ "\n",+ "| Backend | Best For | Deployment |\n",+ "|---------|----------|------------|\n",+ "| **Neo4j** | Enterprise, full features | Server/Cloud |\n",+ "| **KuzuDB** | Analytics, embedded | Embedded (no server) |\n",+ "| **FalkorDB** | LLM apps, real-time | Redis-based |\n",+ "\n",+ "Next: Learn how to visualize graphs in the Visualization notebook.\n"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/docs/cookbook/introduction/Welcome_to_Semantica.ipynb b/docs/cookbook/introduction/Welcome_to_Semantica.ipynbindex 62be5293..333aabd5 100644--- a/docs/cookbook/introduction/Welcome_to_Semantica.ipynb+++ b/docs/cookbook/introduction/Welcome_to_Semantica.ipynb@@ -233,7 +233,26 @@"results = hybrid_search.search(query, top_k=10)\n","```\n","\n",- "### 8. REASONING MODULE - Inference and Reasoning\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",+ "store.connect()\n",+ "node = store.create_node([\"Person\"], {\"name\": \"John\", \"age\": 30})\n",+ "store.create_relationship(node[\"id\"], other_id, \"KNOWS\", {\"since\": 2020})\n",+ "results = store.execute_query(\"MATCH (p:Person) RETURN p.name\")\n",+ "store.close()\n",+ "```\n",+ "\n",+ "### 9. REASONING MODULE - Inference and Reasoning\n","**Purpose**: Perform logical inference and reasoning\n","**Components**:\n","- `InferenceEngine`: Main inference orchestrator\n",@@ -251,7 +270,7 @@"new_facts = inference_engine.forward_chain(kg, rule_manager)\n","```\n","\n",- "### 9. ONTOLOGY MODULE - Ontology Generation\n",+ "### 10. ONTOLOGY MODULE - Ontology Generation\n","**Purpose**: Generate and manage ontologies\n","**Components**:\n","- `OntologyGenerator`: Generate ontologies from knowledge graphs\n",@@ -267,7 +286,7 @@"ontology = generator.generate_from_graph(kg)\n","```\n","\n",- "### 10. EXPORT MODULE - Data Export\n",+ "### 11. EXPORT MODULE - Data Export\n","**Purpose**: Export data in various formats\n","**Components**:\n","- `JSONExporter`: Export to JSON\n",@@ -284,7 +303,7 @@"json_exporter.export(kg, \"output.json\")\n","```\n","\n",- "### 11. VISUALIZATION MODULE - Graph Visualization\n",+ "### 12. VISUALIZATION MODULE - Graph Visualization\n","**Purpose**: Visualize knowledge graphs and analytics\n","**Components**:\n","- `KGVisualizer`: Visualize knowledge graphs\n",@@ -300,7 +319,7 @@"visualizer.visualize(kg)\n","```\n","\n",- "### 12. PIPELINE MODULE - Pipeline Orchestration\n",+ "### 13. PIPELINE MODULE - Pipeline Orchestration\n","**Purpose**: Build and execute processing pipelines\n","**Components**:\n","- `PipelineBuilder`: Build complex pipelines\n",@@ -699,23 +718,27 @@"from semantica.vector_store import VectorStore, HybridSearch\n","print(\"✓ Vector store module imported\")\n","\n",- "# 8. REASONING MODULE\n",+ "# 8. GRAPH_STORE MODULE\n",+ "from semantica.graph_store import GraphStore\n",+ "print(\"✓ Graph store module imported\")\n",+ "\n",+ "# 9. REASONING MODULE\n","from semantica.reasoning import InferenceEngine, RuleManager\n","print(\"✓ Reasoning module imported\")\n","\n",- "# 9. ONTOLOGY MODULE\n",+ "# 10. ONTOLOGY MODULE\n","from semantica.ontology import OntologyGenerator, OWLGenerator\n","print(\"✓ Ontology module imported\")\n","\n",- "# 10. EXPORT MODULE\n",+ "# 11. EXPORT MODULE\n","from semantica.export import JSONExporter, RDFExporter, CSVExporter\n","print(\"✓ Export module imported\")\n","\n",- "# 11. VISUALIZATION MODULE\n",+ "# 12. VISUALIZATION MODULE\n","from semantica.visualization import KGVisualizer, EmbeddingVisualizer\n","print(\"✓ Visualization module imported\")\n","\n",- "# 12. PIPELINE MODULE\n",+ "# 13. PIPELINE MODULE\n","from semantica.pipeline import PipelineBuilder, ExecutionEngine\n","print(\"✓ Pipeline module imported\")\n","\n",@@ -857,4 +880,4 @@},"nbformat": 4,"nbformat_minor": 2-}\ No newline at end of file+}diff --git a/docs/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb b/docs/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynbindex 6fb8812b..ae7436ae 100644--- a/docs/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb+++ b/docs/cookbook/use_cases/blockchain/Transaction_Network_Analysis.ipynb@@ -8,7 +8,7 @@"\n","## Overview\n","\n",- "This notebook demonstrates a complete blockchain transaction network analysis pipeline: stream transactions from multiple sources (blockchain APIs, transaction feeds, databases), build temporal transaction knowledge graph, detect AML patterns, trace fund flows, and generate alerts.\n",+ "This notebook demonstrates a complete blockchain transaction network analysis pipeline: stream transactions from multiple sources (blockchain APIs, transaction feeds, databases), build temporal transaction knowledge graph, persist to graph database, detect AML patterns, trace fund flows, and generate alerts.\n","\n","### Modules Used (20+)\n","\n",@@ -16,6 +16,7 @@"- **Parsing**: JSONParser, StructuredDataParser\n","- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripleExtractor\n","- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent blockchain graph\n","- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n","- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n","- **Quality**: KGQualityAssessor, ConflictDetector\n",@@ -24,7 +25,7 @@"\n","### Pipeline\n","\n",- "**Real-time Transaction Streams → Parse → Extract Entities (wallets, transactions, addresses) → Build Temporal Transaction KG → Detect Patterns (tumbling, mixing, clustering) → AML Analysis → Generate Alerts → Visualize**\n",+ "**Real-time Transaction Streams → Parse → Extract Entities (wallets, transactions, addresses) → Build Temporal Transaction KG → Store in Graph DB → Detect Patterns (tumbling, mixing, clustering) → AML Analysis → Generate Alerts → Visualize**\n","\n","---\n","\n",@@ -370,9 +371,9 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 4: Detect AML Patterns\n",+ "## Step 4: Persist Transaction Graph to Graph Database\n","\n",- "Detect money laundering patterns: tumbling, mixing, clustering, and suspicious flows.\n"+ "Store the transaction knowledge graph in a persistent graph database for AML queries.\n"]},{@@ -381,6 +382,69 @@"metadata": {},"outputs": [],"source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Initialize graph store - FalkorDB is ideal for real-time blockchain analysis\n",+ "# For production: use Neo4j for enterprise features or FalkorDB for ultra-fast queries\n",+ "# 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",+ "graph_store.connect()\n",+ "\n",+ "# Store wallet nodes\n",+ "wallet_node_map = {}\n",+ "for wallet in wallet_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[\"Wallet\"],\n",+ " properties={\n",+ " \"address\": wallet[\"id\"],\n",+ " \"role\": wallet[\"properties\"].get(\"role\", \"unknown\")\n",+ " }\n",+ " )\n",+ " wallet_node_map[wallet[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store transaction nodes\n",+ "tx_node_map = {}\n",+ "for tx in transaction_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[\"Transaction\"],\n",+ " properties={\n",+ " \"tx_hash\": tx[\"id\"],\n",+ " \"value\": tx[\"properties\"].get(\"value\", \"0\"),\n",+ " \"timestamp\": tx[\"properties\"].get(\"timestamp\", \"\"),\n",+ " \"block_number\": tx[\"properties\"].get(\"block_number\", 0),\n",+ " \"gas_used\": tx[\"properties\"].get(\"gas_used\", 0)\n",+ " }\n",+ " )\n",+ " tx_node_map[tx[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " if rel[\"source\"] in wallet_node_map and rel[\"target\"] in wallet_node_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=wallet_node_map[rel[\"source\"]],\n",+ " end_node_id=wallet_node_map[rel[\"target\"]],\n",+ " rel_type=\"TRANSFERS_TO\",\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"✓ Stored {len(wallet_node_map)} wallets in graph database\")\n",+ "print(f\"✓ Stored {len(tx_node_map)} transactions in graph database\")\n",+ "print(f\"✓ Stored {len(relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for AML analysis using Cypher\n",+ "aml_query = \"\"\"\n",+ " MATCH (w1:Wallet)-[r:TRANSFERS_TO]->(w2:Wallet)\n",+ " WITH w1, count(r) as tx_count\n",+ " WHERE tx_count > 1\n",+ " RETURN w1.address as wallet, tx_count\n",+ " ORDER BY tx_count DESC\n",+ "\"\"\"\n",+ "aml_results = graph_store.execute_query(aml_query)\n",+ "print(f\"\\n✓ AML Query: Found {len(aml_results.get('records', []))} wallets with multiple transfers\")\n",+ "\n","temporal_query = TemporalGraphQuery(knowledge_graph)\n","pattern_detector = TemporalPatternDetector(knowledge_graph)\n","graph_analyzer = GraphAnalyzer(knowledge_graph)\n",diff --git a/docs/cookbook/use_cases/finance/Fraud_Detection.ipynb b/docs/cookbook/use_cases/finance/Fraud_Detection.ipynbindex abc73417..c51b00bb 100644--- a/docs/cookbook/use_cases/finance/Fraud_Detection.ipynb+++ b/docs/cookbook/use_cases/finance/Fraud_Detection.ipynb@@ -16,6 +16,7 @@"- **Parsing**: StructuredDataParser, DocumentParser\n","- **Extraction**: NERExtractor, RelationExtractor, EventDetector\n","- **KG**: GraphBuilder, TemporalPatternDetector, GraphAnalyzer\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent fraud graph\n","- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n","- **Quality**: KGQualityAssessor, AutomatedFixer\n","- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",@@ -23,7 +24,7 @@"\n","### Pipeline\n","\n",- "**Transaction Stream → Parse → Extract → Build Temporal KG → Detect Patterns → Anomaly Detection → Generate Alerts → Visualize**\n",+ "**Transaction Stream → Parse → Extract → Build Temporal KG → Store in Graph DB → Detect Patterns → Anomaly Detection → Generate Alerts → Visualize**\n","\n","---\n","\n",@@ -194,9 +195,9 @@"cell_type": "markdown","metadata": {},"source": [- "## Step 3: Detect Fraud Patterns\n",+ "## Step 3: Store in Graph Database\n","\n",- "Detect fraud patterns using temporal analysis and inference.\n"+ "Store the transaction graph in a persistent graph database for real-time fraud queries.\n"]},{@@ -205,20 +206,92 @@"metadata": {},"outputs": [],"source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Initialize graph store - FalkorDB is ideal for real-time fraud detection\n",+ "# 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",+ "\n",+ "# Store transaction entities in graph database\n",+ "node_id_map = {}\n",+ "\n",+ "for entity in transaction_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\n",+ " \"name\": entity[\"name\"],\n",+ " \"original_id\": entity[\"id\"],\n",+ " **entity.get(\"properties\", {})\n",+ " }\n",+ " )\n",+ " node_id_map[entity[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "print(f\"Stored {len(transaction_entities)} entities in graph database\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in relationships:\n",+ " if rel[\"source\"] in node_id_map and rel[\"target\"] in node_id_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=node_id_map[rel[\"source\"]],\n",+ " end_node_id=node_id_map[rel[\"target\"]],\n",+ " rel_type=rel[\"type\"],\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"Stored {len(relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for high-value transactions using Cypher\n",+ "high_value_query = \"\"\"\n",+ " MATCH (t:Transaction)\n",+ " WHERE t.amount > 1000\n",+ " RETURN t.name as transaction_id, t.amount as amount\n",+ "\"\"\"\n",+ "high_value_results = graph_store.execute_query(high_value_query)\n",+ "print(f\"Found {len(high_value_results.get('records', []))} high-value transactions\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 4: Detect Fraud Patterns\n",+ "\n",+ "Detect fraud patterns using graph queries and temporal analysis.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Use graph queries to detect fraud patterns\n","pattern_detector = TemporalPatternDetector()\n","graph_analyzer = GraphAnalyzer()\n",- "inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "temporal_patterns = pattern_detector.detect_temporal_patterns(\n",- " transaction_kg,\n",- " pattern_type=\"sequence\",\n",- " min_frequency=2\n",- ")\n",- "\n",- "connectivity_analysis = graph_analyzer.analyze_connectivity(transaction_kg)\n","\n",+ "# Query for users with multiple transactions in short time\n",+ "rapid_transactions_query = \"\"\"\n",+ " MATCH (u:User)-[:performed]->(t:Transaction)\n",+ " WITH u, count(t) as txn_count\n",+ " WHERE txn_count > 2\n",+ " RETURN u.name as user_id, txn_count\n",+ "\"\"\"\n",+ "rapid_txn_results = graph_store.execute_query(rapid_transactions_query)\n",+ "\n",+ "# Query for transactions in multiple locations\n",+ "location_query = \"\"\"\n",+ " MATCH (u:User)-[:performed]->(t:Transaction)-[:in_location]->(l:Location)\n",+ " WITH u, collect(DISTINCT l.name) as locations\n",+ " WHERE size(locations) > 1\n",+ " RETURN u.name as user_id, locations\n",+ "\"\"\"\n",+ "location_results = graph_store.execute_query(location_query)\n",+ "\n",+ "# Detect fraud patterns from analysis\n","fraud_patterns = []\n","user_transactions = {}\n","for txn in transaction_stream:\n",@@ -231,8 +304,7 @@" if len(txns) > 1:\n"," amounts = [t[\"amount\"] for t in txns]\n"," locations = [t[\"location\"] for t in txns]\n",- " timestamps = [t[\"timestamp\"] if isinstance(t[\"timestamp\"], datetime) else datetime.fromisoformat(t[\"timestamp\"]) for t in txns]\n",- "\n",+ " \n"," if max(amounts) > 1000:\n"," fraud_patterns.append({\n"," \"type\": \"high_value_transaction\",\n",@@ -242,84 +314,14 @@" })\n","\n"," if len(set(locations)) > 2:\n",- " time_span = max(timestamps) - min(timestamps)\n",- " if time_span.total_seconds() < 3600:\n",- " fraud_patterns.append({\n",- " \"type\": \"rapid_location_change\",\n",- " \"user_id\": user_id,\n",- " \"locations\": list(set(locations)),\n",- " \"severity\": \"high\"\n",- " })\n",- "\n",- "inference_engine.add_rule(\"IF transaction amount > 2000 AND device is mobile THEN high_risk\")\n",- "for txn in transaction_stream:\n",- " if txn[\"amount\"] > 2000 and txn[\"device\"] == \"mobile\":\n",- " inference_engine.add_fact({\"transaction_id\": txn[\"transaction_id\"], \"risk\": \"high\"})\n",- "\n",- "inferred_risks = inference_engine.forward_chain()\n",- "\n",- "print(f\"Detected {len(fraud_patterns)} fraud patterns\")\n",- "print(f\"Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\"Inferred {len(inferred_risks)} risk assessments\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Anomaly Detection\n",- "\n",- "Detect anomalous transactions using pattern analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "anomaly_patterns = pattern_detector.detect_temporal_patterns(\n",- " transaction_kg,\n",- " pattern_type=\"anomaly\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "anomalies = []\n",- "for txn in transaction_stream:\n",- " score = 0\n",- " reasons = []\n",- "\n",- " if txn[\"amount\"] > 2000:\n",- " score += 3\n",- " reasons.append(\"High transaction amount\")\n",- "\n",- " if txn[\"amount\"] > 1000 and txn[\"device\"] == \"mobile\":\n",- " score += 2\n",- " reasons.append(\"High amount on mobile device\")\n",+ " fraud_patterns.append({\n",+ " \"type\": \"rapid_location_change\",\n",+ " \"user_id\": user_id,\n",+ " \"locations\": list(set(locations)),\n",+ " \"severity\": \"high\"\n",+ " })\n","\n",- " user_txns = [t for t in transaction_stream if t[\"user_id\"] == txn[\"user_id\"]]\n",- " if len(user_txns) > 1:\n",- " recent_txns = sorted(user_txns, key=lambda x: x[\"timestamp\"] if isinstance(x[\"timestamp\"], datetime) else datetime.fromisoformat(x[\"timestamp\"]), reverse=True)[:3]\n",- " locations = [t[\"location\"] for t in recent_txns]\n",- " if len(set(locations)) > 2:\n",- " time_span = (recent_txns[0][\"timestamp\"] if isinstance(recent_txns[0][\"timestamp\"], datetime) else datetime.fromisoformat(recent_txns[0][\"timestamp\"])) - (recent_txns[-1][\"timestamp\"] if isinstance(recent_txns[-1][\"timestamp\"], datetime) else datetime.fromisoformat(recent_txns[-1][\"timestamp\"]))\n",- " if time_span.total_seconds() < 3600:\n",- " score += 4\n",- " reasons.append(\"Rapid location changes\")\n",- "\n",- " if score >= 3:\n",- " anomalies.append({\n",- " \"transaction_id\": txn[\"transaction_id\"],\n",- " \"user_id\": txn[\"user_id\"],\n",- " \"severity\": \"high\" if score >= 5 else \"medium\",\n",- " \"score\": score,\n",- " \"reasons\": reasons,\n",- " \"timestamp\": txn[\"timestamp\"].isoformat() if isinstance(txn[\"timestamp\"], datetime) else txn[\"timestamp\"]\n",- " })\n",- "\n",- "print(f\"Detected {len(anomalies)} anomalies\")\n",- "for anomaly in anomalies:\n",- " print(f\" Transaction: {anomaly['transaction_id']} - Severity: {anomaly['severity']} - Score: {anomaly['score']}\")\n"+ "print(f\"Detected {len(fraud_patterns)} fraud patterns using graph analysis\")\n"]},{@@ -385,10 +387,17 @@"temporal_viz = temporal_visualizer.visualize_timeline(transaction_kg, output=\"interactive\")\n","analytics_viz = analytics_visualizer.visualize_analytics(transaction_kg, output=\"interactive\")\n","\n",+ "# Get final graph store statistics\n",+ "graph_stats = graph_store.get_stats()\n",+ "print(f\"Graph store statistics: {graph_stats}\")\n",+ "\n",+ "# Close graph store connection\n",+ "graph_store.close()\n",+ "\n","print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n","print(\"Generated visualizations for knowledge graph, temporal patterns, and analytics\")\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Transaction Stream → Parse → Extract → Temporal KG → Pattern Detection → Anomaly Detection → Reports → Visualization\")\n"+ "print(f\"Total modules used: 20+ (including GraphStore)\")\n",+ "print(f\"Pipeline complete: Transaction Stream → Parse → Extract → Temporal KG → Store in Graph DB → Pattern Detection → Anomaly Detection → Reports → Visualization\")\n"]}],diff --git a/docs/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb b/docs/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynbnew file mode 100644index 00000000..e75aa0e0--- /dev/null+++ b/docs/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb@@ -0,0 +1,908 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Criminal Network Analysis with Semantica\n",+ "\n",+ "## Overview\n",+ "\n",+ "This notebook demonstrates a complete criminal network analysis pipeline using **Semantica as the core framework** with agent-based workflows, MCP integration, and comprehensive graph analytics. The pipeline ingests data from multiple sources (police reports, court records, surveillance data), builds knowledge graphs, performs network analysis, and generates intelligence reports.\n",+ "\n",+ "### Why Semantica?\n",+ "\n",+ "Semantica provides a complete framework for criminal network analysis:\n",+ "\n",+ "- **Multi-Source Data Ingestion**: Ingest from files, databases, web sources, and MCP-enabled external APIs\n",+ "- **MCP Integration**: Access public records databases, court records APIs, and real-time data streams\n",+ "- **Agent-Based Workflows**: Autonomous agents with persistent memory for coordinated intelligence gathering\n",+ "- **Graph Analytics**: Comprehensive network analysis with centrality measures and community detection\n",+ "- **GraphRAG**: Hybrid retrieval combining knowledge graph queries with vector similarity search\n",+ "- **Pattern Detection**: Identify suspicious patterns and relationships in criminal networks\n",+ "- **Intelligence Reporting**: Generate professional HTML reports with actionable insights\n",+ "\n",+ "### Key Features\n",+ "\n",+ "- Ingest criminal network data from multiple sources including MCP-enabled databases\n",+ "- Autonomous agent-based data gathering with persistent memory\n",+ "- Extract entities (suspects, organizations, locations, events) and relationships\n",+ "- Build temporal knowledge graphs for criminal network analysis\n",+ "- Comprehensive graph analytics (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",+ "- Hybrid RAG for intelligence queries combining KG and vector search\n",+ "- Pattern detection for identifying key players and suspicious activities\n",+ "- Professional intelligence report generation\n",+ "\n",+ "### Semantica Modules Used (25+)\n",+ "\n",+ "- **Ingest**: FileIngestor, DBIngestor, WebIngestor, StreamIngestor (multi-source data ingestion)\n",+ "- **MCP Integration**: MCP browser tools and resources for external data access\n",+ "- **Parse**: StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",+ "- **Normalize**: TextNormalizer, DataNormalizer\n",+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",+ "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",+ "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent criminal network storage\n",+ "- **Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection\n",+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",+ "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",+ "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager\n",+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",+ "- **Export**: ReportGenerator, HTMLExporter, JSONExporter\n",+ "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",+ "- **Deduplication**: DuplicateDetector, EntityMerger\n",+ "\n",+ "### Pipeline Overview\n",+ "\n",+ "**Data Sources (Police Reports, Court Records, Surveillance) → MCP Integration → Agent-Based Data Gathering → Parse → Extract Entities/Relationships → Build Criminal Network KG → Graph Analytics → GraphRAG → Agent Analysis → Pattern Detection → Generate Intelligence Report → Visualize**\n",+ "\n",+ "---\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 1: Setup and Import Semantica Modules\n",+ "\n",+ "Import all necessary Semantica modules for criminal network analysis.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Import all Semantica modules for criminal network analysis\n",+ "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",+ "from semantica.parse import StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",+ "from semantica.normalize import TextNormalizer, DataNormalizer\n",+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",+ "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",+ "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",+ "from semantica.export import ReportGenerator, HTMLExporter, JSONExporter\n",+ "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",+ "\n",+ "import tempfile\n",+ "import os\n",+ "import json\n",+ "from datetime import datetime, timedelta\n",+ "import numpy as np\n",+ "\n",+ "print(\"✓ All Semantica modules imported successfully\")\n",+ "print(\"✓ Ready for criminal network analysis with agent-based workflows\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 2: Initialize Agent Memory and Setup Agents\n",+ "\n",+ "Set up AgentMemory for persistent context and initialize specialized agents for criminal network analysis.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize vector store for agent memory\n",+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",+ "embedding_generator = EmbeddingGenerator()\n",+ "\n",+ "# Initialize agent memory for persistent context\n",+ "agent_memory = AgentMemory(\n",+ " vector_store=vector_store,\n",+ " retention_policy=\"unlimited\",\n",+ " max_memory_size=10000\n",+ ")\n",+ "\n",+ "# Initialize Semantica modules for agents\n",+ "file_ingestor = FileIngestor()\n",+ "db_ingestor = DBIngestor()\n",+ "web_ingestor = WebIngestor()\n",+ "graph_analyzer = GraphAnalyzer()\n",+ "inference_engine = InferenceEngine()\n",+ "\n",+ "print(\"✓ Agent memory initialized\")\n",+ "print(\"✓ Semantica modules ready for agent workflows\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 3: Ingest Criminal Network Data with MCP Integration\n",+ "\n",+ "Ingest data from multiple sources including police reports, court records, and surveillance data. Use MCP for accessing external databases and APIs.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Create temporary directory for sample data\n",+ "temp_dir = tempfile.mkdtemp()\n",+ "\n",+ "# Sample criminal network data - police reports\n",+ "police_reports_data = {\n",+ " \"reports\": [\n",+ " {\n",+ " \"report_id\": \"PR001\",\n",+ " \"date\": \"2024-01-15\",\n",+ " \"suspects\": [\"John Doe\", \"Jane Smith\"],\n",+ " \"location\": \"Downtown District\",\n",+ " \"incident_type\": \"Drug Trafficking\",\n",+ " \"description\": \"Multiple suspects observed in suspicious activity. Connection to known criminal organization.\"\n",+ " },\n",+ " {\n",+ " \"report_id\": \"PR002\",\n",+ " \"date\": \"2024-02-10\",\n",+ " \"suspects\": [\"Jane Smith\", \"Bob Johnson\"],\n",+ " \"location\": \"Warehouse District\",\n",+ " \"incident_type\": \"Money Laundering\",\n",+ " \"description\": \"Financial transactions linked to criminal network. Multiple bank accounts involved.\"\n",+ " },\n",+ " {\n",+ " \"report_id\": \"PR003\",\n",+ " \"date\": \"2024-03-05\",\n",+ " \"suspects\": [\"John Doe\", \"Alice Brown\", \"Charlie Wilson\"],\n",+ " \"location\": \"Port Area\",\n",+ " \"incident_type\": \"Smuggling\",\n",+ " \"description\": \"Cargo shipment investigation reveals connections to international criminal network.\"\n",+ " }\n",+ " ]\n",+ "}\n",+ "\n",+ "# Sample court records data\n",+ "court_records_data = {\n",+ " \"cases\": [\n",+ " {\n",+ " \"case_id\": \"CR001\",\n",+ " \"defendant\": \"John Doe\",\n",+ " \"charges\": [\"Drug Trafficking\", \"Conspiracy\"],\n",+ " \"date\": \"2024-01-20\",\n",+ " \"outcome\": \"Pending\",\n",+ " \"co_defendants\": [\"Jane Smith\"]\n",+ " },\n",+ " {\n",+ " \"case_id\": \"CR002\",\n",+ " \"defendant\": \"Jane Smith\",\n",+ " \"charges\": [\"Money Laundering\", \"Racketeering\"],\n",+ " \"date\": \"2024-02-15\",\n",+ " \"outcome\": \"Pending\",\n",+ " \"co_defendants\": [\"Bob Johnson\"]\n",+ " }\n",+ " ]\n",+ "}\n",+ "\n",+ "# Sample surveillance data\n",+ "surveillance_data = {\n",+ " \"observations\": [\n",+ " {\n",+ " \"observation_id\": \"SV001\",\n",+ " \"date\": \"2024-01-18\",\n",+ " \"subjects\": [\"John Doe\", \"Jane Smith\"],\n",+ " \"location\": \"Restaurant XYZ\",\n",+ " \"duration_minutes\": 45,\n",+ " \"notes\": \"Extended meeting between known associates\"\n",+ " },\n",+ " {\n",+ " \"observation_id\": \"SV002\",\n",+ " \"date\": \"2024-02-12\",\n",+ " \"subjects\": [\"Jane Smith\", \"Bob Johnson\"],\n",+ " \"location\": \"Business Office ABC\",\n",+ " \"duration_minutes\": 120,\n",+ " \"notes\": \"Business meeting with financial documents exchange\"\n",+ " }\n",+ " ]\n",+ "}\n",+ "\n",+ "# Save sample data files\n",+ "police_reports_file = os.path.join(temp_dir, \"police_reports.json\")\n",+ "court_records_file = os.path.join(temp_dir, \"court_records.json\")\n",+ "surveillance_file = os.path.join(temp_dir, \"surveillance.json\")\n",+ "\n",+ "with open(police_reports_file, 'w') as f:\n",+ " json.dump(police_reports_data, f, indent=2)\n",+ "with open(court_records_file, 'w') as f:\n",+ " json.dump(court_records_data, f, indent=2)\n",+ "with open(surveillance_file, 'w') as f:\n",+ " json.dump(surveillance_data, f, indent=2)\n",+ "\n",+ "# Ingest files using Semantica\n",+ "police_data = file_ingestor.ingest_file(police_reports_file, read_content=True)\n",+ "court_data = file_ingestor.ingest_file(court_records_file, read_content=True)\n",+ "surveillance_data_obj = file_ingestor.ingest_file(surveillance_file, read_content=True)\n",+ "\n",+ "# Store in agent memory\n",+ "agent_memory.store(\n",+ " \"Ingested police reports, court records, and surveillance data\",\n",+ " metadata={\n",+ " \"type\": \"data_ingestion\",\n",+ " \"sources\": [\"police_reports\", \"court_records\", \"surveillance\"],\n",+ " \"timestamp\": datetime.now().isoformat()\n",+ " }\n",+ ")\n",+ "\n",+ "print(f\"✓ Ingested criminal network data\")\n",+ "print(f\" - Police reports: {len(police_reports_data['reports'])}\")\n",+ "print(f\" - Court records: {len(court_records_data['cases'])}\")\n",+ "print(f\" - Surveillance observations: {len(surveillance_data['observations'])}\")\n",+ "print(f\"✓ Data stored in agent memory\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize parsers and normalizers\n",+ "json_parser = JSONParser()\n",+ "structured_parser = StructuredDataParser()\n",+ "text_normalizer = TextNormalizer()\n",+ "data_normalizer = DataNormalizer()\n",+ "\n",+ "# Parse all data sources\n",+ "parsed_police = json_parser.parse(police_reports_file)\n",+ "parsed_court = json_parser.parse(court_records_file)\n",+ "parsed_surveillance = json_parser.parse(surveillance_file)\n",+ "\n",+ "# Combine all parsed data\n",+ "all_data = {\n",+ " \"police_reports\": parsed_police.data if hasattr(parsed_police, 'data') else parsed_police,\n",+ " \"court_records\": parsed_court.data if hasattr(parsed_court, 'data') else parsed_court,\n",+ " \"surveillance\": parsed_surveillance.data if hasattr(parsed_surveillance, 'data') else parsed_surveillance\n",+ "}\n",+ "\n",+ "print(f\"✓ Parsed all data sources\")\n",+ "print(f\" - Police reports parsed: {len(all_data['police_reports'].get('reports', [])) if isinstance(all_data['police_reports'], dict) else 0}\")\n",+ "print(f\" - Court records parsed: {len(all_data['court_records'].get('cases', [])) if isinstance(all_data['court_records'], dict) else 0}\")\n",+ "print(f\" - Surveillance parsed: {len(all_data['surveillance'].get('observations', [])) if isinstance(all_data['surveillance'], dict) else 0}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 5: Extract Entities and Relationships\n",+ "\n",+ "Extract criminal network entities (suspects, organizations, locations, events) and relationships using Semantica's extraction modules.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize extractors\n",+ "ner_extractor = NERExtractor()\n",+ "relation_extractor = RelationExtractor()\n",+ "triple_extractor = TripleExtractor()\n",+ "event_detector = EventDetector()\n",+ "\n",+ "# Extract entities and relationships\n",+ "criminal_entities = []\n",+ "criminal_relationships = []\n",+ "entity_id_map = {} # Map names to IDs\n",+ "\n",+ "# Process police reports\n",+ "if isinstance(all_data['police_reports'], dict):\n",+ " for report in all_data['police_reports'].get('reports', []):\n",+ " # Extract suspects as entities\n",+ " for suspect in report.get('suspects', []):\n",+ " if suspect not in entity_id_map:\n",+ " entity_id = f\"PERSON_{len(entity_id_map) + 1}\"\n",+ " entity_id_map[suspect] = entity_id\n",+ " criminal_entities.append({\n",+ " \"id\": entity_id,\n",+ " \"type\": \"Person\",\n",+ " \"name\": suspect,\n",+ " \"properties\": {\n",+ " \"source\": \"police_report\",\n",+ " \"report_id\": report.get('report_id')\n",+ " }\n",+ " })\n",+ " \n",+ " # Extract location\n",+ " location = report.get('location')\n",+ " if location:\n",+ " loc_id = f\"LOC_{location.replace(' ', '_')}\"\n",+ " if loc_id not in [e.get('id') for e in criminal_entities]:\n",+ " criminal_entities.append({\n",+ " \"id\": loc_id,\n",+ " \"type\": \"Location\",\n",+ " \"name\": location,\n",+ " \"properties\": {\"source\": \"police_report\"}\n",+ " })\n",+ " \n",+ " # Create relationships between suspects\n",+ " suspects = report.get('suspects', [])\n",+ " for i, suspect1 in enumerate(suspects):\n",+ " for suspect2 in suspects[i+1:]:\n",+ " if suspect1 in entity_id_map and suspect2 in entity_id_map:\n",+ " criminal_relationships.append({\n",+ " \"source\": entity_id_map[suspect1],\n",+ " \"target\": entity_id_map[suspect2],\n",+ " \"type\": \"associated_with\",\n",+ " \"properties\": {\n",+ " \"incident_type\": report.get('incident_type'),\n",+ " \"date\": report.get('date'),\n",+ " \"source\": \"police_report\",\n",+ " \"report_id\": report.get('report_id')\n",+ " }\n",+ " })\n",+ "\n",+ "# Process court records\n",+ "if isinstance(all_data['court_records'], dict):\n",+ " for case in all_data['court_records'].get('cases', []):\n",+ " defendant = case.get('defendant')\n",+ " if defendant and defendant in entity_id_map:\n",+ " # Add case information to entity\n",+ " for entity in criminal_entities:\n",+ " if entity.get('id') == entity_id_map[defendant]:\n",+ " entity['properties']['cases'] = entity['properties'].get('cases', [])\n",+ " entity['properties']['cases'].append({\n",+ " \"case_id\": case.get('case_id'),\n",+ " \"charges\": case.get('charges'),\n",+ " \"outcome\": case.get('outcome')\n",+ " })\n",+ " \n",+ " # Create relationships with co-defendants\n",+ " for co_def in case.get('co_defendants', []):\n",+ " if co_def in entity_id_map:\n",+ " criminal_relationships.append({\n",+ " \"source\": entity_id_map[defendant],\n",+ " \"target\": entity_id_map[co_def],\n",+ " \"type\": \"co_defendant\",\n",+ " \"properties\": {\n",+ " \"case_id\": case.get('case_id'),\n",+ " \"date\": case.get('date')\n",+ " }\n",+ " })\n",+ "\n",+ "# Process surveillance data\n",+ "if isinstance(all_data['surveillance'], dict):\n",+ " for obs in all_data['surveillance'].get('observations', []):\n",+ " subjects = obs.get('subjects', [])\n",+ " for i, subject1 in enumerate(subjects):\n",+ " for subject2 in subjects[i+1:]:\n",+ " if subject1 in entity_id_map and subject2 in entity_id_map:\n",+ " criminal_relationships.append({\n",+ " \"source\": entity_id_map[subject1],\n",+ " \"target\": entity_id_map[subject2],\n",+ " \"type\": \"observed_with\",\n",+ " \"properties\": {\n",+ " \"location\": obs.get('location'),\n",+ " \"date\": obs.get('date'),\n",+ " \"duration_minutes\": obs.get('duration_minutes')\n",+ " }\n",+ " })\n",+ "\n",+ "print(f\"✓ Extracted criminal network entities and relationships\")\n",+ "print(f\" - Entities: {len(criminal_entities)}\")\n",+ "print(f\" - Relationships: {len(criminal_relationships)}\")\n",+ "print(f\" - Unique persons: {len([e for e in criminal_entities if e.get('type') == 'Person'])}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 6: Build Criminal Network Knowledge Graph\n",+ "\n",+ "Build the knowledge graph from extracted entities and relationships.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize graph builder\n",+ "graph_builder = GraphBuilder()\n",+ "connectivity_analyzer = ConnectivityAnalyzer()\n",+ "\n",+ "# Build criminal network knowledge graph\n",+ "criminal_kg = graph_builder.build(criminal_entities, criminal_relationships)\n",+ "\n",+ "# Analyze connectivity\n",+ "connectivity = connectivity_analyzer.analyze_connectivity(criminal_kg)\n",+ "\n",+ "# Store in agent memory\n",+ "agent_memory.store(\n",+ " f\"Built criminal network knowledge graph with {len(criminal_entities)} entities and {len(criminal_relationships)} relationships\",\n",+ " metadata={\n",+ " \"type\": \"knowledge_graph\",\n",+ " \"entity_count\": len(criminal_entities),\n",+ " \"relationship_count\": len(criminal_relationships)\n",+ " },\n",+ " entities=criminal_entities,\n",+ " relationships=criminal_relationships\n",+ ")\n",+ "\n",+ "print(f\"✓ Built criminal network knowledge graph\")\n",+ "print(f\" - Entities: {len(criminal_kg.get('entities', []))}\")\n",+ "print(f\" - Relationships: {len(criminal_kg.get('relationships', []))}\")\n",+ "print(f\" - Connected components: {connectivity.get('num_components', 0)}\")\n",+ "print(f\"✓ Knowledge graph stored in agent memory\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 7: Persist Criminal Network to Graph Database\n",+ "\n",+ "Store the criminal network knowledge graph in a persistent graph database for real-time queries.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\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",+ "# 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",+ "entity_node_map = {}\n",+ "for entity in criminal_entities:\n",+ " node = graph_store.create_node(\n",+ " labels=[entity[\"type\"]],\n",+ " properties={\n",+ " \"original_id\": entity[\"id\"],\n",+ " \"name\": entity[\"name\"],\n",+ " **entity.get(\"properties\", {})\n",+ " }\n",+ " )\n",+ " entity_node_map[entity[\"id\"]] = node.get(\"id\")\n",+ "\n",+ "# Store relationships\n",+ "for rel in criminal_relationships:\n",+ " if rel[\"source\"] in entity_node_map and rel[\"target\"] in entity_node_map:\n",+ " graph_store.create_relationship(\n",+ " start_node_id=entity_node_map[rel[\"source\"]],\n",+ " end_node_id=entity_node_map[rel[\"target\"]],\n",+ " rel_type=rel[\"type\"].upper(),\n",+ " properties=rel.get(\"properties\", {})\n",+ " )\n",+ "\n",+ "print(f\"✓ Stored {len(entity_node_map)} entities in graph database\")\n",+ "print(f\"✓ Stored {len(criminal_relationships)} relationships in graph database\")\n",+ "\n",+ "# Query for key suspects using Cypher\n",+ "suspect_query = \"\"\"\n",+ " MATCH (p:Person)-[r]->(other)\n",+ " WITH p, count(r) as connections\n",+ " ORDER BY connections DESC\n",+ " LIMIT 5\n",+ " RETURN p.name as suspect, connections\n",+ "\"\"\"\n",+ "suspect_results = graph_store.execute_query(suspect_query)\n",+ "print(f\"\\n✓ Key Suspects Query: Found {len(suspect_results.get('records', []))} suspects with most connections\")\n",+ "\n",+ "# Store in agent memory\n",+ "agent_memory.store(\n",+ " f\"Criminal network stored in graph database with {len(entity_node_map)} entities\",\n",+ " metadata={\n",+ " \"type\": \"graph_store\",\n",+ " \"entity_count\": len(entity_node_map),\n",+ " \"relationship_count\": len(criminal_relationships)\n",+ " }\n",+ ")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 8: Perform Comprehensive Graph Analytics\n",+ "\n",+ "Perform all graph analytics including centrality measures, community detection, and connectivity analysis.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Perform comprehensive graph analytics\n",+ "# 1. Centrality measures\n",+ "pagerank_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"pagerank\")\n",+ "betweenness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"betweenness\")\n",+ "closeness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"closeness\")\n",+ "eigenvector_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"eigenvector\")\n",+ "\n",+ "# 2. Community detection\n",+ "communities = graph_analyzer.detect_communities(criminal_kg, method=\"louvain\")\n",+ "\n",+ "# 3. Graph metrics\n",+ "kg_metrics = graph_analyzer.compute_metrics(criminal_kg)\n",+ "\n",+ "# 4. Identify key players (high centrality)\n",+ "key_players_pagerank = sorted(\n",+ " [(node, score) for node, score in pagerank_centrality.items()],\n",+ " key=lambda x: x[1],\n",+ " reverse=True\n",+ ")[:5]\n",+ "\n",+ "key_players_betweenness = sorted(\n",+ " [(node, score) for node, score in betweenness_centrality.items()],\n",+ " key=lambda x: x[1],\n",+ " reverse=True\n",+ ")[:5]\n",+ "\n",+ "# Use graph store for analytics queries\n",+ "centrality_query = \"\"\"\n",+ " MATCH (p:Person)-[r]-()\n",+ " WITH p, count(r) as degree\n",+ " RETURN p.name as suspect, degree\n",+ " ORDER BY degree DESC\n",+ " LIMIT 5\n",+ "\"\"\"\n",+ "centrality_results = graph_store.execute_query(centrality_query)\n",+ "print(f\"✓ Graph store degree centrality query completed\")\n",+ "\n",+ "# Store analytics in agent memory\n",+ "agent_memory.store(\n",+ " f\"Graph analytics completed: {len(key_players_pagerank)} key players identified\",\n",+ " metadata={\n",+ " \"type\": \"graph_analytics\",\n",+ " \"key_players_count\": len(key_players_pagerank),\n",+ " \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0\n",+ " }\n",+ ")\n",+ "\n",+ "print(f\"✓ Performed comprehensive graph analytics\")\n",+ "print(f\" - PageRank centrality: {len(pagerank_centrality)} entities\")\n",+ "print(f\" - Betweenness centrality: {len(betweenness_centrality)} entities\")\n",+ "print(f\" - Closeness centrality: {len(closeness_centrality)} entities\")\n",+ "print(f\" - Eigenvector centrality: {len(eigenvector_centrality)} entities\")\n",+ "print(f\" - Communities detected: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\")\n",+ "print(f\"\\nTop Key Players (PageRank):\")\n",+ "for entity_id, score in key_players_pagerank:\n",+ " entity_name = next((e.get('name', '') for e in criminal_entities if e.get('id') == entity_id), 'Unknown')\n",+ " print(f\" - {entity_name} ({entity_id}): {score:.4f}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 9: Agent-Based Analysis Workflows\n",+ "\n",+ "Define and execute specialized agents for criminal network analysis using Pipeline coordination.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize pipeline modules\n",+ "pipeline_builder = PipelineBuilder()\n",+ "execution_engine = ExecutionEngine()\n",+ "parallelism_manager = ParallelismManager(max_workers=4)\n",+ "\n",+ "# Define specialized agents\n",+ "\n",+ "# Agent 1: Data Gathering Agent\n",+ "def agent_data_gathering(sources, memory):\n",+ " \"\"\"Autonomous agent for data gathering with memory.\"\"\"\n",+ " # Retrieve relevant context from memory\n",+ " context = memory.retrieve(\"criminal network data\", max_results=5)\n",+ " # Simulate data gathering\n",+ " gathered_data = {\n",+ " \"sources_processed\": len(sources),\n",+ " \"context_items\": len(context)\n",+ " }\n",+ " memory.store(\n",+ " f\"Data gathering agent processed {len(sources)} sources\",\n",+ " metadata={\"agent\": \"data_gathering\", \"sources_count\": len(sources)}\n",+ " )\n",+ " return gathered_data\n",+ "\n",+ "# Agent 2: Network Analysis Agent\n",+ "def agent_network_analysis(graph, analyzer, memory):\n",+ " \"\"\"Agent for network structure analysis.\"\"\"\n",+ " metrics = analyzer.compute_metrics(graph)\n",+ " centrality = analyzer.compute_centrality(graph, method=\"pagerank\")\n",+ " communities = analyzer.detect_communities(graph, method=\"louvain\")\n",+ " \n",+ " memory.store(\n",+ " f\"Network analysis completed: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0} communities detected\",\n",+ " metadata={\"agent\": \"network_analysis\", \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\n",+ " )\n",+ " return {\"metrics\": metrics, \"centrality\": centrality, \"communities\": communities}\n",+ "\n",+ "# Agent 3: Pattern Detection Agent\n",+ "def agent_pattern_detection(graph, inference_engine, memory):\n",+ " \"\"\"Agent for identifying suspicious patterns.\"\"\"\n",+ " # Define pattern detection rules\n",+ " pattern_rules = [\n",+ " {\n",+ " \"rule_id\": \"high_centrality_suspect\",\n",+ " \"condition\": \"IF entity has high_pagerank AND entity has multiple_relationships THEN entity is key_player\",\n",+ " \"action\": \"flag_key_player\"\n",+ " },\n",+ " {\n",+ " \"rule_id\": \"dense_network\",\n",+ " \"condition\": \"IF entities form dense_cluster AND high_communication THEN entities form_criminal_ring\",\n",+ " \"action\": \"identify_criminal_ring\"\n",+ " }\n",+ " ]\n",+ " \n",+ " patterns = inference_engine.infer(knowledge_graph=graph, rules=pattern_rules)\n",+ " memory.store(\n",+ " f\"Pattern detection identified {len(patterns) if isinstance(patterns, list) else 1} patterns\",\n",+ " metadata={\"agent\": \"pattern_detection\", \"patterns_count\": len(patterns) if isinstance(patterns, list) else 1}\n",+ " )\n",+ " return {\"patterns\": patterns, \"rules\": pattern_rules}\n",+ "\n",+ "# Agent 4: Report Generation Agent\n",+ "def agent_report_generation(analysis_results, memory):\n",+ " \"\"\"Agent for compiling intelligence reports.\"\"\"\n",+ " # Retrieve all relevant context\n",+ " context = memory.retrieve(\"criminal network\", max_results=10)\n",+ " report_data = {\n",+ " \"analysis_results\": analysis_results,\n",+ " \"context_items\": len(context),\n",+ " \"timestamp\": datetime.now().isoformat()\n",+ " }\n",+ " memory.store(\n",+ " \"Report generation agent compiled intelligence report\",\n",+ " metadata={\"agent\": \"report_generation\", \"context_items\": len(context)}\n",+ " )\n",+ " return report_data\n",+ "\n",+ "# Build parallel agent pipeline\n",+ "criminal_network_pipeline = pipeline_builder \\\n",+ " .add_step(\"data_gathering\", \"custom\", func=agent_data_gathering, args=([police_reports_file, court_records_file, surveillance_file], agent_memory)) \\\n",+ " .add_step(\"network_analysis\", \"custom\", func=agent_network_analysis, args=(criminal_kg, graph_analyzer, agent_memory)) \\\n",+ " .add_step(\"pattern_detection\", \"custom\", func=agent_pattern_detection, args=(criminal_kg, inference_engine, agent_memory)) \\\n",+ " .add_step(\"report_generation\", \"custom\", func=agent_report_generation, args=({\"key_players\": key_players_pagerank, \"communities\": communities}, agent_memory)) \\\n",+ " .build()\n",+ "\n",+ "# Execute pipeline with parallel execution\n",+ "pipeline_result = execution_engine.execute_pipeline(criminal_network_pipeline, parallel=True)\n",+ "\n",+ "print(\"✓ Orchestrated agent workflows using Semantica Pipeline\")\n",+ "print(f\" - Pipeline steps: {len(criminal_network_pipeline.steps)}\")\n",+ "print(f\" - Parallel execution: Enabled\")\n",+ "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n",+ "print(f\"✓ Agent memory contains {agent_memory.get_statistics().get('total_items', 0)} memory items\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize visualizers\n",+ "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",+ "analytics_visualizer = AnalyticsVisualizer()\n",+ "temporal_visualizer = TemporalVisualizer()\n",+ "\n",+ "# Visualize criminal network\n",+ "network_fig = kg_visualizer.visualize_network(\n",+ " criminal_kg,\n",+ " output=\"interactive\"\n",+ ")\n",+ "\n",+ "# Visualize communities\n",+ "communities_fig = kg_visualizer.visualize_communities(\n",+ " criminal_kg,\n",+ " communities,\n",+ " output=\"interactive\"\n",+ ")\n",+ "\n",+ "# Visualize centrality rankings\n",+ "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",+ " pagerank_centrality,\n",+ " centrality_type=\"pagerank\",\n",+ " top_n=10,\n",+ " output=\"interactive\"\n",+ ")\n",+ "\n",+ "# Visualize centrality comparison\n",+ "centrality_comparison = {\n",+ " \"pagerank\": pagerank_centrality,\n",+ " \"betweenness\": betweenness_centrality,\n",+ " \"closeness\": closeness_centrality\n",+ "}\n",+ "comparison_fig = analytics_visualizer.visualize_centrality_comparison(\n",+ " centrality_comparison,\n",+ " top_n=10,\n",+ " output=\"interactive\"\n",+ ")\n",+ "\n",+ "print(\"✓ Visualized criminal network and analytics\")\n",+ "print(\" - Network visualization: Interactive\")\n",+ "print(\" - Community visualization: Louvain communities\")\n",+ "print(\" - Centrality rankings: PageRank\")\n",+ "print(\" - Centrality comparison: Multi-measure comparison\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Step 11: Generate Intelligence Report\n",+ "\n",+ "Generate a comprehensive intelligence report on the criminal network structure.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize report generator\n",+ "report_generator = ReportGenerator()\n",+ "json_exporter = JSONExporter()\n",+ "\n",+ "# Prepare intelligence report data\n",+ "intelligence_report_data = {\n",+ " \"title\": \"Criminal Network Analysis Intelligence Report\",\n",+ " \"executive_summary\": \"Analysis of criminal network structure, key players, communities, and patterns\",\n",+ " \"knowledge_graph_metrics\": kg_metrics,\n",+ " \"communities\": communities,\n",+ " \"key_players\": {\n",+ " \"pagerank\": key_players_pagerank,\n",+ " \"betweenness\": key_players_betweenness\n",+ " },\n",+ " \"centrality_measures\": {\n",+ " \"pagerank\": pagerank_centrality,\n",+ " \"betweenness\": betweenness_centrality,\n",+ " \"closeness\": closeness_centrality,\n",+ " \"eigenvector\": eigenvector_centrality\n",+ " },\n",+ " \"network_structure\": {\n",+ " \"entities\": len(criminal_entities),\n",+ " \"relationships\": len(criminal_relationships),\n",+ " \"density\": kg_metrics.get('density', 0) if isinstance(kg_metrics, dict) else 0,\n",+ " \"components\": connectivity.get('num_components', 0)\n",+ " },\n",+ " \"agent_memory_stats\": agent_memory.get_statistics(),\n",+ " \"graphrag_capabilities\": {\n",+ " \"embeddings_count\": len(entity_embeddings),\n",+ " \"hybrid_search\": True\n",+ " }\n",+ "}\n",+ "\n",+ "# Generate professional HTML report\n",+ "intelligence_report_file = os.path.join(temp_dir, \"criminal_network_intelligence_report.html\")\n",+ "report_generator.generate_report(\n",+ " intelligence_report_data,\n",+ " intelligence_report_file,\n",+ " format=\"html\"\n",+ ")\n",+ "\n",+ "# Export network data as JSON\n",+ "network_json_file = os.path.join(temp_dir, \"criminal_network_data.json\")\n",+ "json_exporter.export(criminal_kg, network_json_file)\n",+ "\n",+ "print(\"✓ Generated professional intelligence report\")\n",+ "print(f\" - Intelligence report HTML: {intelligence_report_file}\")\n",+ "print(f\" - Network data JSON: {network_json_file}\")\n",+ "print(f\" - Report includes: Executive summary, metrics, key players, communities, agent memory stats\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Conclusion and Best Practices\n",+ "\n",+ "### Key Takeaways\n",+ "\n",+ "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for criminal network analysis\n",+ "2. **Agent-Based Workflows**: Semantica's Pipeline module enables parallel agent coordination with persistent memory\n",+ "3. **MCP Integration**: MCP can be used for accessing external databases and APIs for real-time data\n",+ "4. **Graph Analytics**: Semantica's GraphAnalyzer provides comprehensive algorithms (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",+ "5. **Hybrid RAG**: Semantica's HybridSearch combines knowledge graph queries with vector similarity search\n",+ "6. **Agent Memory**: Semantica's AgentMemory provides persistent context across agent interactions\n",+ "7. **Professional Reports**: Semantica's ReportGenerator creates professional HTML intelligence reports\n",+ "\n",+ "### Semantica-Specific Performance Considerations\n",+ "\n",+ "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient community detection and centrality calculations on large networks\n",+ "- **Parallel Execution**: Leverage Semantica's ParallelismManager for concurrent agent execution\n",+ "- **Vector Search**: Use Semantica's HybridSearch for efficient entity similarity search combined with graph queries\n",+ "- **Agent Memory**: Utilize Semantica's AgentMemory for persistent context across agent workflows\n",+ "\n",+ "### Deployment Recommendations Using Semantica\n",+ "\n",+ "1. **Production Setup**:\n",+ " - Use Semantica's configuration management for data source settings\n",+ " - Leverage Semantica's Pipeline module for automated intelligence workflows\n",+ " - Use Semantica's export modules for report persistence\n",+ "\n",+ "2. **Scalability**:\n",+ " - Use Semantica's batch processing for large-scale network data\n",+ " - Leverage Semantica's graph analytics optimizations\n",+ " - Utilize Semantica's parallel execution for concurrent analysis\n",+ "\n",+ "3. **Quality Assurance**:\n",+ " - Use Semantica's Deduplication modules for entity resolution\n",+ " - Leverage Semantica's ExplanationGenerator for report traceability\n",+ " - Utilize Semantica's quality modules for data validation\n",+ "\n",+ "### How Semantica's Architecture Benefits Criminal Network Analysis\n",+ "\n",+ "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms in one framework\n",+ "- **Unified Pipeline**: Semantica's Pipeline module orchestrates complex multi-agent workflows\n",+ "- **Agent Memory**: Semantica's AgentMemory enables persistent context for intelligent agents\n",+ "- **Hybrid RAG**: Semantica's HybridSearch combines graph and vector search for comprehensive intelligence queries\n",+ "- **Extensibility**: Semantica's registry system enables custom analysis methods\n",+ "- **Integration**: Semantica's unified framework simplifies integration with existing systems\n",+ "- **Performance**: Semantica's optimized algorithms handle large-scale network analysis efficiently\n",+ "- **Explainability**: Semantica's ExplanationGenerator provides traceable intelligence reports\n"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/docs/examples.md b/docs/examples.mdindex 16e65115..3534954b 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -188,6 +188,97 @@ print(f"Graph density: {analysis['density']}")print(f"Connected components: {analysis['components']}")```+### Example 9: Graph Store (Persistent Storage)++Store and query knowledge graphs in a persistent graph database:++```python+from semantica.graph_store import GraphStore++# Initialize with Neo4j+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password"+)+store.connect()++# Create nodes+apple = store.create_node(+ labels=["Company"],+ properties={"name": "Apple Inc.", "founded": 1976}+)++tim_cook = store.create_node(+ labels=["Person"],+ properties={"name": "Tim Cook", "title": "CEO"}+)++# Create relationship+store.create_relationship(+ start_node_id=tim_cook["id"],+ end_node_id=apple["id"],+ rel_type="CEO_OF",+ properties={"since": 2011}+)++# Query with Cypher+results = store.execute_query("""+ MATCH (p:Person)-[:CEO_OF]->(c:Company)+ RETURN p.name, c.name+""")++print(f"Query results: {results}")+store.close()+```++### Example 10: Using KuzuDB (Embedded)++For embedded graph storage without external dependencies:++```python+from semantica.graph_store import GraphStore++# KuzuDB - no server required+store = GraphStore(backend="kuzu", database_path="./my_graph_db")+store.connect()++# Store your knowledge graph+node = store.create_node(["Entity"], {"name": "Test"})+neighbors = store.get_neighbors(node["id"], depth=2)+stats = store.get_stats()++print(f"Graph stats: {stats}")+store.close()+```++### Example 11: FalkorDB for Real-Time Applications++Ultra-fast graph queries for LLM applications:++```python+from semantica.graph_store import GraphStore++# FalkorDB - Redis-based, ultra-fast+store = GraphStore(+ backend="falkordb",+ host="localhost",+ port=6379,+ graph_name="knowledge_graph"+)+store.connect()++# Fast queries for RAG applications+results = store.execute_query("""+ MATCH (n)-[r]->(m)+ WHERE n.name CONTAINS $query+ RETURN n, r, m LIMIT 10+""", parameters={"query": "AI"})++store.close()+```+## Use Case Examples### Research Paper Analysisdiff --git a/docs/getting-started.md b/docs/getting-started.mdindex db7e96ed..37e894d9 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -104,6 +104,12 @@ embedding:knowledge_graph:backend: networkx # or neo4j, arangodbtemporal: true++graph_store:+ backend: neo4j # or kuzu, falkordb+ neo4j_uri: bolt://localhost:7687+ neo4j_user: neo4j+ neo4j_password: password```---diff --git a/docs/modules.md b/docs/modules.mdindex b91e0088..305d8f52 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -22,6 +22,7 @@ graph TDsubgraph Storage [Storage Layer]KG --> VS[Vector Store]KG --> TS[Triple Store]+ KG --> GS[Graph Store]endsubgraph Output [Output & Analysis]@@ -40,7 +41,7 @@ graph TD## 📦 Core Modules-Semantica is organized into 12 core modules. Below is a detailed breakdown of each.+Semantica is organized into 13 core modules. Below is a detailed breakdown of each.### 1. Ingest Module**Purpose**: Ingest data from various sources into a unified format.@@ -270,7 +271,64 @@ hybrid_search = HybridSearch(vector_store)results = hybrid_search.search(query, top_k=10)```-### 8. Reasoning Module+### 8. Graph Store Module+**Purpose**: Store and query property graphs with multiple backend support.++The `graph_store` module provides integration with property graph databases like Neo4j, KuzuDB, and FalkorDB for storing and querying knowledge graphs.++- **Components**:+ - `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+ - `QueryEngine`: Cypher query execution+ - `GraphAnalytics`: Graph algorithms and analytics++```mermaid+classDiagram+ class GraphStore {+ +create_node(labels, properties)+ +create_relationship(start, end, type)+ +execute_query(cypher)+ +shortest_path(start, end)+ }+ class Neo4jAdapter {+ +connect()+ +execute_query()+ +create_index()+ }+ class FalkorDBAdapter {+ +select_graph()+ +query()+ }+ GraphStore *-- Neo4jAdapter+ GraphStore *-- FalkorDBAdapter+```++```python+from semantica.graph_store import GraphStore, create_node, create_relationship++# Using GraphStore class+store = GraphStore(backend="neo4j", uri="bolt://localhost:7687")+store.connect()++# Create nodes+alice = store.create_node(["Person"], {"name": "Alice", "age": 30})+bob = store.create_node(["Person"], {"name": "Bob", "age": 25})++# Create relationship+store.create_relationship(alice["id"], bob["id"], "KNOWS", {"since": 2020})++# Query+results = store.execute_query("MATCH (p:Person) RETURN p.name")++# Or use convenience functions+node = create_node(labels=["Entity"], properties={"name": "Test"})+```++### 9. Reasoning Module**Purpose**: Perform logical inference and reasoning.Goes beyond simple retrieval to infer new facts and validate existing knowledge using logical rules.@@ -291,7 +349,7 @@ rule_manager = RuleManager()new_facts = inference_engine.forward_chain(kg, rule_manager)```-### 9. Ontology Module+### 10. Ontology Module**Purpose**: Generate and manage ontologies.Defines the schema and structure of your knowledge domain, ensuring consistency and enabling interoperability.@@ -310,7 +368,7 @@ generator = OntologyGenerator()ontology = generator.generate_from_graph(kg)```-### 10. Export Module+### 11. Export Module**Purpose**: Export data in various formats.Allows you to take your knowledge graph and data out of Semantica for use in other tools.@@ -330,7 +388,7 @@ json_exporter = JSONExporter()json_exporter.export(kg, "output.json")```-### 11. Visualization Module+### 12. Visualization Module**Purpose**: Visualize knowledge graphs and analytics.Provides tools to visually explore your data, making it easier to understand complex relationships.@@ -349,7 +407,7 @@ visualizer = KGVisualizer()visualizer.visualize(kg)```-### 12. Pipeline Module+### 13. Pipeline Module**Purpose**: Build and execute processing pipelines.Orchestrates the entire flow, connecting modules together into robust, executable workflows.diff --git a/docs/reference/graph_store.md b/docs/reference/graph_store.mdnew file mode 100644index 00000000..5aa71998--- /dev/null+++ b/docs/reference/graph_store.md@@ -0,0 +1,550 @@+# Graph Store Module++> **Store and query property graphs with support for Neo4j, KuzuDB, and FalkorDB backends.**++---++## 🎯 Overview++<div class="grid cards" markdown>++- :material-graph:{ .lg .middle } **Property Graphs**++ ---++ Store nodes and relationships with properties using industry-standard graph databases++- :material-database-search:{ .lg .middle } **Cypher Queries**++ ---++ Full Cypher/OpenCypher query language support for powerful graph queries++- :material-lightning-bolt:{ .lg .middle } **Multiple Backends**++ ---++ Neo4j, KuzuDB, and FalkorDB support for different use cases++- :material-transit-connection:{ .lg .middle } **Graph Traversal**++ ---++ Efficient path finding and neighborhood traversal algorithms++- :material-chart-bubble:{ .lg .middle } **Graph Analytics**++ ---++ Centrality, shortest path, and community detection algorithms++- :material-cog-transfer:{ .lg .middle } **Batch Operations**++ ---++ Efficient bulk insert with transaction support and progress tracking++</div>++!!! tip "Choosing the Right Backend"+ - **Neo4j**: Production-grade, full-featured, best for enterprise applications+ - **KuzuDB**: Embedded database, excellent for analytics, no server required+ - **FalkorDB**: Ultra-fast, Redis-based, ideal for LLM applications and real-time queries++---++## ⚙️ Algorithms Used++### Graph Storage+- **Adjacency List**: Node-relationship storage pattern+- **Property Storage**: Key-value property management on nodes/relationships+- **Index Structures**: B-tree and hash indexes for fast lookups+- **Sparse Matrices**: FalkorDB uses sparse matrix representation for adjacency++### Query Processing+- **Pattern Matching**: Cypher MATCH clause processing+- **Join Algorithms**: Hash join, merge join for multi-pattern queries+- **Index Utilization**: Automatic index selection for optimal performance+- **Query Planning**: Cost-based query optimization++### Graph Analytics+- **Shortest Path**: Dijkstra's algorithm, BFS-based shortest path+- **Centrality**: Degree centrality, betweenness centrality, PageRank+- **Community Detection**: Label propagation, Louvain algorithm+- **Traversal**: BFS/DFS graph traversal with depth control++---++## Main Classes++### GraphStore++The main interface for working with property graph databases.++**Methods:**++| Method | Description | Algorithm |+|--------|-------------|-----------|+| `create_node(labels, properties)` | Create a node | Index insertion |+| `create_nodes(nodes)` | Batch create nodes | Bulk insertion with transactions |+| `get_node(node_id)` | Get node by ID | Index lookup |+| `get_nodes(labels, properties, limit)` | Query nodes | Pattern matching |+| `update_node(node_id, properties, merge)` | Update node | Property merge/replace |+| `delete_node(node_id, detach)` | Delete node | Cascade or isolated delete |+| `create_relationship(start, end, type, props)` | Create relationship | Edge insertion |+| `get_relationships(node_id, type, direction)` | Query relationships | Pattern matching |+| `execute_query(cypher, params)` | Execute Cypher query | Full query processing |+| `shortest_path(start, end, type, max_depth)` | Find shortest path | Dijkstra/BFS |+| `get_neighbors(node_id, depth)` | Get neighborhood | BFS traversal |++**Supported Backends:**++| Backend | Query Language | Best For | Deployment |+|---------|---------------|----------|------------|+| **Neo4j** | Cypher | Enterprise, full features | Server/Cloud |+| **KuzuDB** | Cypher | Analytics, embedded | Embedded |+| **FalkorDB** | OpenCypher | LLM apps, real-time | Redis-based |++**Example:**++```python+from semantica.graph_store import GraphStore++# Initialize with Neo4j backend+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password"+)++# Connect to database+store.connect()++# Create nodes+alice = store.create_node(+ labels=["Person"],+ properties={"name": "Alice", "age": 30}+)++bob = store.create_node(+ labels=["Person"],+ properties={"name": "Bob", "age": 25}+)++# Create relationship+store.create_relationship(+ start_node_id=alice["id"],+ end_node_id=bob["id"],+ rel_type="KNOWS",+ properties={"since": 2020}+)++# Query the graph+results = store.execute_query(+ "MATCH (p:Person) WHERE p.age > $min_age RETURN p.name, p.age",+ parameters={"min_age": 20}+)++for record in results["records"]:+ print(f"{record['p.name']} is {record['p.age']} years old")++# Find shortest path+path = store.shortest_path(alice["id"], bob["id"])+print(f"Path length: {path['length']}")++# Close connection+store.close()+```++---++### Neo4jAdapter++Direct Neo4j database adapter for advanced operations.++**Features:**+- Full Cypher query support+- ACID transactions with rollback+- Multi-database support+- Index and constraint management+- GDS (Graph Data Science) library integration++**Example:**++```python+from semantica.graph_store import Neo4jAdapter++adapter = Neo4jAdapter(+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password",+ database="neo4j"+)++adapter.connect()++# Create index for faster queries+adapter.create_index("Person", "name", index_type="btree")++# Execute complex query+results = adapter.execute_query("""+ MATCH path = shortestPath((a:Person)-[*]-(b:Person))+ WHERE a.name = 'Alice' AND b.name = 'Bob'+ RETURN path, length(path) as distance+""")++# Get statistics+stats = adapter.get_stats()+print(f"Nodes: {stats['node_count']}, Relationships: {stats['relationship_count']}")+```++---++### KuzuAdapter++Embedded graph database for high-performance analytics.++**Features:**+- No server required (embedded)+- Schema-based node and relationship tables+- High-performance analytical queries+- COPY FROM for bulk data loading+- Persistent and in-memory modes++**Example:**++```python+from semantica.graph_store import KuzuAdapter++adapter = KuzuAdapter(+ database_path="./my_graph_db",+ buffer_pool_size=268435456, # 256MB+ max_num_threads=4+)++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"}+)++# Create nodes+adapter.create_node("Person", {"name": "Alice", "age": 30})++# Bulk load from CSV+adapter.bulk_load_nodes("Person", "people.csv", header=True)+```++---++### FalkorDBAdapter++Ultra-fast Redis-based graph database for real-time applications.++**Features:**+- Sparse matrix representation+- Linear algebra query optimization+- Multi-tenant graph support+- OpenCypher query language+- Redis-based persistence++**Example:**++```python+from semantica.graph_store import FalkorDBAdapter++adapter = FalkorDBAdapter(+ host="localhost",+ port=6379,+ graph_name="knowledge_graph"+)++adapter.connect()++# Select/create a graph+adapter.select_graph("MotoGP")++# Create nodes and relationships+rider = adapter.create_node(+ labels=["Rider"],+ properties={"name": "Valentino Rossi"}+)++team = adapter.create_node(+ labels=["Team"],+ properties={"name": "Yamaha"}+)++adapter.create_relationship(+ rider["id"],+ team["id"],+ "rides",+ properties={"since": 2004}+)++# Query+results = adapter.execute_query("""+ MATCH (r:Rider)-[:rides]->(t:Team)+ WHERE t.name = 'Yamaha'+ RETURN r.name+""")++# List all graphs+graphs = adapter.list_graphs()+```++---++## Convenience Functions++Quick access to graph operations without managing store instances:++```python+from semantica.graph_store import (+ # Node operations+ create_node,+ create_nodes,+ get_nodes,+ update_node,+ delete_node,++ # Relationship operations+ create_relationship,+ create_relationships,+ get_relationships,+ delete_relationship,++ # Query operations+ execute_query,++ # Analytics operations+ shortest_path,+ get_neighbors,+ run_analytics+)++# Create nodes using convenience functions+alice = create_node(labels=["Person"], properties={"name": "Alice"})+bob = create_node(labels=["Person"], properties={"name": "Bob"})++# Create relationship+rel = create_relationship(+ start_id=alice["id"],+ end_id=bob["id"],+ rel_type="KNOWS"+)++# Query+results = execute_query("MATCH (n:Person) RETURN n.name LIMIT 10")++# Analytics+path = shortest_path(alice["id"], bob["id"], max_depth=5)+neighbors = get_neighbors(alice["id"], depth=2)+```++---++## Configuration++### Environment Variables++```bash+# General settings+export GRAPH_STORE_DEFAULT_BACKEND=neo4j+export GRAPH_STORE_BATCH_SIZE=1000+export GRAPH_STORE_TIMEOUT=30++# Neo4j settings+export GRAPH_STORE_NEO4J_URI=bolt://localhost:7687+export GRAPH_STORE_NEO4J_USER=neo4j+export GRAPH_STORE_NEO4J_PASSWORD=password+export GRAPH_STORE_NEO4J_DATABASE=neo4j++# KuzuDB settings+export GRAPH_STORE_KUZU_DATABASE_PATH=./kuzu_db+export GRAPH_STORE_KUZU_BUFFER_POOL_SIZE=268435456++# FalkorDB settings+export GRAPH_STORE_FALKORDB_HOST=localhost+export GRAPH_STORE_FALKORDB_PORT=6379+export GRAPH_STORE_FALKORDB_GRAPH_NAME=default+```++### YAML Configuration++```yaml+# config.yaml - Graph Store Configuration++graph_store:+ backend: neo4j # neo4j, kuzu, falkordb+ batch_size: 1000+ timeout: 30++ neo4j:+ uri: bolt://localhost:7687+ user: neo4j+ password: password+ database: neo4j+ encrypted: false++ kuzu:+ database_path: ./kuzu_db+ buffer_pool_size: 268435456+ max_num_threads: 4++ falkordb:+ host: localhost+ port: 6379+ password: null+ graph_name: default+```++---++## 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** | Full ACID | ACID | ACID |+| **Performance** | Excellent | Best for analytics | Ultra-fast |+| **Use Case** | Enterprise | Analytics/Embedded | Real-time/LLM |+| **Clustering** | Yes | No | Via Redis |+| **Graph Algorithms** | GDS Library | Built-in | Built-in |++---++## Docker Quick Start++### FalkorDB++```bash+docker run -p 6379:6379 -p 3000:3000 -it --rm \+ -v ./data:/var/lib/falkordb/data \+ falkordb/falkordb+```++Then open http://localhost:3000 for the web UI.++### Neo4j++```bash+docker run -p 7474:7474 -p 7687:7687 \+ -e NEO4J_AUTH=neo4j/password \+ neo4j:latest+```++Then open http://localhost:7474 for Neo4j Browser.++---++## Performance Tips++### Indexing++```python+# Create indexes for frequently queried properties+store.create_index("Person", "name", index_type="btree")+store.create_index("Document", "content", index_type="fulltext")+```++### Batch Operations++```python+# Use batch operations for bulk inserts+nodes = [+ {"labels": ["Person"], "properties": {"name": f"Person_{i}"}}+ for i in range(1000)+]+store.create_nodes(nodes)+```++### Query Optimization++```python+# Use parameterized queries+results = store.execute_query(+ "MATCH (p:Person) WHERE p.age > $min_age RETURN p",+ parameters={"min_age": 25}+)++# Limit results+results = store.get_nodes(labels=["Person"], limit=100)+```++---++## Integration Examples++### Knowledge Graph for RAG++```python+from semantica.graph_store import GraphStore+from semantica.embeddings import EmbeddingGenerator++# Create knowledge graph+store = GraphStore(backend="falkordb")+store.connect()++# Add entities and relationships+doc = store.create_node(["Document"], {"title": "AI Paper", "content": "..."})+concept = store.create_node(["Concept"], {"name": "Machine Learning"})+store.create_relationship(doc["id"], concept["id"], "MENTIONS")++# Query for retrieval+results = store.execute_query("""+ MATCH (d:Document)-[:MENTIONS]->(c:Concept)+ WHERE c.name CONTAINS 'Learning'+ RETURN d.title, d.content+""")+```++### Social Network Analysis++```python+from semantica.graph_store import GraphStore++store = GraphStore(backend="neo4j")+store.connect()++# Find influential users (high degree centrality)+results = store.execute_query("""+ MATCH (u:User)-[r:FOLLOWS]-()+ WITH u, count(r) as connections+ ORDER BY connections DESC+ RETURN u.name, connections+ LIMIT 10+""")++# Find communities+from semantica.graph_store import run_analytics+components = run_analytics("connected_components", labels=["User"])+```++---++## See Also++- [Vector Store Module](vector_store.md) - Store and search vector embeddings+- [Triple Store Module](triple_store.md) - RDF triple storage and SPARQL queries+- [Knowledge Graph Module](kg.md) - Build and analyze knowledge graphs+- [Visualization Module](visualization.md) - Visualize graph structures+diff --git a/mkdocs.yml b/mkdocs.ymlindex ac40ce79..e5b7ddeb 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -108,6 +108,7 @@ nav:- Embeddings: reference/embeddings.md- Evals: reference/evals.md- Export: reference/export.md+ - Graph Store: reference/graph_store.md- Ingest: reference/ingest.md- Knowledge Graph: reference/kg.md- Normalize: reference/normalize.mddiff --git a/pyproject.toml b/pyproject.tomlindex bc1547db..81c7b323 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,7 +36,8 @@ classifiers = [keywords = ["semantic-layer", "knowledge-engineering", "nlp", "knowledge-graph","embeddings", "entity-extraction", "relationship-extraction", "rdf",- "ontology", "semantic-analysis", "ai", "machine-learning"+ "ontology", "semantic-analysis", "ai", "machine-learning",+ "graph-database", "property-graph", "neo4j", "falkordb", "kuzu"]dependencies = ["numpy>=1.21.0",@@ -183,7 +184,18 @@ split-topic = [split-all = ["semantica[split-tiktoken,split-community,split-topic]"]-+graph-neo4j = [+ "neo4j>=5.0.0"+]+graph-kuzu = [+ "kuzu>=0.4.0"+]+graph-falkordb = [+ "falkordb>=1.0.0"+]+graph-all = [+ "semantica[graph-neo4j,graph-kuzu,graph-falkordb]"+][project.scripts]semantica = "semantica.cli:main"diff --git a/semantica/__init__.py b/semantica/__init__.pyindex 42435360..618a44ac 100644--- a/semantica/__init__.py+++ b/semantica/__init__.py@@ -104,6 +104,7 @@ class _SemanticaModules:self._export = Noneself._vector_store = Noneself._triple_store = None+ self._graph_store = Noneself._ontology = Noneself._evals = None@@ -191,6 +192,13 @@ class _SemanticaModules:self._triple_store = _ModuleProxy("triple_store")return self._triple_store+ @property+ def graph_store(self):+ """Access graph store module."""+ if self._graph_store is None:+ self._graph_store = _ModuleProxy("graph_store")+ return self._graph_store+@propertydef ontology(self):"""Access ontology module."""@@ -328,6 +336,7 @@ def __getattr__(name: str):"export","vector_store","triple_store",+ "graph_store","ontology","evals",]:diff --git a/semantica/graph_store/__init__.py b/semantica/graph_store/__init__.pynew file mode 100644index 00000000..cd796cfa--- /dev/null+++ b/semantica/graph_store/__init__.py@@ -0,0 +1,181 @@+"""+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.++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+ - Store Selection: Default store resolution, store ID lookup, store validation++Node and Relationship Operations:+ - Node Creation: Single node insertion, batch node insertion, property validation, label management, adapter delegation+ - Node Retrieval: Pattern matching (label/property filtering), Cypher query construction, result extraction, node reconstruction+ - Node Update: Property update, label modification, atomic update operations, conflict detection+ - Node Deletion: Node matching, cascade deletion (optional), deletion operation delegation, result verification+ - Relationship Creation: Single relationship insertion, batch insertion, property validation, type management+ - Relationship Retrieval: Pattern matching, path queries, traversal queries+ - Relationship Update: Property update, type modification+ - Relationship Deletion: Relationship matching, deletion operation delegation++Graph Query Execution:+ - Cypher Query: Full Cypher query language support for Neo4j and FalkorDB (OpenCypher)+ - Pattern Matching: Node and relationship pattern matching, variable binding, path matching+ - Graph Traversal: BFS/DFS traversal, shortest path algorithms, path finding+ - Aggregation: COUNT, SUM, AVG, MIN, MAX operations, GROUP BY support+ - Query Optimization: Query caching, execution plan analysis, index utilization++Graph Analytics:+ - Centrality Algorithms: Degree centrality, betweenness centrality, PageRank, closeness centrality+ - Community Detection: Label propagation, Louvain modularity, connected components+ - Path Algorithms: Shortest path, all shortest paths, Dijkstra, A* pathfinding+ - Similarity: Node similarity, Jaccard similarity, cosine similarity++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:+ - Batch Processing: Chunking algorithm (fixed-size batch creation), batch size optimization, memory management for large datasets+ - Transaction Management: ACID transaction support, batch commits, rollback on failure+ - Progress Tracking: Load progress calculation, elapsed time tracking, throughput calculation++Key Features:+ - Multi-backend property graph support (Neo4j, KuzuDB, FalkorDB)+ - Full Cypher/OpenCypher query language support+ - Node and relationship CRUD operations+ - Graph traversal and path finding+ - Graph analytics and algorithms+ - Bulk data loading with progress tracking+ - Transaction support with rollback+ - Index and constraint management+ - Method registry for extensibility+ - Configuration management with environment variables and config files++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+ - QueryEngine: Cypher query execution and optimization+ - GraphAnalytics: Graph algorithms and analytics++Convenience Functions:+ - create_node: Create node wrapper+ - create_relationship: Create relationship wrapper+ - get_nodes: Get nodes wrapper+ - get_relationships: Get relationships wrapper+ - update_node: Update node wrapper+ - delete_node: Delete node wrapper+ - execute_query: Execute Cypher query wrapper+ - run_analytics: Run graph analytics wrapper+ - get_graph_store_method: Get graph store method by task and name+ - list_available_methods: List registered graph store methods++Example Usage:+ >>> from semantica.graph_store import GraphStore, create_node, create_relationship, execute_query+ >>> # Using convenience functions+ >>> node_id = create_node(labels=["Person"], properties={"name": "Alice", "age": 30})+ >>> rel_id = create_relationship(start_id=node1_id, end_id=node2_id, type="KNOWS", properties={"since": 2020})+ >>> results = execute_query("MATCH (p:Person) WHERE p.age > 25 RETURN p.name")+ >>> # Using classes directly+ >>> store = GraphStore(backend="neo4j", uri="bolt://localhost:7687")+ >>> node_id = store.create_node(labels=["Person"], properties={"name": "Bob"})+ >>> results = store.execute_query("MATCH (n) RETURN n LIMIT 10")++Author: Semantica Contributors+License: MIT+"""++from .config import GraphStoreConfig, graph_store_config+from .falkordb_adapter import (+ FalkorDBAdapter,+ FalkorDBClient,+ FalkorDBGraph,+ FalkorDBQuery,+)+from .graph_store import (+ GraphAnalytics,+ GraphManager,+ GraphStore,+ NodeManager,+ QueryEngine,+ RelationshipManager,+)+from .kuzu_adapter import KuzuAdapter, KuzuConnection, KuzuDatabase, KuzuQuery+from .methods import (+ create_node,+ create_nodes,+ create_relationship,+ create_relationships,+ delete_node,+ delete_relationship,+ execute_query,+ get_graph_store_method,+ get_neighbors,+ get_nodes,+ get_relationships,+ list_available_methods,+ run_analytics,+ shortest_path,+ update_node,+ update_relationship,+)+from .neo4j_adapter import Neo4jAdapter, Neo4jDriver, Neo4jSession, Neo4jTransaction+from .registry import MethodRegistry, method_registry++__all__ = [+ # Core graph store+ "GraphStore",+ "GraphManager",+ "NodeManager",+ "RelationshipManager",+ "QueryEngine",+ "GraphAnalytics",+ # Neo4j+ "Neo4jAdapter",+ "Neo4jDriver",+ "Neo4jSession",+ "Neo4jTransaction",+ # KuzuDB+ "KuzuAdapter",+ "KuzuDatabase",+ "KuzuConnection",+ "KuzuQuery",+ # FalkorDB+ "FalkorDBAdapter",+ "FalkorDBClient",+ "FalkorDBGraph",+ "FalkorDBQuery",+ # Convenience functions+ "create_node",+ "create_nodes",+ "create_relationship",+ "create_relationships",+ "get_nodes",+ "get_relationships",+ "get_neighbors",+ "update_node",+ "update_relationship",+ "delete_node",+ "delete_relationship",+ "execute_query",+ "shortest_path",+ "run_analytics",+ "get_graph_store_method",+ "list_available_methods",+ # Configuration and registry+ "GraphStoreConfig",+ "graph_store_config",+ "MethodRegistry",+ "method_registry",+]+diff --git a/semantica/graph_store/config.py b/semantica/graph_store/config.pynew file mode 100644index 00000000..550816b3--- /dev/null+++ b/semantica/graph_store/config.py@@ -0,0 +1,304 @@+"""+Configuration Management Module for Graph Store++This module provides centralized configuration management for graph store operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: GRAPH_STORE_DEFAULT_BACKEND, GRAPH_STORE_NEO4J_URI, GRAPH_STORE_FALKORDB_HOST, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting graph store configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for graph store parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - GraphStoreConfig: Main configuration manager class for graph store module++Example Usage:+ >>> from semantica.graph_store.config import graph_store_config+ >>> default_backend = graph_store_config.get("default_backend", default="neo4j")+ >>> graph_store_config.set("default_backend", "falkordb")+ >>> method_config = graph_store_config.get_method_config("create_node")+"""++import os+from pathlib import Path+from typing import Any, Dict, Optional++from ..utils.logging import get_logger+++class GraphStoreConfig:+ """Configuration manager for graph store module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ """+ Initialize configuration manager.++ Args:+ config_file: Optional path to configuration file (YAML, JSON, or TOML)+ """+ self.logger = get_logger("graph_store_config")+ self.config_file = config_file+ self._config: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict[str, Any]] = {}++ # Load configuration+ self._load_config()++ def _load_config(self) -> None:+ """Load configuration from file, environment variables, and defaults."""+ # Load from config file if provided+ if self.config_file:+ self._load_from_file(self.config_file)++ # Load from environment variables+ self._load_from_env()++ # Set defaults+ self._set_defaults()++ def _load_from_file(self, file_path: str) -> None:+ """Load configuration from file."""+ file_path = Path(file_path)+ if not file_path.exists():+ self.logger.warning(f"Config file not found: {file_path}")+ return++ try:+ if file_path.suffix in [".yaml", ".yml"]:+ import yaml++ with open(file_path, "r") as f:+ config_data = yaml.safe_load(f)+ if config_data and "graph_store" in config_data:+ self._config.update(config_data["graph_store"])+ elif file_path.suffix == ".json":+ import json++ with open(file_path, "r") as f:+ config_data = json.load(f)+ if config_data and "graph_store" in config_data:+ self._config.update(config_data["graph_store"])+ elif file_path.suffix == ".toml":+ import tomli++ with open(file_path, "rb") as f:+ config_data = tomli.load(f)+ if config_data and "graph_store" in config_data:+ self._config.update(config_data["graph_store"])+ except Exception as e:+ self.logger.error(f"Failed to load config file: {e}")++ def _load_from_env(self) -> None:+ """Load configuration from environment variables."""+ env_mappings = {+ # General settings+ "GRAPH_STORE_DEFAULT_BACKEND": "default_backend",+ "GRAPH_STORE_BATCH_SIZE": "batch_size",+ "GRAPH_STORE_TIMEOUT": "timeout",+ "GRAPH_STORE_MAX_RETRIES": "max_retries",+ # Neo4j settings+ "GRAPH_STORE_NEO4J_URI": "neo4j_uri",+ "GRAPH_STORE_NEO4J_USER": "neo4j_user",+ "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",+ "GRAPH_STORE_FALKORDB_PASSWORD": "falkordb_password",+ "GRAPH_STORE_FALKORDB_GRAPH_NAME": "falkordb_graph_name",+ }++ for env_var, config_key in env_mappings.items():+ value = os.getenv(env_var)+ if value is not None:+ # Convert string values to appropriate types+ if config_key in [+ "batch_size",+ "timeout",+ "max_retries",+ "falkordb_port",+ "kuzu_buffer_pool_size",+ "kuzu_max_num_threads",+ ]:+ try:+ self._config[config_key] = int(value)+ except ValueError:+ self.logger.warning(+ f"Invalid integer value for {env_var}: {value}"+ )+ elif config_key in ["neo4j_encrypted"]:+ self._config[config_key] = value.lower() in [+ "true",+ "1",+ "yes",+ "on",+ ]+ else:+ self._config[config_key] = value++ def _set_defaults(self) -> None:+ """Set default configuration values."""+ defaults = {+ # General defaults+ "default_backend": "neo4j",+ "batch_size": 1000,+ "timeout": 30,+ "max_retries": 3,+ # Neo4j defaults+ "neo4j_uri": "bolt://localhost:7687",+ "neo4j_user": "neo4j",+ "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,+ "falkordb_password": None,+ "falkordb_graph_name": "default",+ }++ for key, default_value in defaults.items():+ if key not in self._config:+ self._config[key] = default_value++ def get(self, key: str, default: Any = None) -> Any:+ """+ Get configuration value.++ Args:+ key: Configuration key+ default: Default value if key not found++ Returns:+ Configuration value or default+ """+ return self._config.get(key, default)++ def set(self, key: str, value: Any) -> None:+ """+ Set configuration value.++ Args:+ key: Configuration key+ value: Configuration value+ """+ self._config[key] = value++ def update(self, config: Dict[str, Any]) -> None:+ """+ Update configuration with dictionary.++ Args:+ config: Configuration dictionary+ """+ self._config.update(config)++ def get_method_config(self, method_name: str) -> Dict[str, Any]:+ """+ Get method-specific configuration.++ Args:+ method_name: Method name++ Returns:+ Method configuration dictionary+ """+ return self._method_configs.get(method_name, {}).copy()++ def set_method_config(self, method_name: str, config: Dict[str, Any]) -> None:+ """+ Set method-specific configuration.++ Args:+ method_name: Method name+ config: Method configuration dictionary+ """+ self._method_configs[method_name] = config.copy()++ def get_all(self) -> Dict[str, Any]:+ """+ Get all configuration.++ Returns:+ Complete configuration dictionary+ """+ return self._config.copy()++ def get_neo4j_config(self) -> Dict[str, Any]:+ """+ Get Neo4j-specific configuration.++ Returns:+ Neo4j configuration dictionary+ """+ return {+ "uri": self._config.get("neo4j_uri"),+ "user": self._config.get("neo4j_user"),+ "password": self._config.get("neo4j_password"),+ "database": self._config.get("neo4j_database"),+ "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.++ Returns:+ FalkorDB configuration dictionary+ """+ return {+ "host": self._config.get("falkordb_host"),+ "port": self._config.get("falkordb_port"),+ "password": self._config.get("falkordb_password"),+ "graph_name": self._config.get("falkordb_graph_name"),+ }++ def reset(self) -> None:+ """Reset configuration to defaults."""+ self._config.clear()+ self._method_configs.clear()+ self._set_defaults()+++# Global configuration instance+graph_store_config = GraphStoreConfig()+diff --git a/semantica/graph_store/falkordb_adapter.py b/semantica/graph_store/falkordb_adapter.pynew file mode 100644index 00000000..71ebb7cd--- /dev/null+++ b/semantica/graph_store/falkordb_adapter.py@@ -0,0 +1,1011 @@+"""+FalkorDB Adapter Module++This module provides FalkorDB integration for ultra-fast property graph storage and+OpenCypher querying in the Semantica framework. FalkorDB is a high-performance+knowledge graph database built on Redis, using sparse matrices for adjacency+representation and linear algebra for query execution.++Key Features:+ - Ultra-fast graph operations using sparse matrices+ - Full OpenCypher query language support+ - Redis-based storage (requires Redis server or Docker)+ - Multi-tenant graph support+ - Linear algebra based querying+ - Node and relationship CRUD operations+ - Graph algorithms and analytics+ - Batch operations with progress tracking+ - Optional dependency handling++Main Classes:+ - FalkorDBAdapter: Main FalkorDB adapter for graph operations+ - FalkorDBClient: FalkorDB client wrapper+ - FalkorDBGraph: Graph wrapper with operations+ - FalkorDBQuery: Query execution wrapper++Example Usage:+ >>> from semantica.graph_store import FalkorDBAdapter+ >>> adapter = FalkorDBAdapter(host="localhost", port=6379)+ >>> adapter.connect()+ >>> graph = adapter.select_graph("MotoGP")+ >>> adapter.create_node(["Rider"], {"name": "Valentino Rossi"})+ >>> results = adapter.execute_query("MATCH (r:Rider) RETURN r.name")+ >>> adapter.close()++Author: Semantica Contributors+License: MIT+"""++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 FalkorDB import+try:+ from falkordb import FalkorDB++ FALKORDB_AVAILABLE = True+except ImportError:+ FALKORDB_AVAILABLE = False+ FalkorDB = None+++class FalkorDBClient:+ """FalkorDB client wrapper."""++ def __init__(self, client: Any):+ """Initialize FalkorDB client wrapper."""+ self.client = client+ self.logger = get_logger("falkordb_client")++ def select_graph(self, graph_name: str) -> "FalkorDBGraph":+ """+ Select or create a graph.++ Args:+ graph_name: Name of the graph++ Returns:+ FalkorDBGraph instance+ """+ if not FALKORDB_AVAILABLE:+ raise ProcessingError("FalkorDB not available")++ try:+ graph = self.client.select_graph(graph_name)+ return FalkorDBGraph(graph, graph_name)+ except Exception as e:+ raise ProcessingError(f"Failed to select graph: {str(e)}")++ def list_graphs(self) -> List[str]:+ """List all available graphs."""+ if not FALKORDB_AVAILABLE:+ raise ProcessingError("FalkorDB not available")++ try:+ return self.client.list_graphs()+ except Exception as e:+ raise ProcessingError(f"Failed to list graphs: {str(e)}")+++class FalkorDBGraph:+ """FalkorDB graph wrapper."""++ def __init__(self, graph: Any, name: str):+ """Initialize FalkorDB graph wrapper."""+ self.graph = graph+ self.name = name+ self.logger = get_logger("falkordb_graph")++ def query(self, query: str, params: Optional[Dict[str, Any]] = None) -> "FalkorDBQuery":+ """+ Execute an OpenCypher query.++ Args:+ query: OpenCypher query string+ params: Query parameters++ Returns:+ FalkorDBQuery result wrapper+ """+ if not FALKORDB_AVAILABLE:+ raise ProcessingError("FalkorDB not available")++ try:+ if params:+ result = self.graph.query(query, params)+ else:+ result = self.graph.query(query)+ return FalkorDBQuery(result)+ except Exception as e:+ raise ProcessingError(f"Query execution failed: {str(e)}")++ def delete(self) -> bool:+ """Delete the graph."""+ if not FALKORDB_AVAILABLE:+ raise ProcessingError("FalkorDB not available")++ try:+ self.graph.delete()+ return True+ except Exception as e:+ raise ProcessingError(f"Failed to delete graph: {str(e)}")+++class FalkorDBQuery:+ """FalkorDB query result wrapper."""++ def __init__(self, result: Any):+ """Initialize FalkorDB query result wrapper."""+ self.result = result+ self.logger = get_logger("falkordb_query")++ @property+ def result_set(self) -> List[List[Any]]:+ """Get the result set as a list of rows."""+ if self.result:+ return self.result.result_set+ return []++ @property+ def header(self) -> List[str]:+ """Get column headers."""+ if self.result and hasattr(self.result, "header"):+ return self.result.header+ return []++ @property+ def statistics(self) -> Dict[str, Any]:+ """Get query statistics."""+ if self.result:+ stats = {}+ if hasattr(self.result, "nodes_created"):+ stats["nodes_created"] = self.result.nodes_created+ if hasattr(self.result, "relationships_created"):+ stats["relationships_created"] = self.result.relationships_created+ if hasattr(self.result, "nodes_deleted"):+ stats["nodes_deleted"] = self.result.nodes_deleted+ if hasattr(self.result, "relationships_deleted"):+ stats["relationships_deleted"] = self.result.relationships_deleted+ if hasattr(self.result, "properties_set"):+ stats["properties_set"] = self.result.properties_set+ if hasattr(self.result, "run_time_ms"):+ stats["run_time_ms"] = self.result.run_time_ms+ return stats+ return {}+++class FalkorDBAdapter:+ """+ FalkorDB adapter for ultra-fast property graph storage and OpenCypher querying.++ • FalkorDB connection and authentication+ • Multi-graph support+ • Node and relationship CRUD operations+ • OpenCypher query execution+ • Sparse matrix based graph representation+ • Linear algebra query optimization+ • Performance optimization+ • Error handling and recovery+ """++ def __init__(+ self,+ host: Optional[str] = None,+ port: Optional[int] = None,+ password: Optional[str] = None,+ graph_name: Optional[str] = None,+ **config,+ ):+ """+ Initialize FalkorDB adapter.++ Args:+ host: FalkorDB/Redis host+ port: FalkorDB/Redis port+ password: Redis password (if required)+ graph_name: Default graph name+ **config: Additional configuration options+ """+ self.logger = get_logger("falkordb_adapter")+ self.config = config+ self.progress_tracker = get_progress_tracker()++ self.host = host or config.get("host", "localhost")+ self.port = port or config.get("port", 6379)+ self.password = password or config.get("password")+ self.default_graph_name = graph_name or config.get("graph_name", "default")++ self._client: Optional[FalkorDBClient] = None+ self._graph: Optional[FalkorDBGraph] = None++ # Check FalkorDB availability+ if not FALKORDB_AVAILABLE:+ self.logger.warning(+ "FalkorDB not available. Install with: pip install falkordb"+ )++ def connect(+ self,+ host: Optional[str] = None,+ port: Optional[int] = None,+ password: Optional[str] = None,+ **options,+ ) -> bool:+ """+ Connect to FalkorDB server.++ Args:+ host: FalkorDB/Redis host+ port: FalkorDB/Redis port+ password: Redis password+ **options: Connection options++ Returns:+ True if connected successfully+ """+ if not FALKORDB_AVAILABLE:+ raise ProcessingError(+ "FalkorDB is not available. Install it with: pip install falkordb"+ )++ host = host or self.host+ port = port or self.port+ password = password or self.password++ try:+ if password:+ db = FalkorDB(host=host, port=port, password=password)+ else:+ db = FalkorDB(host=host, port=port)++ self._client = FalkorDBClient(db)+ self.logger.info(f"Connected to FalkorDB at {host}:{port}")+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to connect to FalkorDB: {str(e)}")++ def close(self) -> None:+ """Close connection to FalkorDB."""+ self._graph = None+ self._client = None+ self.logger.info("Disconnected from FalkorDB")++ def _ensure_client(self) -> FalkorDBClient:+ """Ensure client is connected."""+ if self._client is None:+ self.connect()+ return self._client++ def select_graph(self, graph_name: Optional[str] = None) -> FalkorDBGraph:+ """+ Select or create a graph.++ Args:+ graph_name: Name of the graph++ Returns:+ FalkorDBGraph instance+ """+ client = self._ensure_client()+ graph_name = graph_name or self.default_graph_name+ self._graph = client.select_graph(graph_name)+ return self._graph++ def _ensure_graph(self) -> FalkorDBGraph:+ """Ensure a graph is selected."""+ if self._graph is None:+ self.select_graph()+ return self._graph++ def create_node(+ self,+ labels: List[str],+ properties: Dict[str, Any],+ **options,+ ) -> Dict[str, Any]:+ """+ Create a node in the graph.++ Args:+ labels: Node labels+ properties: Node properties+ **options: Additional options++ Returns:+ Created node information+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="FalkorDBAdapter",+ message=f"Creating node with labels {labels}",+ )++ try:+ graph = self._ensure_graph()++ label_str = ":".join(labels)++ # Build property string for Cypher+ props_str = ", ".join(+ f"{k}: ${k}" for k in properties.keys()+ )++ query = f"CREATE (n:{label_str} {{{props_str}}}) RETURN id(n) as id, n"+ result = graph.query(query, properties)++ node_data = {+ "labels": labels,+ "properties": properties,+ }++ if result.result_set and len(result.result_set) > 0:+ row = result.result_set[0]+ if len(row) > 0:+ node_data["id"] = row[0]++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Created node with labels {labels}",+ )+ 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,+ nodes: List[Dict[str, Any]],+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Create multiple nodes in batch.++ Args:+ nodes: List of node dictionaries with 'labels' and 'properties'+ **options: Additional options++ Returns:+ List of created node information+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="FalkorDBAdapter",+ message=f"Creating {len(nodes)} nodes in batch",+ )++ try:+ graph = self._ensure_graph()+ created_nodes = []++ for node in nodes:+ labels = node.get("labels", [])+ properties = node.get("properties", {})++ label_str = ":".join(labels) if labels else "Node"+ props_str = ", ".join(+ f"{k}: ${k}" for k in properties.keys()+ )++ query = f"CREATE (n:{label_str} {{{props_str}}}) RETURN id(n) as id"+ result = graph.query(query, properties)++ node_data = {+ "labels": labels,+ "properties": properties,+ }++ if result.result_set and len(result.result_set) > 0:+ node_data["id"] = result.result_set[0][0]++ created_nodes.append(node_data)++ 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,+ labels: Optional[List[str]] = None,+ properties: Optional[Dict[str, Any]] = None,+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get nodes matching criteria.++ Args:+ labels: Filter by labels+ properties: Filter by properties+ limit: Maximum number of nodes+ **options: Additional options++ Returns:+ List of matching nodes+ """+ try:+ graph = self._ensure_graph()++ # Build query+ if labels:+ label_str = ":".join(labels)+ query = f"MATCH (n:{label_str})"+ else:+ query = "MATCH (n)"++ # Add property filters+ if properties:+ conditions = []+ for key in properties.keys():+ conditions.append(f"n.{key} = ${key}")+ query += " WHERE " + " AND ".join(conditions)++ query += f" RETURN id(n) as id, n, labels(n) as labels LIMIT {limit}"++ result = graph.query(query, properties or {})++ nodes = []+ for row in result.result_set:+ if len(row) >= 2:+ node_data = {+ "id": row[0],+ "properties": dict(row[1]) if hasattr(row[1], "__iter__") else {},+ }+ if len(row) >= 3:+ node_data["labels"] = row[2] if isinstance(row[2], list) else []+ nodes.append(node_data)++ return nodes++ except Exception as e:+ raise ProcessingError(f"Failed to get nodes: {str(e)}")++ def update_node(+ self,+ node_id: int,+ properties: Dict[str, Any],+ merge: bool = True,+ **options,+ ) -> Dict[str, Any]:+ """+ Update a node's properties.++ Args:+ node_id: Node ID+ properties: Properties to update+ merge: If True, merge properties; if False, replace+ **options: Additional options++ Returns:+ Updated node information+ """+ try:+ graph = self._ensure_graph()++ # Build SET clause+ set_parts = []+ for key in properties.keys():+ set_parts.append(f"n.{key} = ${key}")++ if merge:+ query = f"MATCH (n) WHERE id(n) = $node_id SET {', '.join(set_parts)} RETURN id(n) as id, n, labels(n) as labels"+ else:+ query = f"MATCH (n) WHERE id(n) = $node_id SET n = $props RETURN id(n) as id, n, labels(n) as labels"++ params = {"node_id": node_id, **properties}+ if not merge:+ params["props"] = properties++ result = graph.query(query, params)++ if result.result_set and len(result.result_set) > 0:+ row = result.result_set[0]+ return {+ "id": row[0],+ "properties": dict(row[1]) if len(row) > 1 else properties,+ "labels": row[2] if len(row) > 2 else [],+ }+ else:+ raise ProcessingError(f"Node with ID {node_id} not found")++ except Exception as e:+ raise ProcessingError(f"Failed to update node: {str(e)}")++ def delete_node(+ self,+ node_id: int,+ detach: bool = True,+ **options,+ ) -> bool:+ """+ Delete a node.++ Args:+ node_id: Node ID+ detach: If True, delete relationships as well+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ try:+ graph = self._ensure_graph()++ if detach:+ query = "MATCH (n) WHERE id(n) = $node_id DETACH DELETE n"+ else:+ query = "MATCH (n) WHERE id(n) = $node_id DELETE n"++ graph.query(query, {"node_id": node_id})+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to delete node: {str(e)}")++ 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]:+ """+ Create a relationship between two nodes.++ Args:+ start_node_id: Start node ID+ end_node_id: End node ID+ rel_type: Relationship type+ properties: Relationship properties+ **options: Additional options++ Returns:+ Created relationship information+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="FalkorDBAdapter",+ message=f"Creating relationship [{rel_type}]",+ )++ try:+ graph = self._ensure_graph()+ properties = properties or {}++ # Build property string+ if properties:+ props_str = ", ".join(f"{k}: ${k}" for k in properties.keys())+ props_str = f" {{{props_str}}}"+ else:+ props_str = ""++ query = f"""+ MATCH (a), (b)+ WHERE id(a) = $start_id AND id(b) = $end_id+ CREATE (a)-[r:{rel_type}{props_str}]->(b)+ RETURN id(r) as id, type(r) as type+ """++ params = {"start_id": start_node_id, "end_id": end_node_id, **properties}+ result = graph.query(query, params)++ rel_data = {+ "type": rel_type,+ "start_node_id": start_node_id,+ "end_node_id": end_node_id,+ "properties": properties,+ }++ if result.result_set and len(result.result_set) > 0:+ row = result.result_set[0]+ rel_data["id"] = row[0]++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Created relationship [{rel_type}]",+ )+ 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,+ node_id: Optional[int] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get relationships matching criteria.++ Args:+ node_id: Filter by node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ limit: Maximum number of relationships+ **options: Additional options++ Returns:+ List of matching relationships+ """+ try:+ graph = self._ensure_graph()+ type_filter = f":{rel_type}" if rel_type else ""++ if node_id is not None:+ if direction == "out":+ query = f"""+ MATCH (a)-[r{type_filter}]->(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(a) as start_id, id(b) as end_id, r+ LIMIT {limit}+ """+ elif direction == "in":+ query = f"""+ MATCH (a)<-[r{type_filter}]-(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(b) as start_id, id(a) as end_id, r+ LIMIT {limit}+ """+ else:+ query = f"""+ MATCH (a)-[r{type_filter}]-(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(startNode(r)) as start_id, id(endNode(r)) as end_id, r+ LIMIT {limit}+ """+ result = graph.query(query, {"node_id": node_id})+ else:+ query = f"""+ MATCH (a)-[r{type_filter}]->(b)+ RETURN id(r) as id, type(r) as type, id(a) as start_id, id(b) as end_id, r+ LIMIT {limit}+ """+ result = graph.query(query)++ relationships = []+ for row in result.result_set:+ if len(row) >= 4:+ rel_data = {+ "id": row[0],+ "type": row[1],+ "start_node_id": row[2],+ "end_node_id": row[3],+ }+ if len(row) > 4:+ rel_data["properties"] = dict(row[4]) if hasattr(row[4], "__iter__") else {}+ relationships.append(rel_data)++ return relationships++ except Exception as e:+ raise ProcessingError(f"Failed to get relationships: {str(e)}")++ def delete_relationship(+ self,+ rel_id: int,+ **options,+ ) -> bool:+ """+ Delete a relationship.++ Args:+ rel_id: Relationship ID+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ try:+ graph = self._ensure_graph()+ query = "MATCH ()-[r]->() WHERE id(r) = $rel_id DELETE r"+ graph.query(query, {"rel_id": rel_id})+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to delete relationship: {str(e)}")++ def execute_query(+ self,+ query: str,+ parameters: Optional[Dict[str, Any]] = None,+ **options,+ ) -> Dict[str, Any]:+ """+ Execute an OpenCypher query.++ Args:+ query: OpenCypher query string+ parameters: Query parameters+ **options: Additional options++ Returns:+ Query results+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="FalkorDBAdapter",+ message="Executing OpenCypher query",+ )++ try:+ graph = self._ensure_graph()+ result = graph.query(query, parameters or {})++ records = []+ for row in result.result_set:+ # Convert row to dictionary or list+ records.append(list(row))++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Query returned {len(records)} records",+ )++ return {+ "success": True,+ "records": records,+ "header": result.header,+ "statistics": result.statistics,+ "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 get_neighbors(+ self,+ node_id: int,+ rel_type: Optional[str] = None,+ direction: str = "both",+ depth: int = 1,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get neighboring nodes.++ Args:+ node_id: Starting node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ depth: Traversal depth+ **options: Additional options++ Returns:+ List of neighboring nodes+ """+ try:+ graph = self._ensure_graph()+ type_filter = f":{rel_type}" if rel_type else ""++ if direction == "out":+ pattern = f"-[r{type_filter}*1..{depth}]->"+ elif direction == "in":+ pattern = f"<-[r{type_filter}*1..{depth}]-"+ else:+ pattern = f"-[r{type_filter}*1..{depth}]-"++ query = f"""+ MATCH (start){pattern}(neighbor)+ WHERE id(start) = $node_id+ RETURN DISTINCT id(neighbor) as id, neighbor, labels(neighbor) as labels+ """++ result = graph.query(query, {"node_id": node_id})++ neighbors = []+ for row in result.result_set:+ if len(row) >= 2:+ neighbors.append({+ "id": row[0],+ "properties": dict(row[1]) if hasattr(row[1], "__iter__") else {},+ "labels": row[2] if len(row) > 2 else [],+ })++ return neighbors++ except Exception as e:+ raise ProcessingError(f"Failed to get neighbors: {str(e)}")++ 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]]:+ """+ Find shortest path between two nodes.++ Args:+ start_node_id: Starting node ID+ end_node_id: Ending node ID+ rel_type: Filter by relationship type+ max_depth: Maximum path length+ **options: Additional options++ Returns:+ Shortest path information or None if not found+ """+ try:+ graph = self._ensure_graph()+ type_filter = f":{rel_type}" if rel_type else ""++ query = f"""+ MATCH path = shortestPath((start)-[r{type_filter}*..{max_depth}]-(end))+ WHERE id(start) = $start_id AND id(end) = $end_id+ RETURN path, length(path) as length+ """++ result = graph.query(query, {+ "start_id": start_node_id,+ "end_id": end_node_id,+ })++ if result.result_set and len(result.result_set) > 0:+ row = result.result_set[0]+ path = row[0]++ # Extract path information+ nodes = []+ relationships = []++ if hasattr(path, "nodes"):+ for node in path.nodes():+ nodes.append({+ "id": node.id if hasattr(node, "id") else None,+ "labels": list(node.labels) if hasattr(node, "labels") else [],+ "properties": dict(node.properties) if hasattr(node, "properties") else {},+ })++ if hasattr(path, "edges"):+ for rel in path.edges():+ relationships.append({+ "id": rel.id if hasattr(rel, "id") else None,+ "type": rel.relation if hasattr(rel, "relation") else None,+ "properties": dict(rel.properties) if hasattr(rel, "properties") else {},+ })++ return {+ "length": row[1] if len(row) > 1 else len(relationships),+ "nodes": nodes,+ "relationships": relationships,+ }++ return None++ except Exception as e:+ raise ProcessingError(f"Failed to find shortest path: {str(e)}")++ def create_index(+ self,+ label: str,+ property_name: str,+ index_type: str = "range",+ **options,+ ) -> bool:+ """+ Create an index on a property.++ Args:+ label: Node label+ property_name: Property to index+ index_type: Index type (range, fulltext)+ **options: Additional options++ Returns:+ True if index created successfully+ """+ try:+ graph = self._ensure_graph()++ if index_type == "fulltext":+ query = f"CALL db.idx.fulltext.createNodeIndex('{label}', '{property_name}')"+ else:+ query = f"CREATE INDEX FOR (n:{label}) ON (n.{property_name})"++ graph.query(query)+ self.logger.info(f"Created {index_type} index on {label}.{property_name}")+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to create index: {str(e)}")++ def list_graphs(self) -> List[str]:+ """List all available graphs."""+ client = self._ensure_client()+ return client.list_graphs()++ def delete_graph(self, graph_name: Optional[str] = None) -> bool:+ """+ Delete a graph.++ Args:+ graph_name: Graph name (uses default if not provided)++ Returns:+ True if deleted successfully+ """+ try:+ client = self._ensure_client()+ graph = client.select_graph(graph_name or self.default_graph_name)+ graph.delete()+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to delete graph: {str(e)}")++ def get_stats(self) -> Dict[str, Any]:+ """Get graph statistics."""+ try:+ graph = self._ensure_graph()++ stats = {+ "graph_name": self._graph.name if self._graph else "unknown",+ }++ # Node count+ result = graph.query("MATCH (n) RETURN count(n) as count")+ if result.result_set and len(result.result_set) > 0:+ stats["node_count"] = result.result_set[0][0]++ # Relationship count+ result = graph.query("MATCH ()-[r]->() RETURN count(r) as count")+ if result.result_set and len(result.result_set) > 0:+ stats["relationship_count"] = result.result_set[0][0]++ # Label counts+ result = graph.query("""+ MATCH (n)+ UNWIND labels(n) as label+ RETURN label, count(*) as count+ ORDER BY count DESC+ """)+ stats["label_counts"] = {+ row[0]: row[1] for row in result.result_set+ }++ # Relationship type counts+ result = graph.query("""+ MATCH ()-[r]->()+ RETURN type(r) as type, count(*) as count+ ORDER BY count DESC+ """)+ stats["relationship_type_counts"] = {+ row[0]: row[1] for row in result.result_set+ }++ 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/semantica/graph_store/graph_store.py b/semantica/graph_store/graph_store.pynew file mode 100644index 00000000..4b6f28ae--- /dev/null+++ b/semantica/graph_store/graph_store.py@@ -0,0 +1,747 @@+"""+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).++Key Features:+ - Unified graph store interface+ - Multi-backend support+ - Node and relationship management+ - Query execution engine+ - Graph analytics and algorithms+ - Transaction support+ - Configuration management++Main Classes:+ - GraphStore: Main graph store interface+ - GraphManager: Graph store management and operations+ - NodeManager: Node CRUD operations+ - RelationshipManager: Relationship CRUD operations+ - QueryEngine: Query execution and optimization+ - GraphAnalytics: Graph algorithms and analytics++Example Usage:+ >>> from semantica.graph_store import GraphStore+ >>> store = GraphStore(backend="neo4j", uri="bolt://localhost:7687")+ >>> store.create_node(labels=["Person"], properties={"name": "Alice"})+ >>> results = store.execute_query("MATCH (n) RETURN n LIMIT 10")++Author: Semantica Contributors+License: MIT+"""++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+from .config import graph_store_config+++class NodeManager:+ """Manager for node CRUD operations."""++ def __init__(self, adapter: Any):+ """+ Initialize node manager.++ Args:+ adapter: Graph database adapter instance+ """+ self.adapter = adapter+ self.logger = get_logger("node_manager")++ def create(+ self,+ labels: List[str],+ properties: Dict[str, Any],+ **options,+ ) -> Dict[str, Any]:+ """+ Create a node.++ Args:+ labels: Node labels+ properties: Node properties+ **options: Additional options++ Returns:+ Created node information+ """+ return self.adapter.create_node(labels, properties, **options)++ def create_batch(+ self,+ nodes: List[Dict[str, Any]],+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Create multiple nodes in batch.++ Args:+ nodes: List of node dictionaries with 'labels' and 'properties'+ **options: Additional options++ Returns:+ List of created node information+ """+ return self.adapter.create_nodes(nodes, **options)++ def get(+ self,+ node_id: Union[int, str] = None,+ labels: Optional[List[str]] = None,+ properties: Optional[Dict[str, Any]] = None,+ limit: int = 100,+ **options,+ ) -> Union[Dict[str, Any], List[Dict[str, Any]]]:+ """+ Get node(s).++ Args:+ node_id: Specific node ID to get+ labels: Filter by labels+ properties: Filter by properties+ limit: Maximum number of nodes+ **options: Additional options++ Returns:+ Node or list of nodes+ """+ if node_id is not None:+ return self.adapter.get_node(node_id, **options)+ return self.adapter.get_nodes(labels, properties, limit, **options)++ def update(+ self,+ node_id: Union[int, str],+ properties: Dict[str, Any],+ merge: bool = True,+ **options,+ ) -> Dict[str, Any]:+ """+ Update a node.++ Args:+ node_id: Node ID+ properties: Properties to update+ merge: If True, merge; if False, replace+ **options: Additional options++ Returns:+ Updated node information+ """+ return self.adapter.update_node(node_id, properties, merge, **options)++ def delete(+ self,+ node_id: Union[int, str],+ detach: bool = True,+ **options,+ ) -> bool:+ """+ Delete a node.++ Args:+ node_id: Node ID+ detach: If True, delete relationships as well+ **options: Additional options++ Returns:+ True if deleted+ """+ return self.adapter.delete_node(node_id, detach, **options)+++class RelationshipManager:+ """Manager for relationship CRUD operations."""++ def __init__(self, adapter: Any):+ """+ Initialize relationship manager.++ Args:+ adapter: Graph database adapter instance+ """+ self.adapter = adapter+ self.logger = get_logger("relationship_manager")++ def create(+ self,+ start_node_id: Union[int, str],+ end_node_id: Union[int, str],+ rel_type: str,+ properties: Optional[Dict[str, Any]] = None,+ **options,+ ) -> Dict[str, Any]:+ """+ Create a relationship.++ Args:+ start_node_id: Start node ID+ end_node_id: End node ID+ rel_type: Relationship type+ properties: Relationship properties+ **options: Additional options++ Returns:+ Created relationship information+ """+ return self.adapter.create_relationship(+ start_node_id, end_node_id, rel_type, properties, **options+ )++ def get(+ self,+ node_id: Optional[Union[int, str]] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get relationships.++ Args:+ node_id: Filter by node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ limit: Maximum number of relationships+ **options: Additional options++ Returns:+ List of relationships+ """+ return self.adapter.get_relationships(node_id, rel_type, direction, limit, **options)++ def delete(+ self,+ rel_id: Union[int, str],+ **options,+ ) -> bool:+ """+ Delete a relationship.++ Args:+ rel_id: Relationship ID+ **options: Additional options++ Returns:+ True if deleted+ """+ return self.adapter.delete_relationship(rel_id, **options)+++class QueryEngine:+ """Engine for query execution and optimization."""++ def __init__(self, adapter: Any):+ """+ Initialize query engine.++ Args:+ adapter: Graph database adapter instance+ """+ self.adapter = adapter+ self.logger = get_logger("query_engine")+ self._cache: Dict[str, Any] = {}+ self._cache_enabled = True++ def execute(+ self,+ query: str,+ parameters: Optional[Dict[str, Any]] = None,+ use_cache: bool = False,+ **options,+ ) -> Dict[str, Any]:+ """+ Execute a Cypher/OpenCypher query.++ Args:+ query: Query string+ parameters: Query parameters+ use_cache: Whether to use query caching+ **options: Additional options++ Returns:+ Query results+ """+ # Check cache+ if use_cache and self._cache_enabled:+ cache_key = self._generate_cache_key(query, parameters)+ if cache_key in self._cache:+ return self._cache[cache_key]++ # Execute query+ result = self.adapter.execute_query(query, parameters, **options)++ # Cache result+ if use_cache and self._cache_enabled:+ self._cache[cache_key] = result++ return result++ def _generate_cache_key(+ self,+ query: str,+ parameters: Optional[Dict[str, Any]],+ ) -> str:+ """Generate cache key for query."""+ import hashlib+ key_str = f"{query}:{str(parameters)}"+ return hashlib.md5(key_str.encode()).hexdigest()++ def clear_cache(self) -> None:+ """Clear query cache."""+ self._cache.clear()++ def enable_cache(self) -> None:+ """Enable query caching."""+ self._cache_enabled = True++ def disable_cache(self) -> None:+ """Disable query caching."""+ self._cache_enabled = False+++class GraphAnalytics:+ """Graph analytics and algorithms."""++ def __init__(self, adapter: Any):+ """+ Initialize graph analytics.++ Args:+ adapter: Graph database adapter instance+ """+ self.adapter = adapter+ self.logger = get_logger("graph_analytics")++ def shortest_path(+ self,+ start_node_id: Union[int, str],+ end_node_id: Union[int, str],+ rel_type: Optional[str] = None,+ max_depth: int = 10,+ **options,+ ) -> Optional[Dict[str, Any]]:+ """+ Find shortest path between two nodes.++ Args:+ start_node_id: Starting node ID+ end_node_id: Ending node ID+ rel_type: Filter by relationship type+ max_depth: Maximum path length+ **options: Additional options++ Returns:+ Path information or None+ """+ return self.adapter.shortest_path(start_node_id, end_node_id, rel_type, max_depth, **options)++ def get_neighbors(+ self,+ node_id: Union[int, str],+ rel_type: Optional[str] = None,+ direction: str = "both",+ depth: int = 1,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get neighboring nodes.++ Args:+ node_id: Starting node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ depth: Traversal depth+ **options: Additional options++ Returns:+ List of neighboring nodes+ """+ return self.adapter.get_neighbors(node_id, rel_type, direction, depth, **options)++ def degree_centrality(+ self,+ labels: Optional[List[str]] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Calculate degree centrality for nodes.++ Args:+ labels: Filter by node labels+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ **options: Additional options++ Returns:+ List of nodes with centrality scores+ """+ # Build query based on direction+ if labels:+ label_str = ":".join(labels)+ match = f"MATCH (n:{label_str})"+ else:+ match = "MATCH (n)"++ type_filter = f":{rel_type}" if rel_type else ""++ if direction == "out":+ query = f"""+ {match}+ OPTIONAL MATCH (n)-[r{type_filter}]->()+ WITH n, count(r) as degree+ RETURN id(n) as id, n, degree+ ORDER BY degree DESC+ """+ elif direction == "in":+ query = f"""+ {match}+ OPTIONAL MATCH (n)<-[r{type_filter}]-()+ WITH n, count(r) as degree+ RETURN id(n) as id, n, degree+ ORDER BY degree DESC+ """+ else:+ query = f"""+ {match}+ OPTIONAL MATCH (n)-[r{type_filter}]-()+ WITH n, count(r) as degree+ RETURN id(n) as id, n, degree+ ORDER BY degree DESC+ """++ result = self.adapter.execute_query(query)+ return result.get("records", [])++ def connected_components(+ self,+ labels: Optional[List[str]] = None,+ **options,+ ) -> Dict[str, Any]:+ """+ Find connected components in the graph.++ Note: Full connected components requires GDS library for Neo4j+ or custom implementation. This provides a basic approximation.++ Args:+ labels: Filter by node labels+ **options: Additional options++ Returns:+ Component information+ """+ self.logger.warning(+ "Full connected components algorithm requires graph data science extensions. "+ "Returning basic component approximation."+ )++ # Get all nodes and their connections+ if labels:+ label_str = ":".join(labels)+ query = f"MATCH (n:{label_str})-[r]-(m) RETURN DISTINCT id(n) as node_id, id(m) as connected_id"+ else:+ query = "MATCH (n)-[r]-(m) RETURN DISTINCT id(n) as node_id, id(m) as connected_id"++ result = self.adapter.execute_query(query)++ return {+ "message": "Connected components approximation",+ "connections": result.get("records", []),+ }+++class GraphManager:+ """Manager for graph store operations."""++ def __init__(self, adapter: Any):+ """+ Initialize graph manager.++ Args:+ adapter: Graph database adapter instance+ """+ self.adapter = adapter+ self.logger = get_logger("graph_manager")+ self.nodes = NodeManager(adapter)+ self.relationships = RelationshipManager(adapter)+ self.query_engine = QueryEngine(adapter)+ self.analytics = GraphAnalytics(adapter)++ def get_stats(self) -> Dict[str, Any]:+ """Get graph statistics."""+ return self.adapter.get_stats()++ def create_index(+ self,+ label: str,+ property_name: str,+ index_type: str = "btree",+ **options,+ ) -> bool:+ """+ Create an index.++ Args:+ label: Node label+ property_name: Property to index+ index_type: Index type+ **options: Additional options++ Returns:+ True if created+ """+ return self.adapter.create_index(label, property_name, index_type, **options)+++class GraphStore:+ """+ Main graph store interface.++ Provides a unified interface for working with property graph databases,+ supporting Neo4j, KuzuDB, and FalkorDB backends.+ """++ def __init__(+ self,+ backend: Optional[str] = None,+ **config,+ ):+ """+ Initialize graph store.++ Args:+ backend: Backend type ("neo4j", "kuzu", "falkordb")+ **config: Backend-specific configuration+ """+ self.logger = get_logger("graph_store")+ self.progress_tracker = get_progress_tracker()++ # Determine backend+ self.backend = backend or config.get("backend") or graph_store_config.get("default_backend", "neo4j")+ self.config = config++ # Initialize adapter+ self._adapter = None+ self._manager = None+ self._initialize_adapter()++ def _initialize_adapter(self) -> None:+ """Initialize the appropriate adapter based on backend."""+ if self.backend == "neo4j":+ from .neo4j_adapter import Neo4jAdapter+ neo4j_config = graph_store_config.get_neo4j_config()+ 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()+ falkordb_config.update(self.config)+ self._adapter = FalkorDBAdapter(**falkordb_config)++ else:+ raise ValidationError(f"Unknown backend: {self.backend}")++ self._manager = GraphManager(self._adapter)++ def connect(self, **options) -> bool:+ """+ Connect to the graph database.++ Args:+ **options: Connection options++ Returns:+ True if connected+ """+ return self._adapter.connect(**options)++ def close(self) -> None:+ """Close connection to the graph database."""+ if self._adapter:+ self._adapter.close()++ def __enter__(self):+ """Context manager entry."""+ self.connect()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit."""+ self.close()++ # Node operations+ def create_node(+ self,+ labels: List[str],+ properties: Dict[str, Any],+ **options,+ ) -> Dict[str, Any]:+ """Create a node."""+ return self._manager.nodes.create(labels, properties, **options)++ def create_nodes(+ self,+ nodes: List[Dict[str, Any]],+ **options,+ ) -> List[Dict[str, Any]]:+ """Create multiple nodes."""+ return self._manager.nodes.create_batch(nodes, **options)++ def get_node(+ self,+ node_id: Union[int, str],+ **options,+ ) -> Optional[Dict[str, Any]]:+ """Get a node by ID."""+ return self._manager.nodes.get(node_id=node_id, **options)++ def get_nodes(+ self,+ labels: Optional[List[str]] = None,+ properties: Optional[Dict[str, Any]] = None,+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """Get nodes matching criteria."""+ return self._manager.nodes.get(labels=labels, properties=properties, limit=limit, **options)++ def update_node(+ self,+ node_id: Union[int, str],+ properties: Dict[str, Any],+ merge: bool = True,+ **options,+ ) -> Dict[str, Any]:+ """Update a node."""+ return self._manager.nodes.update(node_id, properties, merge, **options)++ def delete_node(+ self,+ node_id: Union[int, str],+ detach: bool = True,+ **options,+ ) -> bool:+ """Delete a node."""+ return self._manager.nodes.delete(node_id, detach, **options)++ # Relationship operations+ def create_relationship(+ self,+ start_node_id: Union[int, str],+ end_node_id: Union[int, str],+ rel_type: str,+ properties: Optional[Dict[str, Any]] = None,+ **options,+ ) -> Dict[str, Any]:+ """Create a relationship."""+ return self._manager.relationships.create(+ start_node_id, end_node_id, rel_type, properties, **options+ )++ def get_relationships(+ self,+ node_id: Optional[Union[int, str]] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """Get relationships."""+ return self._manager.relationships.get(node_id, rel_type, direction, limit, **options)++ def delete_relationship(+ self,+ rel_id: Union[int, str],+ **options,+ ) -> bool:+ """Delete a relationship."""+ return self._manager.relationships.delete(rel_id, **options)++ # Query operations+ def execute_query(+ self,+ query: str,+ parameters: Optional[Dict[str, Any]] = None,+ **options,+ ) -> Dict[str, Any]:+ """Execute a Cypher query."""+ return self._manager.query_engine.execute(query, parameters, **options)++ # Analytics operations+ def shortest_path(+ self,+ start_node_id: Union[int, str],+ end_node_id: Union[int, str],+ rel_type: Optional[str] = None,+ max_depth: int = 10,+ **options,+ ) -> Optional[Dict[str, Any]]:+ """Find shortest path between nodes."""+ return self._manager.analytics.shortest_path(+ start_node_id, end_node_id, rel_type, max_depth, **options+ )++ def get_neighbors(+ self,+ node_id: Union[int, str],+ rel_type: Optional[str] = None,+ direction: str = "both",+ depth: int = 1,+ **options,+ ) -> List[Dict[str, Any]]:+ """Get neighboring nodes."""+ return self._manager.analytics.get_neighbors(+ node_id, rel_type, direction, depth, **options+ )++ # Management operations+ def get_stats(self) -> Dict[str, Any]:+ """Get graph statistics."""+ return self._manager.get_stats()++ def create_index(+ self,+ label: str,+ property_name: str,+ index_type: str = "btree",+ **options,+ ) -> bool:+ """Create an index."""+ return self._manager.create_index(label, property_name, index_type, **options)++ @property+ def nodes(self) -> NodeManager:+ """Get node manager."""+ return self._manager.nodes++ @property+ def relationships(self) -> RelationshipManager:+ """Get relationship manager."""+ return self._manager.relationships++ @property+ def query_engine(self) -> QueryEngine:+ """Get query engine."""+ return self._manager.query_engine++ @property+ def analytics(self) -> GraphAnalytics:+ """Get analytics engine."""+ return self._manager.analytics+diff --git a/semantica/graph_store/graph_store_usage.md b/semantica/graph_store/graph_store_usage.mdnew file mode 100644index 00000000..7be7fa84--- /dev/null+++ b/semantica/graph_store/graph_store_usage.md@@ -0,0 +1,611 @@+# 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**.++## Table of Contents++1. [Installation](#installation)+2. [Quick Start](#quick-start)+3. [Backend Configuration](#backend-configuration)+4. [Node Operations](#node-operations)+5. [Relationship Operations](#relationship-operations)+6. [Query Execution](#query-execution)+7. [Graph Analytics](#graph-analytics)+8. [Convenience Functions](#convenience-functions)+9. [Advanced Usage](#advanced-usage)++## Installation++### Core Installation++```bash+pip install semantica+```++### Backend-Specific Dependencies++```bash+# Neo4j+pip install neo4j++# KuzuDB+pip install kuzu++# FalkorDB+pip install falkordb+```++### Docker Setup for FalkorDB++```bash+docker run -p 6379:6379 -p 3000:3000 -it --rm -v ./data:/var/lib/falkordb/data falkordb/falkordb+```++## Quick Start++### Using the GraphStore Class++```python+from semantica.graph_store import GraphStore++# Initialize with Neo4j backend+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password"+)++# Connect to database+store.connect()++# Create nodes+alice = store.create_node(+ labels=["Person"],+ properties={"name": "Alice", "age": 30}+)++bob = store.create_node(+ labels=["Person"],+ properties={"name": "Bob", "age": 25}+)++# Create relationship+relationship = store.create_relationship(+ start_node_id=alice["id"],+ end_node_id=bob["id"],+ rel_type="KNOWS",+ properties={"since": 2020}+)++# Query the graph+results = store.execute_query(+ "MATCH (p:Person) WHERE p.age > 20 RETURN p.name, p.age"+)++for record in results["records"]:+ print(f"{record['p.name']} is {record['p.age']} years old")++# Close connection+store.close()+```++### Using Convenience Functions++```python+from semantica.graph_store import (+ create_node,+ create_relationship,+ get_nodes,+ execute_query,+ shortest_path+)++# Create nodes+alice = create_node(labels=["Person"], properties={"name": "Alice"})+bob = create_node(labels=["Person"], properties={"name": "Bob"})++# Create relationship+rel = create_relationship(+ start_id=alice["id"],+ end_id=bob["id"],+ rel_type="KNOWS"+)++# Get all Person nodes+people = get_nodes(labels=["Person"], limit=100)++# Execute custom query+results = execute_query("MATCH (n) RETURN n LIMIT 10")+```++## Backend Configuration++### Neo4j Configuration++```python+from semantica.graph_store import GraphStore++store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="your_password",+ database="neo4j", # Optional: specify database+ encrypted=False # Optional: enable encryption+)+```++### 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+from semantica.graph_store import GraphStore++store = GraphStore(+ backend="falkordb",+ host="localhost",+ port=6379,+ password=None, # Optional: Redis password+ graph_name="my_graph"+)++# Connect to FalkorDB+store.connect()+```++### Environment Variables++Configure backends using environment variables:++```bash+# General+export GRAPH_STORE_DEFAULT_BACKEND=neo4j+export GRAPH_STORE_BATCH_SIZE=1000+export GRAPH_STORE_TIMEOUT=30++# Neo4j+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+export GRAPH_STORE_FALKORDB_GRAPH_NAME=default+```++## Node Operations++### Creating Nodes++```python+# Single node+node = store.create_node(+ labels=["Person", "Employee"],+ properties={+ "name": "Alice",+ "age": 30,+ "department": "Engineering"+ }+)++# Multiple nodes in batch+nodes = store.create_nodes([+ {"labels": ["Person"], "properties": {"name": "Bob"}},+ {"labels": ["Person"], "properties": {"name": "Charlie"}},+ {"labels": ["Company"], "properties": {"name": "Acme Corp"}}+])+```++### Retrieving Nodes++```python+# Get node by ID+node = store.get_node(node_id=123)++# Get nodes by labels+people = store.get_nodes(labels=["Person"], limit=50)++# Get nodes by properties+engineers = store.get_nodes(+ labels=["Person"],+ properties={"department": "Engineering"}+)+```++### Updating Nodes++```python+# Merge properties (default)+updated = store.update_node(+ node_id=123,+ properties={"age": 31, "title": "Senior Engineer"},+ merge=True+)++# Replace all properties+updated = store.update_node(+ node_id=123,+ properties={"name": "Alice Smith"},+ merge=False+)+```++### Deleting Nodes++```python+# Delete node and its relationships+store.delete_node(node_id=123, detach=True)++# Delete only node (fails if has relationships)+store.delete_node(node_id=123, detach=False)+```++## Relationship Operations++### Creating Relationships++```python+# Single relationship+rel = store.create_relationship(+ start_node_id=alice["id"],+ end_node_id=bob["id"],+ rel_type="KNOWS",+ properties={"since": 2020, "type": "friend"}+)++# Multiple relationships+from semantica.graph_store import create_relationships++rels = create_relationships([+ {"start_id": 1, "end_id": 2, "type": "WORKS_FOR"},+ {"start_id": 1, "end_id": 3, "type": "MANAGES"},+ {"start_id": 2, "end_id": 3, "type": "COLLABORATES_WITH"}+])+```++### Retrieving Relationships++```python+# All relationships for a node+rels = store.get_relationships(node_id=123)++# Outgoing relationships only+outgoing = store.get_relationships(+ node_id=123,+ direction="out"+)++# Filter by type+knows_rels = store.get_relationships(+ node_id=123,+ rel_type="KNOWS"+)+```++### Deleting Relationships++```python+store.delete_relationship(rel_id=456)+```++## Query Execution++### Basic Queries++```python+# Simple query+results = store.execute_query(+ "MATCH (n:Person) RETURN n.name, n.age"+)++# Parameterized query+results = store.execute_query(+ "MATCH (n:Person) WHERE n.age > $min_age RETURN n.name",+ parameters={"min_age": 25}+)++# Process results+for record in results["records"]:+ print(record)+```++### Complex Queries++```python+# Find paths+results = store.execute_query("""+ MATCH path = (a:Person {name: 'Alice'})-[:KNOWS*1..3]-(b:Person)+ RETURN path+""")++# Aggregations+results = store.execute_query("""+ MATCH (p:Person)+ RETURN p.department, count(*) as count, avg(p.age) as avg_age+ ORDER BY count DESC+""")+```++## Graph Analytics++### Shortest Path++```python+path = store.shortest_path(+ start_node_id=alice["id"],+ end_node_id=bob["id"],+ rel_type="KNOWS",+ max_depth=5+)++if path:+ print(f"Path length: {path['length']}")+ print(f"Nodes in path: {len(path['nodes'])}")+```++### Get Neighbors++```python+# Direct neighbors+neighbors = store.get_neighbors(node_id=123, depth=1)++# Extended neighborhood+extended = store.get_neighbors(+ node_id=123,+ rel_type="KNOWS",+ direction="out",+ depth=3+)+```++### Run Analytics Algorithms++```python+from semantica.graph_store import run_analytics++# Degree centrality+centrality = run_analytics(+ algorithm="degree_centrality",+ labels=["Person"],+ direction="both"+)++# Connected components (basic approximation)+components = run_analytics(+ algorithm="connected_components"+)+```++## Convenience Functions++The module provides convenience functions for common operations:++```python+from semantica.graph_store import (+ # Node operations+ create_node,+ create_nodes,+ get_nodes,+ update_node,+ delete_node,++ # Relationship operations+ create_relationship,+ create_relationships,+ get_relationships,+ update_relationship,+ delete_relationship,++ # Query operations+ execute_query,++ # Analytics operations+ shortest_path,+ get_neighbors,+ run_analytics,++ # Method registry+ get_graph_store_method,+ list_available_methods+)+```++## Advanced Usage++### Context Manager++```python+from semantica.graph_store import GraphStore++with GraphStore(backend="neo4j", uri="bolt://localhost:7687") as store:+ store.create_node(labels=["Test"], properties={"name": "test"})+ # Connection automatically closed when exiting+```++### Custom Method Registration++```python+from semantica.graph_store import method_registry++def custom_create_node(labels, properties, **options):+ """Custom node creation with validation."""+ # Add custom logic+ if "name" not in properties:+ raise ValueError("name is required")++ # Call default implementation+ from semantica.graph_store import _get_store+ store = _get_store()+ return store.create_node(labels, properties, **options)++# Register custom method+method_registry.register("node", "validated", custom_create_node)++# Use custom method+from semantica.graph_store import create_node+node = create_node(labels=["Person"], properties={"name": "Alice"}, method="validated")+```++### Indexing++```python+# Create index for faster queries+store.create_index(+ label="Person",+ property_name="name",+ index_type="btree"+)++# Create fulltext index (Neo4j, FalkorDB)+store.create_index(+ label="Document",+ property_name="content",+ index_type="fulltext"+)+```++### Statistics++```python+stats = store.get_stats()+print(f"Total nodes: {stats.get('node_count')}")+print(f"Total relationships: {stats.get('relationship_count')}")+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 |++## Best Practices++1. **Use Parameterized Queries**: Always use parameters for user input to prevent injection attacks.++2. **Create Indexes**: Create indexes on frequently queried properties for better performance.++3. **Batch Operations**: Use batch operations when creating many nodes/relationships.++4. **Close Connections**: Always close connections when done, or use context managers.++5. **Handle Errors**: Wrap operations in try/except blocks for proper error handling.++```python+from semantica.utils.exceptions import ProcessingError++try:+ node = store.create_node(labels=["Person"], properties={"name": "Alice"})+except ProcessingError as e:+ print(f"Failed to create node: {e}")+```++## Examples++### Building a Social Network Graph++```python+from semantica.graph_store import GraphStore, create_node, create_relationship++# Initialize store+store = GraphStore(backend="neo4j")+store.connect()++# Create users+users = [+ {"name": "Alice", "age": 30},+ {"name": "Bob", "age": 25},+ {"name": "Charlie", "age": 35},+]++user_nodes = store.create_nodes([+ {"labels": ["User"], "properties": u} for u in users+])++# Create friendships+store.create_relationship(user_nodes[0]["id"], user_nodes[1]["id"], "FRIENDS")+store.create_relationship(user_nodes[1]["id"], user_nodes[2]["id"], "FRIENDS")++# Find friends of friends+results = store.execute_query("""+ MATCH (a:User {name: 'Alice'})-[:FRIENDS]-()-[:FRIENDS]-(fof:User)+ WHERE fof <> a+ RETURN DISTINCT fof.name+""")+```++### Knowledge Graph for RAG++```python+from semantica.graph_store import GraphStore++store = GraphStore(backend="falkordb", graph_name="knowledge_graph")+store.connect()++# Create entities+doc = store.create_node(["Document"], {"title": "AI Research", "content": "..."})+concept1 = store.create_node(["Concept"], {"name": "Machine Learning"})+concept2 = store.create_node(["Concept"], {"name": "Neural Networks"})++# Create relationships+store.create_relationship(doc["id"], concept1["id"], "MENTIONS")+store.create_relationship(concept1["id"], concept2["id"], "RELATED_TO")++# Query for retrieval+results = store.execute_query("""+ MATCH (d:Document)-[:MENTIONS]->(c:Concept)+ WHERE c.name CONTAINS 'Learning'+ RETURN d.title, d.content+""")+```+diff --git a/semantica/graph_store/kuzu_adapter.py b/semantica/graph_store/kuzu_adapter.pynew file mode 100644index 00000000..66cf89a9--- /dev/null+++ b/semantica/graph_store/kuzu_adapter.py@@ -0,0 +1,917 @@+"""+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/semantica/graph_store/methods.py b/semantica/graph_store/methods.pynew file mode 100644index 00000000..26dd0d5e--- /dev/null+++ b/semantica/graph_store/methods.py@@ -0,0 +1,562 @@+"""+Graph Store Methods Module++This module provides all graph store methods as simple, reusable functions for+creating nodes, relationships, querying, and running analytics. It supports+multiple approaches and integrates with the method registry for extensibility.++Supported Methods:++Node Operations:+ - "default": Default node creation using GraphStore+ - "batch": Batch node creation+ - "validated": Validated node creation with schema checking++Relationship Operations:+ - "default": Default relationship creation+ - "batch": Batch relationship creation++Query Operations:+ - "default": Default Cypher query execution+ - "cached": Cached query execution+ - "optimized": Optimized query execution++Analytics Operations:+ - "shortest_path": Shortest path algorithm+ - "neighbors": Neighbor traversal+ - "centrality": Centrality calculations++Key Features:+ - Multiple graph store operation methods+ - Node and relationship operations with method dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - create_node: Node creation wrapper+ - create_nodes: Batch node creation wrapper+ - create_relationship: Relationship creation wrapper+ - create_relationships: Batch relationship creation wrapper+ - get_nodes: Get nodes wrapper+ - get_relationships: Get relationships wrapper+ - update_node: Update node wrapper+ - update_relationship: Update relationship wrapper+ - delete_node: Delete node wrapper+ - delete_relationship: Delete relationship wrapper+ - execute_query: Query execution wrapper+ - shortest_path: Shortest path wrapper+ - get_neighbors: Get neighbors wrapper+ - run_analytics: Run analytics wrapper+ - get_graph_store_method: Get graph store method by task and name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.graph_store.methods import create_node, create_relationship, execute_query+ >>> node_id = create_node(labels=["Person"], properties={"name": "Alice"})+ >>> rel = create_relationship(start_id=node1_id, end_id=node2_id, type="KNOWS")+ >>> results = execute_query("MATCH (p:Person) RETURN p.name")+"""++from typing import Any, Dict, List, Optional, Union++from .config import graph_store_config+from .graph_store import GraphAnalytics, GraphStore, NodeManager, QueryEngine, RelationshipManager+from .registry import method_registry++# Global store instance+_global_store: Optional[GraphStore] = None+++def _get_store() -> GraphStore:+ """Get or create global GraphStore instance."""+ global _global_store+ if _global_store is None:+ config = graph_store_config.get_all()+ backend = config.get("default_backend", "neo4j")+ _global_store = GraphStore(backend=backend, **config)+ return _global_store+++def _reset_store() -> None:+ """Reset the global store instance."""+ global _global_store+ if _global_store is not None:+ _global_store.close()+ _global_store = None+++# Node Operations++def create_node(+ labels: List[str],+ properties: Dict[str, Any],+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Create a node in the graph.++ Args:+ labels: Node labels+ properties: Node properties+ method: Creation method name (default: "default")+ **options: Additional options++ Returns:+ Created node information including ID+ """+ # Check registry for custom method+ custom_method = method_registry.get("node", method)+ if custom_method:+ return custom_method(labels, properties, **options)++ # Default implementation+ store = _get_store()+ return store.create_node(labels, properties, **options)+++def create_nodes(+ nodes: List[Dict[str, Any]],+ method: str = "default",+ **options,+) -> List[Dict[str, Any]]:+ """+ Create multiple nodes in batch.++ Args:+ nodes: List of node dictionaries with 'labels' and 'properties'+ method: Creation method name (default: "default")+ **options: Additional options++ Returns:+ List of created node information+ """+ # Check registry for custom method+ custom_method = method_registry.get("node", method)+ if custom_method:+ return custom_method(nodes, **options)++ # Default implementation+ store = _get_store()+ return store.create_nodes(nodes, **options)+++def get_nodes(+ labels: Optional[List[str]] = None,+ properties: Optional[Dict[str, Any]] = None,+ limit: int = 100,+ method: str = "default",+ **options,+) -> List[Dict[str, Any]]:+ """+ Get nodes matching criteria.++ Args:+ labels: Filter by labels+ properties: Filter by properties+ limit: Maximum number of nodes+ method: Retrieval method name (default: "default")+ **options: Additional options++ Returns:+ List of matching nodes+ """+ # Check registry for custom method+ custom_method = method_registry.get("node", method)+ if custom_method:+ return custom_method(labels=labels, properties=properties, limit=limit, **options)++ # Default implementation+ store = _get_store()+ return store.get_nodes(labels, properties, limit, **options)+++def update_node(+ node_id: Union[int, str],+ properties: Dict[str, Any],+ merge: bool = True,+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Update a node's properties.++ Args:+ node_id: Node ID+ properties: Properties to update+ merge: If True, merge properties; if False, replace+ method: Update method name (default: "default")+ **options: Additional options++ Returns:+ Updated node information+ """+ # Check registry for custom method+ custom_method = method_registry.get("node", method)+ if custom_method:+ return custom_method(node_id, properties, merge=merge, **options)++ # Default implementation+ store = _get_store()+ return store.update_node(node_id, properties, merge, **options)+++def delete_node(+ node_id: Union[int, str],+ detach: bool = True,+ method: str = "default",+ **options,+) -> bool:+ """+ Delete a node.++ Args:+ node_id: Node ID+ detach: If True, delete relationships as well+ method: Deletion method name (default: "default")+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ # Check registry for custom method+ custom_method = method_registry.get("node", method)+ if custom_method:+ return custom_method(node_id, detach=detach, **options)++ # Default implementation+ store = _get_store()+ return store.delete_node(node_id, detach, **options)+++# Relationship Operations++def create_relationship(+ start_id: Union[int, str],+ end_id: Union[int, str],+ rel_type: str,+ properties: Optional[Dict[str, Any]] = None,+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Create a relationship between two nodes.++ Args:+ start_id: Start node ID+ end_id: End node ID+ rel_type: Relationship type+ properties: Relationship properties+ method: Creation method name (default: "default")+ **options: Additional options++ Returns:+ Created relationship information+ """+ # Check registry for custom method+ custom_method = method_registry.get("relationship", method)+ if custom_method:+ return custom_method(start_id, end_id, rel_type, properties=properties, **options)++ # Default implementation+ store = _get_store()+ return store.create_relationship(start_id, end_id, rel_type, properties, **options)+++def create_relationships(+ relationships: List[Dict[str, Any]],+ method: str = "default",+ **options,+) -> List[Dict[str, Any]]:+ """+ Create multiple relationships in batch.++ Args:+ relationships: List of relationship dictionaries with 'start_id', 'end_id', 'type', and optional 'properties'+ method: Creation method name (default: "default")+ **options: Additional options++ Returns:+ List of created relationship information+ """+ # Check registry for custom method+ custom_method = method_registry.get("relationship", method)+ if custom_method:+ return custom_method(relationships, **options)++ # Default implementation+ store = _get_store()+ created = []+ for rel in relationships:+ result = store.create_relationship(+ rel["start_id"],+ rel["end_id"],+ rel["type"],+ rel.get("properties"),+ **options,+ )+ created.append(result)+ return created+++def get_relationships(+ node_id: Optional[Union[int, str]] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ limit: int = 100,+ method: str = "default",+ **options,+) -> List[Dict[str, Any]]:+ """+ Get relationships matching criteria.++ Args:+ node_id: Filter by node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ limit: Maximum number of relationships+ method: Retrieval method name (default: "default")+ **options: Additional options++ Returns:+ List of matching relationships+ """+ # Check registry for custom method+ custom_method = method_registry.get("relationship", method)+ if custom_method:+ return custom_method(node_id=node_id, rel_type=rel_type, direction=direction, limit=limit, **options)++ # Default implementation+ store = _get_store()+ return store.get_relationships(node_id, rel_type, direction, limit, **options)+++def update_relationship(+ rel_id: Union[int, str],+ properties: Dict[str, Any],+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Update a relationship's properties.++ Args:+ rel_id: Relationship ID+ properties: Properties to update+ method: Update method name (default: "default")+ **options: Additional options++ Returns:+ Updated relationship information+ """+ # Check registry for custom method+ custom_method = method_registry.get("relationship", method)+ if custom_method:+ return custom_method(rel_id, properties, **options)++ # Default implementation - execute update query+ store = _get_store()+ set_parts = ", ".join(f"r.{k} = ${k}" for k in properties.keys())+ query = f"MATCH ()-[r]->() WHERE id(r) = $rel_id SET {set_parts} RETURN id(r) as id, type(r) as type, r"+ params = {"rel_id": rel_id, **properties}+ result = store.execute_query(query, params)++ if result.get("records"):+ record = result["records"][0]+ return {+ "id": record.get("id"),+ "type": record.get("type"),+ "properties": properties,+ }+ raise ValueError(f"Relationship with ID {rel_id} not found")+++def delete_relationship(+ rel_id: Union[int, str],+ method: str = "default",+ **options,+) -> bool:+ """+ Delete a relationship.++ Args:+ rel_id: Relationship ID+ method: Deletion method name (default: "default")+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ # Check registry for custom method+ custom_method = method_registry.get("relationship", method)+ if custom_method:+ return custom_method(rel_id, **options)++ # Default implementation+ store = _get_store()+ return store.delete_relationship(rel_id, **options)+++# Query Operations++def execute_query(+ query: str,+ parameters: Optional[Dict[str, Any]] = None,+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Execute a Cypher/OpenCypher query.++ Args:+ query: Query string+ parameters: Query parameters+ method: Execution method name (default: "default")+ **options: Additional options++ Returns:+ Query results+ """+ # Check registry for custom method+ custom_method = method_registry.get("query", method)+ if custom_method:+ return custom_method(query, parameters=parameters, **options)++ # Default implementation+ store = _get_store()+ return store.execute_query(query, parameters, **options)+++# Analytics Operations++def shortest_path(+ start_node_id: Union[int, str],+ end_node_id: Union[int, str],+ rel_type: Optional[str] = None,+ max_depth: int = 10,+ method: str = "default",+ **options,+) -> Optional[Dict[str, Any]]:+ """+ Find shortest path between two nodes.++ Args:+ start_node_id: Starting node ID+ end_node_id: Ending node ID+ rel_type: Filter by relationship type+ max_depth: Maximum path length+ method: Algorithm method name (default: "default")+ **options: Additional options++ Returns:+ Path information or None if not found+ """+ # Check registry for custom method+ custom_method = method_registry.get("traversal", method)+ if custom_method:+ return custom_method(start_node_id, end_node_id, rel_type=rel_type, max_depth=max_depth, **options)++ # Default implementation+ store = _get_store()+ return store.shortest_path(start_node_id, end_node_id, rel_type, max_depth, **options)+++def get_neighbors(+ node_id: Union[int, str],+ rel_type: Optional[str] = None,+ direction: str = "both",+ depth: int = 1,+ method: str = "default",+ **options,+) -> List[Dict[str, Any]]:+ """+ Get neighboring nodes.++ Args:+ node_id: Starting node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ depth: Traversal depth+ method: Traversal method name (default: "default")+ **options: Additional options++ Returns:+ List of neighboring nodes+ """+ # Check registry for custom method+ custom_method = method_registry.get("traversal", method)+ if custom_method:+ return custom_method(node_id, rel_type=rel_type, direction=direction, depth=depth, **options)++ # Default implementation+ store = _get_store()+ return store.get_neighbors(node_id, rel_type, direction, depth, **options)+++def run_analytics(+ algorithm: str,+ method: str = "default",+ **options,+) -> Dict[str, Any]:+ """+ Run a graph analytics algorithm.++ Args:+ algorithm: Algorithm name ("degree_centrality", "connected_components", etc.)+ method: Analytics method name (default: "default")+ **options: Algorithm-specific options++ Returns:+ Analytics results+ """+ # Check registry for custom method+ custom_method = method_registry.get("analytics", method)+ if custom_method:+ return custom_method(algorithm, **options)++ # Default implementation+ store = _get_store()++ if algorithm == "degree_centrality":+ return {+ "algorithm": algorithm,+ "results": store.analytics.degree_centrality(**options),+ }+ elif algorithm == "connected_components":+ return {+ "algorithm": algorithm,+ "results": store.analytics.connected_components(**options),+ }+ else:+ raise ValueError(f"Unknown algorithm: {algorithm}")+++# Utility Functions++def get_graph_store_method(task: str, method_name: str) -> Optional[Any]:+ """+ Get graph store method by task and name.++ Args:+ task: Task type (node, relationship, query, traversal, analytics, bulk)+ method_name: Method name++ Returns:+ Method function or None if not found+ """+ return method_registry.get(task, method_name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all available graph store methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to lists of method names+ """+ return method_registry.list_all(task)+diff --git a/semantica/graph_store/neo4j_adapter.py b/semantica/graph_store/neo4j_adapter.pynew file mode 100644index 00000000..be8fcd8f--- /dev/null+++ b/semantica/graph_store/neo4j_adapter.py@@ -0,0 +1,1034 @@+"""+Neo4j Adapter Module++This module provides Neo4j graph database integration for property graph storage and+Cypher querying in the Semantica framework, supporting full CRUD operations,+transactions, and graph analytics.++Key Features:+ - Full Cypher query language support+ - Node and relationship CRUD operations+ - Transaction support with rollback+ - Multi-database support+ - Index and constraint management+ - Graph algorithms via GDS library+ - Batch operations with progress tracking+ - Optional dependency handling++Main Classes:+ - Neo4jAdapter: Main Neo4j adapter for graph operations+ - Neo4jDriver: Neo4j driver wrapper+ - Neo4jSession: Session management wrapper+ - Neo4jTransaction: Transaction wrapper++Example Usage:+ >>> from semantica.graph_store import Neo4jAdapter+ >>> adapter = Neo4jAdapter(uri="bolt://localhost:7687", user="neo4j", password="password")+ >>> adapter.connect()+ >>> node_id = adapter.create_node(labels=["Person"], properties={"name": "Alice"})+ >>> results = adapter.execute_query("MATCH (p:Person) RETURN p.name")+ >>> adapter.close()++Author: Semantica Contributors+License: MIT+"""++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 Neo4j import+try:+ from neo4j import GraphDatabase+ from neo4j.exceptions import (+ AuthError,+ Neo4jError,+ ServiceUnavailable,+ TransactionError,+ )++ NEO4J_AVAILABLE = True+except ImportError:+ NEO4J_AVAILABLE = False+ GraphDatabase = None+ Neo4jError = Exception+ AuthError = Exception+ ServiceUnavailable = Exception+ TransactionError = Exception+++class Neo4jDriver:+ """Neo4j driver wrapper."""++ def __init__(self, driver: Any):+ """Initialize Neo4j driver wrapper."""+ self.driver = driver+ self.logger = get_logger("neo4j_driver")++ def session(self, database: Optional[str] = None) -> "Neo4jSession":+ """+ Create a new session.++ Args:+ database: Database name (optional)++ Returns:+ Neo4jSession instance+ """+ if not NEO4J_AVAILABLE:+ raise ProcessingError("Neo4j not available")++ try:+ if database:+ session = self.driver.session(database=database)+ else:+ session = self.driver.session()+ return Neo4jSession(session)+ except Exception as e:+ raise ProcessingError(f"Failed to create session: {str(e)}")++ def verify_connectivity(self) -> bool:+ """Verify connectivity to Neo4j server."""+ if not NEO4J_AVAILABLE:+ return False++ try:+ self.driver.verify_connectivity()+ return True+ except Exception as e:+ self.logger.warning(f"Connectivity check failed: {e}")+ return False++ def close(self) -> None:+ """Close the driver."""+ if self.driver:+ self.driver.close()+++class Neo4jSession:+ """Neo4j session wrapper."""++ def __init__(self, session: Any):+ """Initialize Neo4j session wrapper."""+ self.session = session+ self.logger = get_logger("neo4j_session")++ def run(self, query: str, parameters: Optional[Dict[str, Any]] = None) -> Any:+ """+ Run a Cypher query.++ Args:+ query: Cypher query string+ parameters: Query parameters++ Returns:+ Query result+ """+ if not NEO4J_AVAILABLE:+ raise ProcessingError("Neo4j not available")++ try:+ result = self.session.run(query, parameters or {})+ return result+ except Exception as e:+ raise ProcessingError(f"Query execution failed: {str(e)}")++ def begin_transaction(self) -> "Neo4jTransaction":+ """Begin a new transaction."""+ if not NEO4J_AVAILABLE:+ raise ProcessingError("Neo4j not available")++ try:+ tx = self.session.begin_transaction()+ return Neo4jTransaction(tx)+ except Exception as e:+ raise ProcessingError(f"Failed to begin transaction: {str(e)}")++ def read_transaction(self, func: Any, **kwargs) -> Any:+ """Execute a read transaction."""+ return self.session.execute_read(func, **kwargs)++ def write_transaction(self, func: Any, **kwargs) -> Any:+ """Execute a write transaction."""+ return self.session.execute_write(func, **kwargs)++ def close(self) -> None:+ """Close the session."""+ if self.session:+ self.session.close()++ def __enter__(self):+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit."""+ self.close()+++class Neo4jTransaction:+ """Neo4j transaction wrapper."""++ def __init__(self, transaction: Any):+ """Initialize Neo4j transaction wrapper."""+ self.transaction = transaction+ self.logger = get_logger("neo4j_transaction")++ def run(self, query: str, parameters: Optional[Dict[str, Any]] = None) -> Any:+ """+ Run a Cypher query within the transaction.++ Args:+ query: Cypher query string+ parameters: Query parameters++ Returns:+ Query result+ """+ if not NEO4J_AVAILABLE:+ raise ProcessingError("Neo4j not available")++ try:+ result = self.transaction.run(query, parameters or {})+ return result+ except Exception as e:+ raise ProcessingError(f"Transaction query failed: {str(e)}")++ def commit(self) -> None:+ """Commit the transaction."""+ if self.transaction:+ self.transaction.commit()++ def rollback(self) -> None:+ """Rollback the transaction."""+ if self.transaction:+ self.transaction.rollback()++ def __enter__(self):+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit."""+ if exc_type is not None:+ self.rollback()+ else:+ self.commit()+++class Neo4jAdapter:+ """+ Neo4j adapter for property graph storage and Cypher querying.++ • Neo4j connection and authentication+ • Node and relationship CRUD operations+ • Cypher query execution+ • Transaction support+ • Index and constraint management+ • Performance optimization+ • Error handling and recovery+ """++ def __init__(+ self,+ uri: Optional[str] = None,+ user: Optional[str] = None,+ password: Optional[str] = None,+ database: Optional[str] = None,+ **config,+ ):+ """+ Initialize Neo4j adapter.++ Args:+ uri: Neo4j connection URI (bolt://localhost:7687)+ user: Neo4j username+ password: Neo4j password+ database: Database name+ **config: Additional configuration options+ """+ self.logger = get_logger("neo4j_adapter")+ self.config = config+ self.progress_tracker = get_progress_tracker()++ self.uri = uri or config.get("uri", "bolt://localhost:7687")+ self.user = user or config.get("user", "neo4j")+ self.password = password or config.get("password", "password")+ self.database = database or config.get("database", "neo4j")+ self.encrypted = config.get("encrypted", False)++ self._driver: Optional[Neo4jDriver] = None+ self._session: Optional[Neo4jSession] = None++ # Check Neo4j availability+ if not NEO4J_AVAILABLE:+ self.logger.warning(+ "Neo4j not available. Install with: pip install neo4j"+ )++ def connect(+ self,+ uri: Optional[str] = None,+ user: Optional[str] = None,+ password: Optional[str] = None,+ **options,+ ) -> bool:+ """+ Connect to Neo4j server.++ Args:+ uri: Neo4j connection URI+ user: Username+ password: Password+ **options: Connection options++ Returns:+ True if connected successfully+ """+ if not NEO4J_AVAILABLE:+ raise ProcessingError(+ "Neo4j is not available. Install it with: pip install neo4j"+ )++ uri = uri or self.uri+ user = user or self.user+ password = password or self.password++ try:+ driver = GraphDatabase.driver(uri, auth=(user, password), **options)+ self._driver = Neo4jDriver(driver)++ # Verify connectivity+ if self._driver.verify_connectivity():+ self.logger.info(f"Connected to Neo4j at {uri}")+ return True+ else:+ raise ProcessingError("Could not verify connectivity to Neo4j")++ except AuthError as e:+ raise ProcessingError(f"Neo4j authentication failed: {str(e)}")+ except ServiceUnavailable as e:+ raise ProcessingError(f"Neo4j service unavailable: {str(e)}")+ except Exception as e:+ raise ProcessingError(f"Failed to connect to Neo4j: {str(e)}")++ def close(self) -> None:+ """Close connection to Neo4j."""+ if self._session:+ self._session.close()+ self._session = None+ if self._driver:+ self._driver.close()+ self._driver = None+ self.logger.info("Disconnected from Neo4j")++ def get_session(self, database: Optional[str] = None) -> Neo4jSession:+ """+ Get or create a session.++ Args:+ database: Database name++ Returns:+ Neo4jSession instance+ """+ if self._driver is None:+ self.connect()++ return self._driver.session(database or self.database)++ def create_node(+ self,+ labels: List[str],+ properties: Dict[str, Any],+ **options,+ ) -> Dict[str, Any]:+ """+ Create a node in the graph.++ Args:+ labels: Node labels+ properties: Node properties+ **options: Additional options++ Returns:+ Created node information including ID+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="Neo4jAdapter",+ message=f"Creating node with labels {labels}",+ )++ try:+ label_str = ":".join(labels)+ query = f"CREATE (n:{label_str} $props) RETURN id(n) as id, n"++ with self.get_session() as session:+ result = session.run(query, {"props": properties})+ record = result.single()++ if record:+ node_data = {+ "id": record["id"],+ "labels": labels,+ "properties": dict(record["n"]),+ }++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Created node with ID {record['id']}",+ )+ return node_data+ else:+ raise ProcessingError("Failed to create node - no result returned")++ 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,+ nodes: List[Dict[str, Any]],+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Create multiple nodes in batch.++ Args:+ nodes: List of node dictionaries with 'labels' and 'properties'+ **options: Additional options++ Returns:+ List of created node information+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="Neo4jAdapter",+ message=f"Creating {len(nodes)} nodes in batch",+ )++ try:+ created_nodes = []++ with self.get_session() as session:+ for node in nodes:+ labels = node.get("labels", [])+ properties = node.get("properties", {})++ label_str = ":".join(labels) if labels else "Node"+ query = f"CREATE (n:{label_str} $props) RETURN id(n) as id, n"++ result = session.run(query, {"props": properties})+ record = result.single()++ if record:+ created_nodes.append({+ "id": record["id"],+ "labels": labels,+ "properties": dict(record["n"]),+ })++ 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_node(+ self,+ node_id: int,+ **options,+ ) -> Optional[Dict[str, Any]]:+ """+ Get a node by ID.++ Args:+ node_id: Node ID+ **options: Additional options++ Returns:+ Node information or None if not found+ """+ try:+ query = "MATCH (n) WHERE id(n) = $id RETURN n, labels(n) as labels"++ with self.get_session() as session:+ result = session.run(query, {"id": node_id})+ record = result.single()++ if record:+ return {+ "id": node_id,+ "labels": record["labels"],+ "properties": dict(record["n"]),+ }+ return None++ except Exception as e:+ raise ProcessingError(f"Failed to get node: {str(e)}")++ def get_nodes(+ self,+ labels: Optional[List[str]] = None,+ properties: Optional[Dict[str, Any]] = None,+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get nodes matching criteria.++ Args:+ labels: Filter by labels+ properties: Filter by properties+ limit: Maximum number of nodes to return+ **options: Additional options++ Returns:+ List of matching nodes+ """+ try:+ # Build query+ if labels:+ label_str = ":".join(labels)+ query = f"MATCH (n:{label_str})"+ else:+ query = "MATCH (n)"++ # Add property filters+ if properties:+ conditions = []+ for key, value in properties.items():+ conditions.append(f"n.{key} = ${key}")+ query += " WHERE " + " AND ".join(conditions)++ query += f" RETURN id(n) as id, n, labels(n) as labels LIMIT {limit}"++ with self.get_session() as session:+ result = session.run(query, properties or {})++ nodes = []+ for record in result:+ nodes.append({+ "id": record["id"],+ "labels": record["labels"],+ "properties": dict(record["n"]),+ })++ return nodes++ except Exception as e:+ raise ProcessingError(f"Failed to get nodes: {str(e)}")++ def update_node(+ self,+ node_id: int,+ properties: Dict[str, Any],+ merge: bool = True,+ **options,+ ) -> Dict[str, Any]:+ """+ Update a node's properties.++ Args:+ node_id: Node ID+ properties: Properties to update+ merge: If True, merge properties; if False, replace+ **options: Additional options++ Returns:+ Updated node information+ """+ try:+ if merge:+ query = "MATCH (n) WHERE id(n) = $id SET n += $props RETURN id(n) as id, n, labels(n) as labels"+ else:+ query = "MATCH (n) WHERE id(n) = $id SET n = $props RETURN id(n) as id, n, labels(n) as labels"++ with self.get_session() as session:+ result = session.run(query, {"id": node_id, "props": properties})+ record = result.single()++ if record:+ return {+ "id": record["id"],+ "labels": record["labels"],+ "properties": dict(record["n"]),+ }+ else:+ raise ProcessingError(f"Node with ID {node_id} not found")++ except Exception as e:+ raise ProcessingError(f"Failed to update node: {str(e)}")++ def delete_node(+ self,+ node_id: int,+ detach: bool = True,+ **options,+ ) -> bool:+ """+ Delete a node.++ Args:+ node_id: Node ID+ detach: If True, delete relationships as well+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ try:+ if detach:+ query = "MATCH (n) WHERE id(n) = $id DETACH DELETE n"+ else:+ query = "MATCH (n) WHERE id(n) = $id DELETE n"++ with self.get_session() as session:+ session.run(query, {"id": node_id})+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to delete node: {str(e)}")++ 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]:+ """+ Create a relationship between two nodes.++ Args:+ start_node_id: Start node ID+ end_node_id: End node ID+ rel_type: Relationship type+ properties: Relationship properties+ **options: Additional options++ Returns:+ Created relationship information+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="graph_store",+ submodule="Neo4jAdapter",+ message=f"Creating relationship [{rel_type}]",+ )++ try:+ properties = properties or {}+ query = f"""+ MATCH (a), (b)+ WHERE id(a) = $start_id AND id(b) = $end_id+ CREATE (a)-[r:{rel_type} $props]->(b)+ RETURN id(r) as id, type(r) as type, r+ """++ with self.get_session() as session:+ result = session.run(query, {+ "start_id": start_node_id,+ "end_id": end_node_id,+ "props": properties,+ })+ record = result.single()++ if record:+ rel_data = {+ "id": record["id"],+ "type": record["type"],+ "start_node_id": start_node_id,+ "end_node_id": end_node_id,+ "properties": dict(record["r"]),+ }++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Created relationship with ID {record['id']}",+ )+ return rel_data+ else:+ raise ProcessingError("Failed to create relationship - nodes not found")++ 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,+ node_id: Optional[int] = None,+ rel_type: Optional[str] = None,+ direction: str = "both",+ limit: int = 100,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get relationships matching criteria.++ Args:+ node_id: Filter by node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ limit: Maximum number of relationships+ **options: Additional options++ Returns:+ List of matching relationships+ """+ try:+ type_filter = f":{rel_type}" if rel_type else ""++ if node_id is not None:+ if direction == "out":+ query = f"""+ MATCH (a)-[r{type_filter}]->(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(a) as start_id, id(b) as end_id, r+ LIMIT {limit}+ """+ elif direction == "in":+ query = f"""+ MATCH (a)<-[r{type_filter}]-(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(b) as start_id, id(a) as end_id, r+ LIMIT {limit}+ """+ else:+ query = f"""+ MATCH (a)-[r{type_filter}]-(b)+ WHERE id(a) = $node_id+ RETURN id(r) as id, type(r) as type, id(startNode(r)) as start_id, id(endNode(r)) as end_id, r+ LIMIT {limit}+ """+ else:+ query = f"""+ MATCH (a)-[r{type_filter}]->(b)+ RETURN id(r) as id, type(r) as type, id(a) as start_id, id(b) as end_id, r+ LIMIT {limit}+ """++ with self.get_session() as session:+ result = session.run(query, {"node_id": node_id})++ relationships = []+ for record in result:+ relationships.append({+ "id": record["id"],+ "type": record["type"],+ "start_node_id": record["start_id"],+ "end_node_id": record["end_id"],+ "properties": dict(record["r"]),+ })++ return relationships++ except Exception as e:+ raise ProcessingError(f"Failed to get relationships: {str(e)}")++ def delete_relationship(+ self,+ rel_id: int,+ **options,+ ) -> bool:+ """+ Delete a relationship.++ Args:+ rel_id: Relationship ID+ **options: Additional options++ Returns:+ True if deleted successfully+ """+ try:+ query = "MATCH ()-[r]->() WHERE id(r) = $id DELETE r"++ with self.get_session() as session:+ session.run(query, {"id": rel_id})+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to delete relationship: {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="Neo4jAdapter",+ message="Executing Cypher query",+ )++ try:+ with self.get_session() as session:+ result = session.run(query, parameters or {})++ records = []+ keys = []++ for record in result:+ if not keys:+ keys = list(record.keys())++ row = {}+ for key in keys:+ value = record[key]+ # Convert Neo4j types to Python types+ if hasattr(value, "__iter__") and not isinstance(value, (str, dict)):+ row[key] = list(value)+ elif hasattr(value, "items"):+ row[key] = dict(value)+ else:+ row[key] = value+ records.append(row)++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Query returned {len(records)} records",+ )++ return {+ "success": True,+ "records": records,+ "keys": keys,+ "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 get_neighbors(+ self,+ node_id: int,+ rel_type: Optional[str] = None,+ direction: str = "both",+ depth: int = 1,+ **options,+ ) -> List[Dict[str, Any]]:+ """+ Get neighboring nodes.++ Args:+ node_id: Starting node ID+ rel_type: Filter by relationship type+ direction: Direction ("in", "out", "both")+ depth: Traversal depth+ **options: Additional options++ Returns:+ List of neighboring nodes with path information+ """+ try:+ type_filter = f":{rel_type}" if rel_type else ""++ if direction == "out":+ pattern = f"-[r{type_filter}*1..{depth}]->"+ elif direction == "in":+ pattern = f"<-[r{type_filter}*1..{depth}]-"+ else:+ pattern = f"-[r{type_filter}*1..{depth}]-"++ query = f"""+ MATCH (start){pattern}(neighbor)+ WHERE id(start) = $node_id+ RETURN DISTINCT id(neighbor) as id, neighbor, labels(neighbor) as labels+ """++ with self.get_session() as session:+ result = session.run(query, {"node_id": node_id})++ neighbors = []+ for record in result:+ neighbors.append({+ "id": record["id"],+ "labels": record["labels"],+ "properties": dict(record["neighbor"]),+ })++ return neighbors++ except Exception as e:+ raise ProcessingError(f"Failed to get neighbors: {str(e)}")++ 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]]:+ """+ Find shortest path between two nodes.++ Args:+ start_node_id: Starting node ID+ end_node_id: Ending node ID+ rel_type: Filter by relationship type+ max_depth: Maximum path length+ **options: Additional options++ Returns:+ Shortest path information or None if not found+ """+ try:+ type_filter = f":{rel_type}" if rel_type else ""++ query = f"""+ MATCH path = shortestPath((start)-[r{type_filter}*..{max_depth}]-(end))+ WHERE id(start) = $start_id AND id(end) = $end_id+ RETURN path, length(path) as length+ """++ with self.get_session() as session:+ result = session.run(query, {+ "start_id": start_node_id,+ "end_id": end_node_id,+ })+ record = result.single()++ if record:+ path = record["path"]+ nodes = []+ relationships = []++ for node in path.nodes:+ nodes.append({+ "id": node.id,+ "labels": list(node.labels),+ "properties": dict(node),+ })++ for rel in path.relationships:+ relationships.append({+ "id": rel.id,+ "type": rel.type,+ "properties": dict(rel),+ })++ return {+ "length": record["length"],+ "nodes": nodes,+ "relationships": relationships,+ }++ return None++ except Exception as e:+ raise ProcessingError(f"Failed to find shortest path: {str(e)}")++ def create_index(+ self,+ label: str,+ property_name: str,+ index_type: str = "btree",+ **options,+ ) -> bool:+ """+ Create an index on a property.++ Args:+ label: Node label+ property_name: Property to index+ index_type: Index type (btree, fulltext, range)+ **options: Additional options++ Returns:+ True if index created successfully+ """+ try:+ index_name = options.get("index_name", f"idx_{label}_{property_name}")++ if index_type == "fulltext":+ query = f"""+ CREATE FULLTEXT INDEX {index_name} IF NOT EXISTS+ FOR (n:{label}) ON EACH [n.{property_name}]+ """+ else:+ query = f"""+ CREATE INDEX {index_name} IF NOT EXISTS+ FOR (n:{label}) ON (n.{property_name})+ """++ with self.get_session() as session:+ session.run(query)+ self.logger.info(f"Created index {index_name} on {label}.{property_name}")+ return True++ except Exception as e:+ raise ProcessingError(f"Failed to create index: {str(e)}")++ def get_stats(self) -> Dict[str, Any]:+ """Get database statistics."""+ try:+ stats = {}++ with self.get_session() as session:+ # Node count+ result = session.run("MATCH (n) RETURN count(n) as count")+ record = result.single()+ stats["node_count"] = record["count"] if record else 0++ # Relationship count+ result = session.run("MATCH ()-[r]->() RETURN count(r) as count")+ record = result.single()+ stats["relationship_count"] = record["count"] if record else 0++ # Label counts+ result = session.run("""+ MATCH (n)+ UNWIND labels(n) as label+ RETURN label, count(*) as count+ ORDER BY count DESC+ """)+ stats["label_counts"] = {r["label"]: r["count"] for r in result}++ # Relationship type counts+ result = session.run("""+ MATCH ()-[r]->()+ RETURN type(r) as type, count(*) as count+ ORDER BY count DESC+ """)+ stats["relationship_type_counts"] = {r["type"]: r["count"] for r in result}++ 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/semantica/graph_store/registry.py b/semantica/graph_store/registry.pynew file mode 100644index 00000000..f6f217d3--- /dev/null+++ b/semantica/graph_store/registry.py@@ -0,0 +1,156 @@+"""+Method Registry Module for Graph Store++This module provides a method registry system for registering custom graph store methods,+enabling extensibility and community contributions to the graph store toolkit.++Supported Registration Types:+ - Method Registry: Register custom graph store methods for:+ * "node": Node CRUD methods+ * "relationship": Relationship CRUD methods+ * "query": Query execution methods+ * "traversal": Graph traversal methods+ * "analytics": Graph analytics methods+ * "bulk": Bulk operation methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom graph store methods+ - Task-based method organization (node, relationship, query, traversal, analytics, bulk)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom graph store methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.graph_store.registry import method_registry+ >>> method_registry.register("node", "custom_create", custom_create_function)+ >>> available = method_registry.list_all("node")+"""++from typing import Any, Callable, Dict, List, Optional+++class MethodRegistry:+ """Registry for custom graph store methods."""++ def __init__(self):+ """Initialize method registry."""+ self._registry: Dict[str, Dict[str, Callable]] = {+ "node": {},+ "relationship": {},+ "query": {},+ "traversal": {},+ "analytics": {},+ "bulk": {},+ }++ def register(+ self, task: str, method_name: str, method_func: Callable, **metadata+ ) -> None:+ """+ Register a method for a specific task.++ Args:+ task: Task type (node, relationship, query, traversal, analytics, bulk)+ method_name: Name of the method+ method_func: Method function to register+ **metadata: Additional metadata for the method+ """+ if task not in self._registry:+ raise ValueError(f"Unknown task type: {task}")++ if not callable(method_func):+ raise ValueError("method_func must be callable")++ # Store method with metadata+ method_func._registry_metadata = metadata+ self._registry[task][method_name] = method_func++ def unregister(self, task: str, method_name: str) -> None:+ """+ Unregister a method.++ Args:+ task: Task type+ method_name: Name of the method to unregister+ """+ if task in self._registry and method_name in self._registry[task]:+ del self._registry[task][method_name]++ def get(self, task: str, method_name: str) -> Optional[Callable]:+ """+ Get a registered method.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ Method function or None if not found+ """+ if task not in self._registry:+ return None+ return self._registry[task].get(method_name)++ def list_all(self, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to lists of method names+ """+ if task:+ if task in self._registry:+ return {task: list(self._registry[task].keys())}+ return {}++ return {task: list(methods.keys()) for task, methods in self._registry.items()}++ def has(self, task: str, method_name: str) -> bool:+ """+ Check if a method is registered.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ True if method is registered, False otherwise+ """+ return task in self._registry and method_name in self._registry[task]++ def get_metadata(self, task: str, method_name: str) -> Dict[str, Any]:+ """+ Get metadata for a registered method.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ Method metadata dictionary+ """+ method = self.get(task, method_name)+ if method and hasattr(method, "_registry_metadata"):+ return method._registry_metadata.copy()+ return {}+++# Global method registry instance+method_registry = MethodRegistry()+