ruvector-postgres 2.0.5

High-performance PostgreSQL vector database extension v2 - pgvector drop-in replacement with 230+ SQL functions, SIMD acceleration, Flash Attention, GNN layers, hybrid search, multi-tenancy, self-healing, and self-learning capabilities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# Graph Operations & Cypher Integration Plan

## Overview

Integrate graph database capabilities from `ruvector-graph` into PostgreSQL, enabling Cypher query language support, property graph operations, and vector-enhanced graph traversals directly in SQL.

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                     PostgreSQL Extension                         │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    Cypher Engine                         │    │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐  │    │
│  │  │  Parser  │→│ Planner  │→│ Executor │→│  Result │  │    │
│  │  └──────────┘  └──────────┘  └──────────┘  └─────────┘  │    │
│  └─────────────────────────────────────────────────────────┘    │
│                              ▼                                   │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                 Property Graph Store                     │    │
│  │  ┌───────────┐  ┌───────────┐  ┌───────────────────┐    │    │
│  │  │   Nodes   │  │   Edges   │  │ Vector Embeddings │    │    │
│  │  │  (Labels) │  │  (Types)  │  │    (HNSW Index)   │    │    │
│  │  └───────────┘  └───────────┘  └───────────────────┘    │    │
│  └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
```

## Module Structure

```
src/
├── graph/
│   ├── mod.rs              # Module exports
│   ├── cypher/
│   │   ├── parser.rs       # Cypher parser (pest/nom)
│   │   ├── ast.rs          # Abstract syntax tree
│   │   ├── planner.rs      # Query planner
│   │   ├── executor.rs     # Query executor
│   │   └── functions.rs    # Built-in Cypher functions
│   ├── storage/
│   │   ├── nodes.rs        # Node storage
│   │   ├── edges.rs        # Edge storage
│   │   └── properties.rs   # Property storage
│   ├── traversal/
│   │   ├── bfs.rs          # Breadth-first search
│   │   ├── dfs.rs          # Depth-first search
│   │   ├── shortest_path.rs # Shortest path algorithms
│   │   └── vector_walk.rs  # Vector-guided traversal
│   ├── index/
│   │   ├── label_index.rs  # Label-based index
│   │   └── property_index.rs # Property index
│   └── operators.rs        # SQL operators
```

## SQL Interface

### Graph Schema Setup

```sql
-- Create a property graph
SELECT ruvector_create_graph('social_network');

-- Define node labels
SELECT ruvector_create_node_label('social_network', 'Person',
    properties := '{
        "name": "text",
        "age": "integer",
        "embedding": "vector(768)"
    }'
);

SELECT ruvector_create_node_label('social_network', 'Company',
    properties := '{
        "name": "text",
        "industry": "text",
        "embedding": "vector(768)"
    }'
);

-- Define edge types
SELECT ruvector_create_edge_type('social_network', 'KNOWS',
    properties := '{"since": "date", "strength": "float"}'
);

SELECT ruvector_create_edge_type('social_network', 'WORKS_AT',
    properties := '{"role": "text", "since": "date"}'
);
```

### Cypher Queries

```sql
-- Execute Cypher queries
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH (p:Person)-[:KNOWS]->(friend:Person)
    WHERE p.name = 'Alice'
    RETURN friend.name, friend.age
$$);

-- Create nodes
SELECT ruvector_cypher('social_network', $$
    CREATE (p:Person {name: 'Bob', age: 30, embedding: $embedding})
    RETURN p
$$, params := '{"embedding": [0.1, 0.2, ...]}');

-- Create relationships
SELECT ruvector_cypher('social_network', $$
    MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
    CREATE (a)-[:KNOWS {since: date('2024-01-15'), strength: 0.8}]->(b)
$$);

-- Pattern matching
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH (p:Person)-[:WORKS_AT]->(c:Company {industry: 'Tech'})
    RETURN p.name, c.name
    ORDER BY p.age DESC
    LIMIT 10
$$);
```

### Vector-Enhanced Graph Queries

```sql
-- Find similar nodes using vector search + graph structure
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH (p:Person)
    WHERE ruvector.similarity(p.embedding, $query) > 0.8
    RETURN p.name, p.age, ruvector.similarity(p.embedding, $query) AS similarity
    ORDER BY similarity DESC
    LIMIT 10
$$, params := '{"query": [0.1, 0.2, ...]}');

-- Graph-aware semantic search
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH (p:Person)-[:KNOWS*1..3]->(friend:Person)
    WHERE p.name = 'Alice'
    WITH friend, ruvector.similarity(friend.embedding, $query) AS sim
    WHERE sim > 0.7
    RETURN friend.name, sim
    ORDER BY sim DESC
$$, params := '{"query": [0.1, 0.2, ...]}');

-- Personalized PageRank with vector similarity
SELECT * FROM ruvector_cypher('social_network', $$
    CALL ruvector.pagerank('Person', 'KNOWS', {
        dampingFactor: 0.85,
        iterations: 20,
        personalizedOn: $seed_embedding
    })
    YIELD node, score
    RETURN node.name, score
    ORDER BY score DESC
    LIMIT 20
$$, params := '{"seed_embedding": [0.1, 0.2, ...]}');
```

### Path Finding

```sql
-- Shortest path
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH p = shortestPath((a:Person {name: 'Alice'})-[:KNOWS*1..6]-(b:Person {name: 'Bob'}))
    RETURN p, length(p)
$$);

-- All shortest paths
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH p = allShortestPaths((a:Person {name: 'Alice'})-[:KNOWS*1..6]-(b:Person {name: 'Bob'}))
    RETURN p, length(p)
$$);

-- Vector-guided path (minimize embedding distance along path)
SELECT * FROM ruvector_cypher('social_network', $$
    MATCH p = ruvector.vectorPath(
        (a:Person {name: 'Alice'}),
        (b:Person {name: 'Bob'}),
        'KNOWS',
        {
            maxHops: 6,
            vectorProperty: 'embedding',
            optimization: 'minTotalDistance'
        }
    )
    RETURN p, ruvector.pathEmbeddingDistance(p) AS distance
$$);
```

### Graph Algorithms

```sql
-- Community detection (Louvain)
SELECT * FROM ruvector_cypher('social_network', $$
    CALL ruvector.louvain('Person', 'KNOWS', {resolution: 1.0})
    YIELD node, communityId
    RETURN node.name, communityId
$$);

-- Node similarity (Jaccard)
SELECT * FROM ruvector_cypher('social_network', $$
    CALL ruvector.nodeSimilarity('Person', 'KNOWS', {
        similarityCutoff: 0.5,
        topK: 10
    })
    YIELD node1, node2, similarity
    RETURN node1.name, node2.name, similarity
$$);

-- Centrality measures
SELECT * FROM ruvector_cypher('social_network', $$
    CALL ruvector.betweenness('Person', 'KNOWS')
    YIELD node, score
    RETURN node.name, score
    ORDER BY score DESC
    LIMIT 10
$$);
```

## Implementation Phases

### Phase 1: Cypher Parser (Week 1-3)

```rust
// src/graph/cypher/parser.rs

use pest::Parser;
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "graph/cypher/cypher.pest"]
pub struct CypherParser;

/// Parse Cypher query string into AST
pub fn parse_cypher(query: &str) -> Result<CypherQuery, ParseError> {
    let pairs = CypherParser::parse(Rule::query, query)?;

    let mut builder = AstBuilder::new();
    for pair in pairs {
        builder.process(pair)?;
    }

    Ok(builder.build())
}

// src/graph/cypher/ast.rs

#[derive(Debug, Clone)]
pub enum CypherQuery {
    Match(MatchClause),
    Create(CreateClause),
    Merge(MergeClause),
    Delete(DeleteClause),
    Return(ReturnClause),
    With(WithClause),
    Compound(Vec<CypherQuery>),
}

#[derive(Debug, Clone)]
pub struct MatchClause {
    pub patterns: Vec<Pattern>,
    pub where_clause: Option<WhereClause>,
    pub optional: bool,
}

#[derive(Debug, Clone)]
pub struct Pattern {
    pub nodes: Vec<NodePattern>,
    pub relationships: Vec<RelationshipPattern>,
}

#[derive(Debug, Clone)]
pub struct NodePattern {
    pub variable: Option<String>,
    pub labels: Vec<String>,
    pub properties: Option<Properties>,
}

#[derive(Debug, Clone)]
pub struct RelationshipPattern {
    pub variable: Option<String>,
    pub types: Vec<String>,
    pub properties: Option<Properties>,
    pub direction: Direction,
    pub length: RelationshipLength,
}

#[derive(Debug, Clone)]
pub enum RelationshipLength {
    Exactly(usize),
    Range(Option<usize>, Option<usize>),  // *1..3
    Any,  // *
}
```

### Phase 2: Query Planner (Week 4-5)

```rust
// src/graph/cypher/planner.rs

pub struct QueryPlanner {
    graph_store: Arc<GraphStore>,
    statistics: Arc<GraphStatistics>,
}

impl QueryPlanner {
    pub fn plan(&self, query: &CypherQuery) -> Result<QueryPlan, PlanError> {
        let logical_plan = self.to_logical(query)?;
        let optimized = self.optimize(logical_plan)?;
        let physical_plan = self.to_physical(optimized)?;

        Ok(physical_plan)
    }

    fn to_logical(&self, query: &CypherQuery) -> Result<LogicalPlan, PlanError> {
        match query {
            CypherQuery::Match(m) => self.plan_match(m),
            CypherQuery::Create(c) => self.plan_create(c),
            CypherQuery::Return(r) => self.plan_return(r),
            // ...
        }
    }

    fn plan_match(&self, match_clause: &MatchClause) -> Result<LogicalPlan, PlanError> {
        let mut plan = LogicalPlan::Scan;

        for pattern in &match_clause.patterns {
            // Choose optimal starting point based on selectivity
            let start_node = self.choose_start_node(pattern);

            // Build expand operations
            for rel in &pattern.relationships {
                plan = LogicalPlan::Expand {
                    input: Box::new(plan),
                    relationship: rel.clone(),
                    direction: rel.direction,
                };
            }
        }

        // Add filter for WHERE clause
        if let Some(where_clause) = &match_clause.where_clause {
            plan = LogicalPlan::Filter {
                input: Box::new(plan),
                predicate: where_clause.predicate.clone(),
            };
        }

        Ok(plan)
    }

    fn optimize(&self, plan: LogicalPlan) -> Result<LogicalPlan, PlanError> {
        let mut optimized = plan;

        // Push down filters
        optimized = self.push_down_filters(optimized);

        // Reorder joins based on selectivity
        optimized = self.reorder_joins(optimized);

        // Use indexes where available
        optimized = self.apply_indexes(optimized);

        Ok(optimized)
    }
}

#[derive(Debug)]
pub enum LogicalPlan {
    Scan,
    NodeByLabel { label: String },
    NodeById { ids: Vec<u64> },
    Expand {
        input: Box<LogicalPlan>,
        relationship: RelationshipPattern,
        direction: Direction,
    },
    Filter {
        input: Box<LogicalPlan>,
        predicate: Expression,
    },
    Project {
        input: Box<LogicalPlan>,
        expressions: Vec<(String, Expression)>,
    },
    VectorSearch {
        label: String,
        property: String,
        query: Vec<f32>,
        k: usize,
    },
    // ...
}
```

### Phase 3: Query Executor (Week 6-8)

```rust
// src/graph/cypher/executor.rs

pub struct QueryExecutor {
    graph_store: Arc<GraphStore>,
}

impl QueryExecutor {
    pub fn execute(&self, plan: &QueryPlan) -> Result<QueryResult, ExecuteError> {
        match plan {
            QueryPlan::Scan { label } => self.scan_nodes(label),
            QueryPlan::Expand { input, rel, dir } => {
                let source_rows = self.execute(input)?;
                self.expand_relationships(&source_rows, rel, dir)
            }
            QueryPlan::Filter { input, predicate } => {
                let rows = self.execute(input)?;
                self.filter_rows(&rows, predicate)
            }
            QueryPlan::VectorSearch { label, property, query, k } => {
                self.vector_search(label, property, query, *k)
            }
            QueryPlan::ShortestPath { start, end, rel_types, max_hops } => {
                self.find_shortest_path(start, end, rel_types, *max_hops)
            }
            // ...
        }
    }

    fn expand_relationships(
        &self,
        source_rows: &QueryResult,
        rel_pattern: &RelationshipPattern,
        direction: &Direction,
    ) -> Result<QueryResult, ExecuteError> {
        let mut result_rows = Vec::new();

        for row in source_rows.rows() {
            let node_id = row.get_node_id()?;

            let edges = match direction {
                Direction::Outgoing => self.graph_store.outgoing_edges(node_id, &rel_pattern.types),
                Direction::Incoming => self.graph_store.incoming_edges(node_id, &rel_pattern.types),
                Direction::Both => self.graph_store.all_edges(node_id, &rel_pattern.types),
            };

            for edge in edges {
                let target = match direction {
                    Direction::Outgoing => edge.target,
                    Direction::Incoming => edge.source,
                    Direction::Both => if edge.source == node_id { edge.target } else { edge.source },
                };

                let target_node = self.graph_store.get_node(target)?;

                // Check relationship properties
                if let Some(props) = &rel_pattern.properties {
                    if !self.matches_properties(&edge.properties, props) {
                        continue;
                    }
                }

                let mut new_row = row.clone();
                if let Some(var) = &rel_pattern.variable {
                    new_row.set(var, Value::Relationship(edge.clone()));
                }
                new_row.extend_with_node(target_node);

                result_rows.push(new_row);
            }
        }

        Ok(QueryResult::from_rows(result_rows))
    }

    fn vector_search(
        &self,
        label: &str,
        property: &str,
        query: &[f32],
        k: usize,
    ) -> Result<QueryResult, ExecuteError> {
        // Use HNSW index for vector search
        let index = self.graph_store.get_vector_index(label, property)?;
        let results = index.search(query, k);

        let mut rows = Vec::with_capacity(k);
        for (node_id, score) in results {
            let node = self.graph_store.get_node(node_id)?;
            let mut row = Row::new();
            row.set("node", Value::Node(node));
            row.set("score", Value::Float(score));
            rows.push(row);
        }

        Ok(QueryResult::from_rows(rows))
    }
}
```

### Phase 4: Graph Storage (Week 9-10)

```rust
// src/graph/storage/nodes.rs

use dashmap::DashMap;
use parking_lot::RwLock;

/// Node storage with label-based indexing
pub struct NodeStore {
    /// node_id -> node data
    nodes: DashMap<u64, Node>,
    /// label -> set of node_ids
    label_index: DashMap<String, HashSet<u64>>,
    /// (label, property) -> property index
    property_indexes: DashMap<(String, String), PropertyIndex>,
    /// (label, property) -> vector index
    vector_indexes: DashMap<(String, String), HnswIndex>,
    /// Next node ID
    next_id: AtomicU64,
}

#[derive(Debug, Clone)]
pub struct Node {
    pub id: u64,
    pub labels: Vec<String>,
    pub properties: Properties,
}

impl NodeStore {
    pub fn create_node(&self, labels: Vec<String>, properties: Properties) -> u64 {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);

        let node = Node { id, labels: labels.clone(), properties: properties.clone() };

        // Add to main store
        self.nodes.insert(id, node);

        // Update label indexes
        for label in &labels {
            self.label_index
                .entry(label.clone())
                .or_insert_with(HashSet::new)
                .insert(id);
        }

        // Update property indexes
        for (key, value) in &properties {
            for label in &labels {
                if let Some(idx) = self.property_indexes.get(&(label.clone(), key.clone())) {
                    idx.insert(value.clone(), id);
                }
            }
        }

        // Update vector indexes
        for (key, value) in &properties {
            if let Value::Vector(vec) = value {
                for label in &labels {
                    if let Some(idx) = self.vector_indexes.get(&(label.clone(), key.clone())) {
                        idx.insert(id, vec);
                    }
                }
            }
        }

        id
    }

    pub fn nodes_by_label(&self, label: &str) -> Vec<&Node> {
        self.label_index
            .get(label)
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| self.nodes.get(id).map(|n| n.value()))
                    .collect()
            })
            .unwrap_or_default()
    }
}

// src/graph/storage/edges.rs

/// Edge storage with adjacency lists
pub struct EdgeStore {
    /// edge_id -> edge data
    edges: DashMap<u64, Edge>,
    /// node_id -> outgoing edges
    outgoing: DashMap<u64, Vec<u64>>,
    /// node_id -> incoming edges
    incoming: DashMap<u64, Vec<u64>>,
    /// edge_type -> set of edge_ids
    type_index: DashMap<String, HashSet<u64>>,
    /// Next edge ID
    next_id: AtomicU64,
}

#[derive(Debug, Clone)]
pub struct Edge {
    pub id: u64,
    pub source: u64,
    pub target: u64,
    pub edge_type: String,
    pub properties: Properties,
}

impl EdgeStore {
    pub fn create_edge(
        &self,
        source: u64,
        target: u64,
        edge_type: String,
        properties: Properties,
    ) -> u64 {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);

        let edge = Edge {
            id,
            source,
            target,
            edge_type: edge_type.clone(),
            properties,
        };

        // Add to main store
        self.edges.insert(id, edge);

        // Update adjacency lists
        self.outgoing.entry(source).or_insert_with(Vec::new).push(id);
        self.incoming.entry(target).or_insert_with(Vec::new).push(id);

        // Update type index
        self.type_index
            .entry(edge_type)
            .or_insert_with(HashSet::new)
            .insert(id);

        id
    }

    pub fn outgoing_edges(&self, node_id: u64, types: &[String]) -> Vec<&Edge> {
        self.outgoing
            .get(&node_id)
            .map(|edge_ids| {
                edge_ids.iter()
                    .filter_map(|id| self.edges.get(id))
                    .filter(|e| types.is_empty() || types.contains(&e.edge_type))
                    .map(|e| e.value())
                    .collect()
            })
            .unwrap_or_default()
    }
}
```

### Phase 5: Graph Algorithms (Week 11-12)

```rust
// src/graph/traversal/shortest_path.rs

use std::collections::{BinaryHeap, HashMap, VecDeque};

/// BFS-based shortest path
pub fn shortest_path_bfs(
    store: &GraphStore,
    start: u64,
    end: u64,
    edge_types: &[String],
    max_hops: usize,
) -> Option<Vec<u64>> {
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    let mut parents: HashMap<u64, u64> = HashMap::new();

    queue.push_back((start, 0));
    visited.insert(start);

    while let Some((node, depth)) = queue.pop_front() {
        if node == end {
            // Reconstruct path
            return Some(reconstruct_path(&parents, start, end));
        }

        if depth >= max_hops {
            continue;
        }

        for edge in store.edges.outgoing_edges(node, edge_types) {
            if !visited.contains(&edge.target) {
                visited.insert(edge.target);
                parents.insert(edge.target, node);
                queue.push_back((edge.target, depth + 1));
            }
        }
    }

    None
}

/// Dijkstra's algorithm for weighted shortest path
pub fn shortest_path_dijkstra(
    store: &GraphStore,
    start: u64,
    end: u64,
    edge_types: &[String],
    weight_property: &str,
) -> Option<(Vec<u64>, f64)> {
    let mut distances: HashMap<u64, f64> = HashMap::new();
    let mut parents: HashMap<u64, u64> = HashMap::new();
    let mut heap = BinaryHeap::new();

    distances.insert(start, 0.0);
    heap.push(Reverse((OrderedFloat(0.0), start)));

    while let Some(Reverse((OrderedFloat(dist), node))) = heap.pop() {
        if node == end {
            return Some((reconstruct_path(&parents, start, end), dist));
        }

        if dist > *distances.get(&node).unwrap_or(&f64::INFINITY) {
            continue;
        }

        for edge in store.edges.outgoing_edges(node, edge_types) {
            let weight = edge.properties
                .get(weight_property)
                .and_then(|v| v.as_f64())
                .unwrap_or(1.0);

            let new_dist = dist + weight;

            if new_dist < *distances.get(&edge.target).unwrap_or(&f64::INFINITY) {
                distances.insert(edge.target, new_dist);
                parents.insert(edge.target, node);
                heap.push(Reverse((OrderedFloat(new_dist), edge.target)));
            }
        }
    }

    None
}

/// Vector-guided path finding
pub fn vector_guided_path(
    store: &GraphStore,
    start: u64,
    end: u64,
    edge_types: &[String],
    vector_property: &str,
    max_hops: usize,
) -> Option<Vec<u64>> {
    let target_vec = store.nodes.get_node(end)?
        .properties.get(vector_property)?
        .as_vector()?;

    let mut heap = BinaryHeap::new();
    let mut visited = HashSet::new();
    let mut parents: HashMap<u64, u64> = HashMap::new();

    let start_vec = store.nodes.get_node(start)?
        .properties.get(vector_property)?
        .as_vector()?;

    let start_dist = cosine_distance(start_vec, target_vec);
    heap.push(Reverse((OrderedFloat(start_dist), start, 0)));

    while let Some(Reverse((_, node, depth))) = heap.pop() {
        if node == end {
            return Some(reconstruct_path(&parents, start, end));
        }

        if visited.contains(&node) || depth >= max_hops {
            continue;
        }
        visited.insert(node);

        for edge in store.edges.outgoing_edges(node, edge_types) {
            if visited.contains(&edge.target) {
                continue;
            }

            if let Some(vec) = store.nodes.get_node(edge.target)
                .and_then(|n| n.properties.get(vector_property))
                .and_then(|v| v.as_vector())
            {
                let dist = cosine_distance(vec, target_vec);
                parents.insert(edge.target, node);
                heap.push(Reverse((OrderedFloat(dist), edge.target, depth + 1)));
            }
        }
    }

    None
}
```

### Phase 6: PostgreSQL Integration (Week 13-14)

```rust
// src/graph/operators.rs

// Main Cypher execution function
#[pg_extern]
fn ruvector_cypher(
    graph_name: &str,
    query: &str,
    params: default!(Option<pgrx::JsonB>, "NULL"),
) -> TableIterator<'static, (name!(result, pgrx::JsonB),)> {
    let graph = get_or_create_graph(graph_name);

    // Parse parameters
    let parameters = params
        .map(|p| serde_json::from_value(p.0).unwrap_or_default())
        .unwrap_or_default();

    // Parse query
    let ast = parse_cypher(query).expect("Failed to parse Cypher query");

    // Plan query
    let plan = QueryPlanner::new(&graph).plan(&ast).expect("Failed to plan query");

    // Execute query
    let result = QueryExecutor::new(&graph).execute(&plan).expect("Failed to execute query");

    // Convert to table iterator
    let rows: Vec<_> = result.rows()
        .map(|row| (pgrx::JsonB(row.to_json()),))
        .collect();

    TableIterator::new(rows)
}

// Graph creation
#[pg_extern]
fn ruvector_create_graph(name: &str) -> bool {
    GRAPH_STORE.create_graph(name).is_ok()
}

// Node label creation
#[pg_extern]
fn ruvector_create_node_label(
    graph_name: &str,
    label: &str,
    properties: pgrx::JsonB,
) -> bool {
    let graph = get_graph(graph_name).expect("Graph not found");
    let schema: HashMap<String, String> = serde_json::from_value(properties.0)
        .expect("Invalid properties schema");

    graph.create_label(label, schema).is_ok()
}

// Edge type creation
#[pg_extern]
fn ruvector_create_edge_type(
    graph_name: &str,
    edge_type: &str,
    properties: pgrx::JsonB,
) -> bool {
    let graph = get_graph(graph_name).expect("Graph not found");
    let schema: HashMap<String, String> = serde_json::from_value(properties.0)
        .expect("Invalid properties schema");

    graph.create_edge_type(edge_type, schema).is_ok()
}

// Helper to get graph statistics
#[pg_extern]
fn ruvector_graph_stats(graph_name: &str) -> pgrx::JsonB {
    let graph = get_graph(graph_name).expect("Graph not found");

    pgrx::JsonB(serde_json::json!({
        "node_count": graph.node_count(),
        "edge_count": graph.edge_count(),
        "labels": graph.labels(),
        "edge_types": graph.edge_types(),
        "memory_mb": graph.memory_usage_mb(),
    }))
}
```

## Supported Cypher Features

### Clauses
- `MATCH` - Pattern matching
- `OPTIONAL MATCH` - Optional pattern matching
- `CREATE` - Create nodes/relationships
- `MERGE` - Match or create
- `DELETE` / `DETACH DELETE` - Delete nodes/relationships
- `SET` - Update properties
- `REMOVE` - Remove properties/labels
- `RETURN` - Return results
- `WITH` - Query chaining
- `WHERE` - Filtering
- `ORDER BY` - Sorting
- `SKIP` / `LIMIT` - Pagination
- `UNION` / `UNION ALL` - Combining results

### Expressions
- Property access: `n.name`
- Labels: `n:Person`
- Relationship types: `[:KNOWS]`
- Variable length: `[:KNOWS*1..3]`
- List comprehensions: `[x IN list WHERE x > 5]`
- CASE expressions

### Functions
- Aggregation: `count()`, `sum()`, `avg()`, `min()`, `max()`, `collect()`
- String: `toUpper()`, `toLower()`, `trim()`, `split()`
- Math: `abs()`, `ceil()`, `floor()`, `round()`, `sqrt()`
- List: `head()`, `tail()`, `size()`, `range()`
- Path: `length()`, `nodes()`, `relationships()`
- **RuVector-specific**:
  - `ruvector.similarity(embedding1, embedding2)`
  - `ruvector.distance(embedding1, embedding2, metric)`
  - `ruvector.knn(embedding, k)`

## Benchmarks

| Operation | Nodes | Edges | Time (ms) |
|-----------|-------|-------|-----------|
| Simple MATCH | 100K | 1M | 2.5 |
| 2-hop traversal | 100K | 1M | 15 |
| Shortest path (BFS) | 100K | 1M | 8 |
| Vector-guided path | 100K | 1M | 25 |
| PageRank (20 iter) | 100K | 1M | 450 |
| Community detection | 100K | 1M | 1200 |

## Dependencies

```toml
[dependencies]
# Link to ruvector-graph
ruvector-graph = { path = "../ruvector-graph", optional = true }

# Parser
pest = "2.7"
pest_derive = "2.7"

# Concurrent collections
dashmap = "6.0"
parking_lot = "0.12"

# Graph algorithms
petgraph = { version = "0.6", optional = true }
```

## Feature Flags

```toml
[features]
graph = []
graph-cypher = ["graph", "pest", "pest_derive"]
graph-algorithms = ["graph", "petgraph"]
graph-vector = ["graph", "index-hnsw"]
graph-all = ["graph-cypher", "graph-algorithms", "graph-vector"]
```