Built-in Functions Reference
Complete catalog of string, math, temporal, vector, geo, JSON, HSTORE, range, array, IP/CIDR, and ML scoring functions.
SpydDB evaluates every scalar function natively inside the expression VM (and accelerates eligible numeric operators with native Cranelift JIT). Standard operators mirror both SpydQL and PostgreSQL Wire SQL.
Note: Dedicated full-text search and relevance functions (
match,search,score,multi_match,fuzzy_match,phrase_match,highlight*,snippet*,rrf,hybrid_score) are documented in depth in the Full-Text Search & Hybrid Ranking manual.
1. String & Text Functions#
| Function | Signature | Behavior & Return Type |
|---|---|---|
lower / upper | lower(text) -> text | ASCII/UTF-8 lowercase or uppercase conversion |
trim / ltrim / rtrim | trim(text) -> text | Strips leading and/or trailing whitespace |
length | length(text) -> i64 | Character length (null input returns null) |
substring | substring(text, start [, len]) -> text | 1-based character offset extraction (optional length) |
left / right | left(text, n) -> text | First or last n characters (clamped to string length) |
concat | concat(a, b, ...) -> text | Concatenates values into text (skips null arguments, matching PostgreSQL) |
replace | replace(text, from, to) -> text | Exact substring substitution |
starts_with / ends_with / contains | starts_with(text, prefix) -> bool | Substring/affix predicate checks |
contains_token | contains_token(text, token) -> bool | Token-boundary check using the full-text analyzer |
domain | domain(email_or_url) -> text | Extracts domain suffix from email or URL strings |
tokenize | tokenize(text) -> text | Deterministic keyed pseudonymization token for dynamic field masking |
like / not like | col like "prod-%" | Linear-time % / _ wildcard matching |
users
| extend
lower(trim(email)) as normalized,
domain(email) as mail_domain,
concat(left(first_name, 1), left(last_name, 1)) as initials
| where starts_with(normalized, "ada") and length(normalized) > 5
| pick id, normalized, mail_domain, initials;2. Math, Finance & Control Flow#
| Function | Description & Semantics |
|---|---|
abs(x) | Absolute value with checked overflow handling |
round(x [, digits]), floor(x), ceil(x) | Rounding & truncation for f64 and fixed-scale decimal |
sqrt(x), power(base, exp) | Checked floating-point power/root evaluation |
greatest(a, b, ...), least(a, b, ...) | Returns max/min across expressions |
coalesce(a, b, ...) | Returns first non-null value |
nullif(a, b) | Returns null when a == b, otherwise a |
balance_delta(balance, min, max, delta) | Checked bounded ledger arithmetic—errors if intermediate or resulting balance steps outside [min, max] |
Example atomic bounded ledger update:
accounts
| where id == 42
| set { balance_cents: balance_delta(balance_cents, 0, 10000000, -2500) }
| returning id, balance_cents;3. Date, Time & Duration Functions#
Time literals support unquoted human duration suffixes: ns, us, ms, s, m, h, d, w (e.g., 15m, 1h, 7d).
| Function | Signature | Description |
|---|---|---|
now() | -> timestamp | Current transaction UTC timestamp at microsecond resolution |
time_bucket(ts, duration) | -> timestamp | Floors instant to aligned bucket boundaries (e.g. time_bucket(created_at, 5m)) |
date_trunc(unit, ts) | -> timestamp | Truncates to "second", "minute", "hour", "day", "week" (Monday-aligned), "month", "year" |
extract(field, ts) | -> i64 | Extracts "year", "month", "day", "hour", "minute", "second", "dow" (1..7), "doy" (1..366), or "epoch" (seconds) |
events
| where created_at >= now() - 24h
| extend date_trunc("hour", created_at) as hour_bucket, extract("dow", created_at) as dow
| group by hour_bucket
| agg count() as events
| sort hour_bucket asc;4. JSON & HSTORE Functions#
JSON Navigation#
- Inline path syntax:
payload.customer.tier,payload.items[0].sku(0-based indexing inside dynamic JSON arrays) json_get(doc, path): Extracts structured nested JSON value at a dot-separated pathjson_text(doc, path): Extracts JSON scalar rendered cleanly astext(returnsnullwhen missing or JSONnull)
HSTORE Key-Value Inspection#
| Function | Signature | Return Type |
|---|---|---|
hstore_get(map, key) | Retrieves string value for key (or null) | text |
hstore_has_key(map, key) | Checks whether key exists (even if its value is null) | bool |
hstore_keys(map) | Returns all keys | text[] |
hstore_values(map) | Returns all values | text[] |
5. Array Functions#
Typed arrays (text[], u64[], etc.) use 1-based indexing (arr[1]). Out-of-bounds or arr[0] evaluate to null.
| Function | Description |
|---|---|
array_length(arr) | Number of elements (u64/i64) in arr (null if arr is null) |
array_contains(arr, elem) | Boolean membership check preserving typed equality rules |
Combine with the unnest pipeline operator (| unnest tags as tag) to expand arrays into individual relational rows.
6. Range Functions#
Construct ranges ([lower, upper)) and query bounds without manual boundary math:
| Function | Signature | Purpose |
|---|---|---|
int4range(lo, hi) | -> int4range | Construct validated 32-bit signed integer range (lo <= hi) |
int8range(lo, hi) | -> int8range | Construct validated 64-bit signed integer range |
daterange(lo, hi) | -> daterange | Construct validated calendar date range |
tsrange(lo, hi) | -> tsrange | Construct validated microsecond timestamp range |
range_contains(r, val) | -> bool | true when val lies inside range bounds |
range_overlaps(a, b) | -> bool | true when two ranges of matching kind share any point |
lower(r) / upper(r) | -> scalar | Extracts range lower or upper endpoint (null if unbounded) |
is_empty(r) | -> bool | true when the range encloses zero values |
7. Vector & In-Engine ML Functions#
| Function | Arguments & Purpose |
|---|---|
nearest(col, vec, k) | Exact top-k index/scan predicate pairing with vector(dim) collections |
vector_distance(a, b) | Euclidean L2 distance between two equal-length vectors |
vector_similarity(a, b) | Cosine similarity ([-1.0, 1.0]) |
vector_dot(a, b) | Exact f64 dot product |
vector_norm(a) | L2 vector magnitude |
vector_normalize(a) | Returns unit-normalized vector |
vector_centroid(a, b, ...) | Element-wise mean vector across two or more vectors |
sparse_dot(a, b) | Inner product of two sparse_vector values |
sparse_nearest(col, q, k) | Top-k SPLADE Block-Max WAND sparse vector retrieval predicate |
maxsim(doc_tokens, q_tokens) | Exact ColBERT late-interaction MaxSim score (f64) |
nearest_maxsim(col, q, k) | Two-stage MUVERA FDE + exact MaxSim multi-vector top-k predicate |
ml_score(model_json, feat1, ...) | Deterministic in-engine linear/logistic/decision-list/GBDT/XGBoost/LightGBM inference score (f64) |
ml_class(model_json, feat1, ...) | Predicted class label (bool for binary classifiers, integer class index for multi-class GBDT) |
ml_proba(model_json, feat1, ...) | JSON array of class probabilities (softmax for multi-class GBDT, [1-p, p] for binary) |
ml_explain(model_json, feat1, ...) | Deterministic exact TreeSHAP JSON attribution (base_value, prediction, contributions, check_sum_error) |
rrf(rank1, rank2 [, k]) | Reciprocal Rank Fusion score (default k = 60) for hybrid retrieval |
hybrid_score(score1, score2 [, alpha]) | Weighted linear fusion (default alpha = 0.5) |
Pair inference with the in-database training aggregates ml_train(features), ml_train_gbdt(features[, n_estimators[, max_depth]]), ml_train_gbdt_classifier(features[, n_estimators[, max_depth]]), and ml_train_gbdt_multiclass(features, num_classes[, n_estimators[, max_depth]]) (see Vector, Spatial, ML & Graph).
8. Geospatial Functions#
| Function | Signature & Behavior |
|---|---|
geo_distance(p1, p2) | Haversine great-circle distance in meters between two geo_point values |
geo_within(pt, s, w, n, e) | Axis-aligned latitude/longitude bounding-box check |
geo_contains(poly, pt) | Point-in-polygon check for geo_polygon shapes |
geo_radius(pt, lat, lng, meters) | Radius filter centered on (lat, lng) in meters |
geo_near(pt, lat, lng, k) | Spatial top-k nearest-neighbor scan predicate (R-Tree cell index accelerated) |