How VelesQL Supports Graph Queries and Pattern Matching in VelesDB
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. 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:
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 incrates/velesdb-core/src/collection/search/query/match_exec/similarity.rs.
API Exposure
The functionality surfaces through multiple interfaces:
- HTTP API – The
match_queryhandler incrates/velesdb-server/src/handlers/match_query.rsprocesses 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.rsprovides theGraphStoretype with in-memory storage and traversal methods includingbfs_traverse(),dfs_traverse(), andget_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
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, ¶ms)
.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
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
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):
{
"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
MATCHclauses through a dedicated parser inmatch_clause.rsthat builds AST representations of node and relationship patterns. - The execution layer provides
execute_match()for pure graph traversal andexecute_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 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 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 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 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.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →