Vector, AI Retrieval, Spatial, ML & Graph
HNSW dense, SPLADE sparse (Block-Max WAND), ColBERT/MUVERA multi-vector MaxSim, R-Tree geo, in-engine GBDT & TreeSHAP, and graph edges.
SpydDB executes dense HNSW vector search, SPLADE learned sparse retrieval (sparse_vector + Block-Max WAND), ColBERT multi-vector late-interaction retrieval (multi_vector(D) + MUVERA FDE + exact MaxSim), R-Tree 2D geospatial queries, in-database Gradient Boosted Decision Tree (GBDT) training/scoring/TreeSHAP explainability, and graph traversals over standard transactional collections — all inside a single ACID/MVCC snapshot.
1. Dense HNSW, Sparse SPLADE & ColBERT Multi-Vector Retrieval#
Declare dense vector(dim) (up to 65,536 dimensions), learned sparse sparse_vector, and late-interaction multi_vector(dim) fields alongside full-text BM25 and geospatial indexes:
create collection catalog_items {
id: u64 primary auto_increment,
title: text not null,
description: text not null,
category: string(64) not null,
coords: geopoint,
embedding: vector(384) not null,
splade: sparse_vector,
token_vecs: multi_vector(128),
index idx_items_vec on (embedding) using hnsw,
index idx_items_sparse on (splade) using sparse,
index idx_items_colbert on (token_vecs) using colbert,
index idx_items_fts on (title, description) using fulltext,
index idx_items_geo on (coords) using geo
}Dense HNSW (nearest)#
Query top-$k$ nearest neighbors with nearest(field, $query_vec, k):
catalog_items
| where nearest(embedding, $1, 20)
| pick id, title, vector_similarity(embedding, $1) as score
| sort score desc
| take 10Learned Sparse Retrieval (sparse_vector + Block-Max WAND)#
Attach using sparse to a sparse_vector field for SPLADE / BM25-style learned sparse retrieval accelerated by Block-Max WAND dynamic pruning:
catalog_items
| where sparse_nearest(splade, $1, 20)
| pick id, title, sparse_dot(splade, $1) as lexical_score
| sort lexical_score desc
| take 10ColBERT Late-Interaction Retrieval (multi_vector(D) + MUVERA FDE)#
Attach using colbert (or using muvera) to a multi_vector(dim) column. Stage 1 narrows candidates with MUVERA Fixed-Dimensional Encoding and Stage 2 rescores with exact 8-lane unrolled maxsim:
catalog_items
| where nearest_maxsim(token_vecs, $1, 20)
| pick id, title, maxsim(token_vecs, $1) as colbert_score
| sort colbert_score desc
| take 10Vector, Sparse & Late-Interaction Math Functions#
| Function | Description |
|---|---|
vector_dot(a, b) | Dense dot product ($\sum a_i b_i$) |
vector_norm(a) | Euclidean $L_2$ norm ($\sqrt{\sum a_i^2}$) |
vector_distance(a, b) | Euclidean distance ($\sqrt{\sum (a_i - b_i)^2}$) |
vector_similarity(a, b) | Cosine similarity ($\frac{a \cdot b}{|a| |b|}$) |
vector_normalize(a) | Unit-normalized vector (returns zero vector unchanged on zero input) |
vector_centroid(v1, v2, ...) | Element-wise mean vector |
sparse_dot(a, b) | Inner product of two sparse_vector values |
sparse_nearest(col, q, k) | Top-$k$ Block-Max WAND sparse retrieval |
maxsim(doc_tokens, q_tokens) | Exact ColBERT late-interaction MaxSim score |
nearest_maxsim(col, q, k) | Two-stage MUVERA FDE + exact MaxSim top-$k$ retrieval |
2. R-Tree Geospatial Queries (geopoint & geo_within)#
Filter geographic points using indexed bounding boxes (geo_within(point, min_lat, min_lng, max_lat, max_lng)):
catalog_items
| where geo_within(coords, 37.70, -122.52, 37.82, -122.36)
| pick id, title, coords
| take 50All official SDKs provide native GeoPoint(lat, lng) value types (Vector / VectorValue for embeddings).
3. Hybrid 4-Model Omni Query (One Snapshot)#
Combine HNSW vector search, BM25 full-text search, R-Tree geospatial bounding, and relational filtering in a single query plan — intersecting index candidate sets under one consistent MVCC snapshot and security context:
with semantic_hits as (
catalog_items | where nearest(embedding, $1, 50) | pick id
)
| catalog_items
| where id in (semantic_hits | pick id)
and match(description, "wireless mechanical")
and geo_within(coords, 37.60, -122.60, 37.90, -122.20)
and category == "peripherals"
| pick id, title, vector_similarity(embedding, $1) as relevance
| sort relevance desc
| take 10Run explain to inspect the candidate-set intersection across HNSW, Full-Text BM25, and Geo indexes.
4. In-Engine ML: GBDT Training, Scoring, Probabilities & TreeSHAP#
Train, store, score, and explain models directly inside SpydQL queries without exporting sensitive PII, financial transactions, or tenant-scoped records to an external inference server.
Supported Model Kinds#
- Linear & Logistic (
linear,logistic) and Decision Lists (decision_list) - Gradient Boosted Decision Trees (
gbdt):- Regression:
ml_train_gbdt(vector_field[, n_estimators[, max_depth]]) - Binary Logistic Classification:
ml_train_gbdt_classifier(vector_field[, n_estimators[, max_depth]]) - Multi-Class Softmax Classification:
ml_train_gbdt_multiclass(vector_field, num_classes[, n_estimators[, max_depth]]) - Supports categorical split bitsets (
CategoricalSplit) alongside numeric histogram splits - Supports XGBoost and LightGBM JSON model import so externally trained ensembles score natively inside SpydDB
- Uses a per-query parsed model cache so repeated row evaluations avoid reparsing model JSON
- Regression:
Training GBDT Models in SpydQL#
Pack feature values plus the target label as the final element of a vector(N) column and fit globally or per group (e.g., per region or tenant):
-- 1. Binary fraud classifier (40 trees, max depth 4)
tx_history
| agg ml_train_gbdt_classifier(features, 40, 4) as fraud_model
-- 2. Multi-class softmax triage classifier (3 classes: allow, review, block)
triage_train
| agg ml_train_gbdt_multiclass(features, 3, 25, 3) as triage_model
-- 3. Regression reranker / price estimator
rag_judgments
| agg ml_train_gbdt(features, 35, 4) as reranker_model
-- 4. Per-region models in one grouped aggregation
regional_tx
| group by region
| agg ml_train_gbdt_classifier(features, 25, 3) as regional_model
| sort regionScoring, Probabilities & Exact TreeSHAP (ml_score, ml_class, ml_proba, ml_explain)#
-- Score, classify, extract softmax probabilities, and compute exact TreeSHAP explanations
models
| join orders on true
| where models.name == "fraud_triage_v2"
| pick orders.id,
ml_class(models.body, orders.amount, orders.velocity, orders.country_code) as tier,
ml_proba(models.body, orders.amount, orders.velocity, orders.country_code) as class_probs,
ml_explain(models.body, orders.amount, orders.velocity, orders.country_code) as shap_json
| sort orders.id desc
| take 25| Function | Return Value |
|---|---|
ml_score(model, x1, ...) | Numeric score (regression value, binary probability, or winning class score) |
ml_class(model, x1, ...) | Predicted class label (bool for binary classifiers, integer class index for multi-class) |
ml_proba(model, x1, ...) | JSON array of class probabilities (e.g. [0.04, 0.19, 0.77]) |
ml_explain(model, x1, ...) | Deterministic exact TreeSHAP JSON (base_value, prediction, contributions, check_sum_error) |
Fail-Closed Null Rule: Unlike standard arithmetic operators,
ml_score,ml_class,ml_proba, andml_explainfail immediately onNULLfeature inputs rather than silently coercing missing features to zero. Wrap nullable columns explicitly withcoalesce(col, fallback).
Fitting Linear Models Per Group (ml_train)#
training_samples
| group by segment
| agg ml_train(features) as fitted_model5. Graph Analytics Over Edge Collections#
Model graphs as standard transactional edge collections so every edge automatically receives ACID commits, tenant partitioning, row policies, backups, and PITR:
create collection service_edges {
id: u64 primary auto_increment,
from_node: string(120) not null,
to_node: string(120) not null,
weight: f64 not null default 1.0,
index idx_from on from_node,
index idx_to on to_node
}Traverse multi-hop neighborhoods via recursive CTE pipelines or query graph edges directly for dependency maps, shortest paths, connected components, cycles, and PageRank analysis.