# How VelesQL Supports Graph Queries and Pattern Matching in VelesDB

> Discover how VelesQL enables powerful graph queries and pattern matching in VelesDB using a Cypher-style MATCH clause, AST execution, and versatile API access.

- Repository: [Wiscale/velesdb](https://github.com/cyberlife-coder/velesdb)
- Tags: how-to-guide
- Published: 2026-02-28

---

**VelesQL implements a Cypher-style `MATCH` clause that parses node and relationship patterns into an AST, executes them via `execute_match()` or hybrid vector-aware `execute_match_with_similarity()`, and exposes results through REST and WASM APIs.**

VelesQL extends the VelesDB query engine with native graph semantics through its dedicated `MATCH` clause, enabling complex pattern matching across nodes and relationships. This implementation, found in the `cyberlife-coder/velesdb` repository, bridges traditional property graph traversal with modern vector similarity search, providing both server-side execution and client-side WASM support.

## The MATCH Clause Architecture

The graph query capability is structured across three distinct layers: parsing, execution planning, and API exposure.

### Parsing Layer

When `Parser::parse()` encounters a `MATCH` statement, it delegates to the dedicated match clause parser in [`crates/velesdb-core/src/velesql/parser/match_clause.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/velesql/parser/match_clause.rs). This module constructs a `MatchClause` AST containing node patterns with aliases, labels, and property constraints; relationship patterns with directionality and variable-length path specifications; optional `WHERE` filters; and `RETURN` projections.

### Execution Engine

The core engine translates `MatchClause` into executable plans via two primary entry points in [`crates/velesdb-core/src/collection/search/query/match_exec/mod.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/collection/search/query/match_exec/mod.rs):

- **`execute_match()`** – Pure graph pattern matching based on node labels, relationship types, and property constraints without vector scoring.
- **`execute_match_with_similarity()`** – Hybrid execution that combines pattern matching with vector similarity search, defined in [`crates/velesdb-core/src/collection/search/query/match_exec/similarity.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/collection/search/query/match_exec/similarity.rs).

### API Exposure

The functionality surfaces through multiple interfaces:

- **HTTP API** – The `match_query` handler in [`crates/velesdb-server/src/handlers/match_query.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-server/src/handlers/match_query.rs) processes POST requests to `/collections/{name}/match`, validating VelesQL syntax and forwarding execution to the core engine.
- **WASM Graph Store** – For client-side applications, [`crates/velesdb-wasm/src/graph.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-wasm/src/graph.rs) provides the `GraphStore` type with in-memory storage and traversal methods including `bfs_traverse()`, `dfs_traverse()`, and `get_neighbors()`.

## Pattern Matching Mechanics

VelesQL implements Cypher-compatible pattern semantics for nodes and relationships.

### Node Patterns

The parser recognizes syntax such as `(<alias>:Label1:Label2 {prop: value})` and maps it to `NodePattern` structures holding an optional alias, a list of label constraints, and a map of property constraints.

### Relationship Patterns

Relationship patterns like `-[:TYPE*1..3 {prop: v}]->` become `RelationshipPattern` objects specifying direction (incoming, outgoing, or undirected), optional type constraints, variable-length path ranges, and property filters.

### WHERE and RETURN Clauses

The `WHERE` clause converts into a boolean `Condition` tree supporting property comparisons and built-in functions like `similarity()`. The `RETURN` clause drives projection, with the executor materializing specified expressions into JSON values attached to each result row.

## Hybrid Graph and Vector Search

The `execute_match_with_similarity()` function enables semantic graph traversal. When provided with a query vector and similarity threshold, the executor first runs the pattern matcher to obtain candidate node bindings, then computes cosine similarity (or the configured metric) between the query vector and stored node embeddings. Only matches with a score meeting the threshold survive, and the score is attached to the result via the `score` field.

This bridges property graph patterns with vector similarity, enabling queries that find semantically similar nodes within specific graph structures.

## Practical Implementation Examples

### Rust Core Library

```rust
use velesdb_core::velesql::Parser;
use velesdb_core::collection::Collection;

// Assume `collection` is an opened Collection handle
let query_str = "MATCH (p:Person)-[:KNOWS]->(f:Person) \
                 WHERE similarity(p.vec, $v) > 0.8 \
                 RETURN p.name, f.name";

let parsed = Parser::parse(query_str).expect("valid VelesQL");
let match_clause = parsed.match_clause.unwrap(); // guaranteed by `is_match_query()`

// Parameters: vector `v` and any other placeholders
let mut params = std::collections::HashMap::new();
params.insert("v".to_string(), serde_json::json!([0.1, 0.2, 0.3]));

let results = collection
    .execute_match_with_similarity(&match_clause, &[0.1, 0.2, 0.3], 0.8, &params)
    .expect("execution succeeded");

// Inspect bindings and scores
for item in results {
    println!("Person {} knows {}", 
             item.projected["p.name"], 
             item.projected["f.name"]);
    println!("Similarity score: {:.2}", item.score.unwrap());
}

```

### WASM GraphStore

```javascript
import init, { GraphStore, GraphNode, GraphEdge } from 'velesdb-wasm';

// Initialise the WASM module (await init())
const store = new GraphStore();

// Add nodes
store.add_node(new GraphNode(1, "Person"));
store.add_node(new GraphNode(2, "Person"));
store.add_node(new GraphNode(3, "Document"));

// Add edges (KNOWS)
store.add_edge(GraphEdge.new(1, 1, 2, "KNOWS"));

// Simple 1‑hop neighbor lookup
const neighbors = store.get_neighbors(1); // → [2]

// BFS traversal up to depth 3, limit 10 results
store.bfs_traverse(1, 3, 10).then(res => {
    console.log("BFS result:", res); // array of [nodeId, depth] tuples
});

```

### HTTP API

```bash
curl -X POST https://api.velesdb.com/collections/mygraph/match \
     -H "Content-Type: application/json" \
     -d '{
           "query": "MATCH (a:Article)-[:TAGGED]->(t:Tag) RETURN a.title, t.name",
           "params": {}
         }'

```

Response (JSON):

```json
{
  "results": [
    {
      "bindings": { "a": 42, "t": 7 },
      "projected": { "a.title": "Graph Databases", "t.name": "Veles" },
      "depth": 1
    },
    { "bindings": { "a": 43, "t": 8 }, … }
  ],
  "took_ms": 12,
  "count": 2,
  "meta": { "velesql_contract_version": "0.6.1" }
}

```

## Summary

- VelesQL implements **Cypher-style `MATCH` clauses** through a dedicated parser in [`match_clause.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/match_clause.rs) that builds AST representations of node and relationship patterns.
- The execution layer provides **`execute_match()`** for pure graph traversal and **`execute_match_with_similarity()`** for hybrid vector-graph search, enabling semantic pattern matching.
- Pattern syntax supports **variable-length paths**, **property filters**, **WHERE conditions**, and **RETURN projections**, matching industry-standard graph query capabilities.
- Developers can access graph queries via **Rust core library**, **HTTP REST API** (`/collections/{name}/match`), or **WASM GraphStore** for client-side traversal.

## Frequently Asked Questions

### What graph query syntax does VelesQL support?

VelesQL implements a Cypher-compatible `MATCH` clause supporting node patterns with labels and properties, directed and undirected relationship patterns, variable-length paths using `*min..max` syntax, and standard `WHERE` and `RETURN` clauses. The parser in [`crates/velesdb-core/src/velesql/parser/match_clause.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/velesql/parser/match_clause.rs) converts this syntax into a `MatchClause` AST for execution.

### How does VelesQL combine graph pattern matching with vector search?

The `execute_match_with_similarity()` function in [`crates/velesdb-core/src/collection/search/query/match_exec/similarity.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/collection/search/query/match_exec/similarity.rs) first evaluates the graph pattern to identify candidate nodes, then computes cosine similarity between the query vector and stored node embeddings. Results are filtered by the similarity threshold and returned with a `score` field, enabling semantic graph traversal queries.

### Can I use VelesQL graph queries in a browser environment?

Yes, the `velesdb-wasm` crate provides a `GraphStore` type in [`crates/velesdb-wasm/src/graph.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-wasm/src/graph.rs) that supports in-memory graph storage and traversal methods including `bfs_traverse()`, `dfs_traverse()`, and `get_neighbors()`. This allows client-side JavaScript applications to perform graph operations and pattern matching without server round-trips.

### What is the difference between `execute_match()` and `execute_match_with_similarity()`?

`execute_match()` in [`crates/velesdb-core/src/collection/search/query/match_exec/mod.rs`](https://github.com/cyberlife-coder/velesdb/blob/main/crates/velesdb-core/src/collection/search/query/match_exec/mod.rs) performs pure graph pattern matching based on node labels, relationship types, and property constraints without vector scoring. In contrast, `execute_match_with_similarity()` augments this with vector similarity calculations, requiring a query vector and threshold parameter to filter results by semantic relevance.