HQL reference

This is the complete grammar, for looking things up. To learn querying step by step, start with Querying data; the Query API runs queries and returns this same reference as markdown.

HQL is the language for querying and deleting Hilus entities: one string of pipe-separated clauses that filters, searches, combines conditions, aggregates and deletes. Named parameters (:name) take their values from the params sent with the query.

String DSL Syntax

<Entity> [@ <branch>] | <clause> | <clause> ...

Basic Structure

Component Description Example
Entity The entity type to query Call, Message, Document
Branch Optional branch name (bare / - . _ allowed, or quoted) @ main, @ feature/my-change
Clause Filter, search, or control clause status = "active"

Comparison Operators

Operator Description Example
= Equal status = "active"
!= Not equal status != "completed"
> Greater than end_time - start_time > 180
>= Greater than or equal created_at >= "2024-01-01"
< Less than score < 0.5
<= Less than or equal count <= 100

Set Operators

Operator Description Example
in Value in set status in ("active", "pending")
not in Value not in set status not in ("deleted", "archived")

A list may be written in brackets too: status in ["active", "pending"] is the same list.


Members of Lists of Objects

A field that holds a list of objects can be traversed by member name:

# At least one tool call has this name
Call | conversation.messages.tool_calls.name = "Call_transfer_call"

# No tool call on any message has this name
Call | conversation.messages.tool_calls.name != "Call_transfer_call"

# Return tool names in message/tool-call order
Call | select conversation.messages.tool_calls.name

Positive operators (=, in, comparisons, like/ilike, regex, exists) mean at least one list element matches. Negative operators (!=, not in, negative regex, not exists) mean no list element matches and therefore include null or empty lists.

The equivalent literal-left membership spellings are also accepted: "Call_transfer_call" in conversation.messages.tool_calls.name and "Call_transfer_call" not in conversation.messages.tool_calls.name.

Lists inside list items, and entity references

A member that is itself a list of objects is walked the same way: the condition holds when some inner item of some outer item matches, and negative operators mean no inner item anywhere matches.

An entity reference stored inside such an object (written as {entity_type: Agent, id: "..."}, stored as a reference marker) exposes id and entity_type, matched without loading the referenced entity. A list of references works the same way. Other members of a reference are not reachable from here; query the referenced type itself.

# Calls where an AI agent handled a segment (:id is a named parameter)
Call | segments.agent.id = :id
Call | segments.phone_tree.id = :id
# The line reached can reach this person (direct or shared line)
Call | segments.line_parties.id = :id
# The person was heard in a segment (list inside a list item)
Call | segments.participants.party.id = :id
# Any segment with an agent at all
Call | segments.agent.entity_type = "Agent"

# Projection: one value per segment; an inner list gives one array per segment
Call | select id, segments.agent.id, segments.participants.party.id

Null Checks

Operator Description Example
is null Field is null conversation is null
is not null Field is not null recording is not null

Pattern Matching

Operator Description Example
like SQL LIKE (case-sensitive) name like "John%"
ilike SQL ILIKE (case-insensitive) email ilike "%@gmail.com"
not like / not ilike No match; the same as NOT (name like ...) email not ilike "%@gmail.com"

not goes in front of like, ilike, contains, startswith and between the same way.

Wildcards:

Performance: like/ilike do NOT use the full-text search indexes — they scan every row in scope (and on list fields like Message.content, every list element), which can hit the statement timeout over long time windows. If you are searching for a word or name rather than an arbitrary substring, use the indexed fulltext operator instead: content ~* "Smith" (fast) vs content ilike "%Smith%" (slow). Reserve like/ilike for cases that need exact substring/wildcard semantics on a narrow, well-filtered row set.


Search Operators

Semantic and fulltext search on indexed fields: text, and the text read from stored files (see "Field-less search, match, and *" below).

Operator Type Description Example
~= Vector Semantic similarity search content ~= "appointment cancellation"
~~ Hybrid Combined vector + fulltext content ~~ "cardiac symptoms"
~* Fulltext Keyword/token matching content ~* "urgent"
*~ Phrase Phrase search (word order matters) content *~ "looking for my pet"

Similarity threshold (optional suffix): content ~= "refill request" >= 0.5 restricts vector/hybrid matches to a minimum similarity (0.0–1.0).

Ranking vs predicate — how position changes meaning

The SAME operator compiles to two different operations depending on where it appears:

Predicate-context rules:

Field-less search, match, and *

Text-bearing fields (strings, list strings, pdf / audio / image / file dtypes, text members of nested objects) are chunk-indexed: their text is split into passages that are embedded and full-text indexed. Search operators rank an entity by its best passage.

Files stored inside the items of a list field (a ticket's attachments[].file) are chunk-indexed too: search the member path, or the bare list field when it holds exactly one file member. ~*, *~, ~= and ~~ all read the passages. The text of a scanned pdf, an image or an audio clip is added after its OCR or transcription runs in the background, so it can be matched a little later than the save.

SupportTicket | attachments ~* "invoice"            same as attachments.file ~* "invoice"
SupportTicket | attachments.file ~~ "refund policy" | select id, attachments.file.chunks{text,score}
Message | content ~~ "refill"            search one field
Message | ~~ "refill"                    search EVERY chunk-indexed field of Message  (== Message | match ~~ "refill")
* | ~~ "refill" | limit 10               search every chunk-indexed entity in the org

match is the best passage of the query's (single) search — available whether the field was named or not:

Message | content ~~ "refill" | select id, match.text, match.score
* | ~~ "rabies certificate" | select _concrete_type, id, match.field, match.text, match.score | limit 10

A chunk record has the members text score idx start end meta hash dtype field. start/end place the passage in its value: for text and for a pdf they are line indices counted from 0, end being the line after the passage (in a pdf, lines of its read text, not pages); for audio they are seconds; a picture is one passage, 0 to 1. meta holds what else the source records about the passage: for a pdf its page, counted from 0; for audio the utterances with their speaker and channel. dtype is the source dtype of the passage (string, markdown, pdf, image, audio, file, …); field the column it came from. The same record type backs <field>.chunks (all passages of a field):

Document | lines ~~ "vaccines" | select id, lines.chunks{text,score}             all chunks, best first when a score is asked for
Document | lines ~~ "vaccines" | flatten lines.chunks | order by lines.chunks.score desc | select lines.chunks.start, lines.chunks.text

* needs exactly one ranking search and projects the BaseEntity built-ins (id, created_at, …), _concrete_type and match.*.

Dtype filters — "has a pdf" vs "the hit is in a pdf"

Message | content.dtype = "pdf"                    the value / ANY list item is a pdf (hash-prefix test, no index needed)
Message | content.dtype IN ("image", "file")       literals are validated against the field's declared dtypes
Message | content.dtype != "image"                 no item is an image
Message | ~~ "rabies" | match.dtype = "pdf"        the matching PASSAGE is inside a pdf (pushed into the search probe)
Message | content.chunks.dtype = "image"           any passage of the field is an image

The literals are dtype names (pdf, image, audio, file, …). A match.dtype / <field>.chunks.dtype equality in the same AND as the search narrows the probe itself (no top-K starvation); anywhere else it is a chunk-existence predicate.

Size

<field>.size.<measure> is the size of the value behind a chunk-indexed field: chars (text length), items (list length), pages (the page count of a PDF document), seconds (where the transcript of a recording ends), bytes (blob size, when known). pages and seconds come from the read text and the transcript, so they arrive with the text, a little after the save. Filter, order, select; also on the matched passage's field as match.size.<measure>.

Fax | pdf.size.pages > 30 | order by pdf.size.pages desc | select id, pdf.size{pages,bytes}
Call | recording.size.seconds > 1800
Document | lines.size.chars > 20000 AND lines ~~ "referral"
* | ~~ "referral" | match.dtype = "pdf" AND match.size.pages > 30

Regex Operators

PostgreSQL regular expression matching.

Operator Description Example
=~ Regex match (case-sensitive) name =~ "^John"
=~* Regex match (case-insensitive) name =~* "^john"
!~ Regex NOT match (case-sensitive) name !~ "^Test"
!~* Regex NOT match (case-insensitive) name !~* "^test"

Boolean Logic

Combine conditions with AND, OR, NOT, and parentheses.

Operator Description Example
AND Both conditions must be true status = "active" AND score > 0.8
OR Either condition must be true status = "active" OR status = "pending"
NOT Negate a condition NOT status = "deleted"
() Group conditions (a = 1 OR b = 2) AND c = 3

Precedence: NOT > AND > OR (use parentheses to override)

Examples

# OR
Call | status = "active" OR status = "pending"

# AND (explicit)
Call | status = "active" AND created_at >= "2024-01-01"

# Complex boolean
Call | (status = "active" OR status = "pending") AND NOT provider = "test"

Range Operators

Operator Description Example
BETWEEN Value in range (inclusive) created_at BETWEEN "2024-01-01" AND "2024-12-31"

Smart Date Parsing

Date values are automatically normalized to ISO format. All these formats work:

# All equivalent - parsed to 2025-05-01
Call | created_at >= "05/1/2025"
Call | created_at >= "5/1/2025"
Call | created_at >= "May 1, 2025"
Call | created_at >= "1 May 2025"
Call | created_at >= "2025-05-01"

# With time
Call | created_at >= "2025-05-01T10:30:00"

# An age
Call | created_at >= "3 days ago"
Call | created_at >= "2 hours ago"

An age ("N minutes/hours/days/weeks ago") is resolved when the query runs. Words such as "yesterday" or "last week" are not understood: a date field refuses them and names the forms it takes; write NOW() - INTERVAL "1 day" instead (next section). Time fields (moment) compare instants; the moment page says how a value without an offset or zone is read.

Relative Date/Time Expressions

Use NOW() and INTERVAL for relative time filters directly in HQL:

# Messages from the last 15 minutes
Message | created_at >= NOW() - INTERVAL "15 minutes"

# Calls from the last 7 days
Call | created_at >= NOW() - INTERVAL "7 days"

# Upcoming appointments in the next 2 hours
Call | scheduled_at <= NOW() + INTERVAL "2 hours"

# Just NOW() as a value
Call | created_at <= NOW()

Supported interval units: seconds, minutes, hours, days, weeks, months, years.

Field differences (duration)

Subtract two timestamp fields (datetime or moment columns, both stored as UTC instants) and compare to seconds or an INTERVAL. A bare number or a named parameter is seconds (EXTRACT(EPOCH FROM ...)); rows where either side is null never match. The same expression can be selected; the result is duration in seconds, aliased as the expression text.

# Calls longer than 3 minutes
Call | end_time - start_time > INTERVAL "3 minutes"
Call | end_time - start_time > 180
Call | end_time - start_time >= :min_s   # params {"min_s": 60}
Call | NOW() - end_time > 120   # seconds since end_time
Call | start_time - NOW() < 0   # start_time in the past
Call | end_time - NOW() > 120   # same pattern, field minus NOW()

# Project duration (seconds)
Call | end_time - start_time > 120 | select id, end_time-start_time

Call has no stored duration column — use end_time - start_time.


Existence Check

Operator Description Example
EXISTS Field/relation exists conversation EXISTS
NOT EXISTS Field/relation does not exist recording NOT EXISTS

Control Clauses

Clause Description Example
select Specify fields to return select id, status, created_at
order Sort results (asc or desc; defaults to desc when omitted) order created_at desc
limit Maximum results; offset M after it skips M first limit 100, limit 20 offset 40
offset Standalone skip, on handle sources only; entity queries write limit N offset M offset 20
group by Group results group by status
flatten Expand nested entities to rows flatten messages
distinct on One row per distinct key (first under order) distinct on scenario_id

Distinct On (latest per key)

distinct on <path> keeps exactly one row per distinct value of a root-entity field: the row that sorts first under the query's order (default created_at desc, so the newest). limit applies after deduplication.

# The most recent SimulationTestRun per scenario for one workflow
SimulationTestRun | workflow_id = :w AND scenario_id is not null | distinct on scenario_id | order by created_at desc | select id, scenario_id, outcome, created_at

# Oldest call per phone number
Call | distinct on from_number | order by created_at asc | select id, from_number

Rules:

Aggregations

Aggregates are standalone clauses (not inside select).

Function Description Example
count(*) or count Count all rows Call | status = "active" | count(*)
count(field) Count non-null values Call | count(messages)
sum(field) Sum values Call | sum(duration)
avg(field) Average values Call | avg(score)
min(field) Minimum value Call | min(created_at)
max(field) Maximum value Call | max(duration)
# Count all matching calls
Call | status = "active" | count(*)

# Shorthand count (without parentheses)
Call | group by status | count

# Count with grouping
Call | group by status | count(*)

# Multiple aggregates
Call | group by status | count(*) | avg(duration)

Flatten Clause

The flatten clause expands a list on the entity, creating one row per item instead of aggregating them. The list can hold nested entities (messages), objects stored on the entity itself (config_decisions), or strings inside an object field (analysis.request_categories).

Default behavior (without flatten):

With flatten:

Syntax

flatten <path>

Examples

# Default: One row per conversation with messages as array
Conversation | select id, messages.content
# Returns: [{'id': '1', 'messages.content': ['Hi', 'Hello', 'Bye']}]

# With flatten: One row per message
Conversation | flatten messages | select id, messages.content
# Returns: [
#   {'id': '1', 'messages.content': 'Hi'},
#   {'id': '1', 'messages.content': 'Hello'},
#   {'id': '1', 'messages.content': 'Bye'}
# ]

# Filter on flattened messages
Conversation | flatten messages | messages.role = "user" | select id, messages.content

# Objects stored on the entity: both conditions must hold on the same decision
Workflow | flatten config_decisions | config_decisions.key = "after_hours_mode" AND config_decisions.answer = "self_serve" | select id, name

# Strings inside an object field: one row per topic, so counts are per topic
Conversation | flatten analysis.request_categories | group by analysis.request_categories | count(*)

# Combine with limits
Conversation | flatten messages | limit 100   # First 100 message rows

When to Use


Nested Entity Paths

Access fields on related entities using dot notation.

# Filter on nested entity field
Call | conversation.from_number = "+15551234567"

# Search on nested entity field
Call | conversation.messages.content ~~ "appointment"

# Select nested fields
Call | select id, conversation.from_number, status

# Members of an object field on the referenced entity: just that member
Call | select id, conversation.analysis.client_experience, conversation.analysis.request_categories

# Through a list of entities: some message matches / no message matches
Conversation | messages.party.phone_numbers = "+15551234567"
Conversation | messages.type != "voice"   # no voice message at all
Conversation | NOT (messages.type = "voice")   # the same

# A list of strings inside an object field: some item equals
Conversation | analysis.request_categories in ("billing", "records")

A path through a list follows the list rule in Flatten Clause: positive conditions match when some item matches, negative conditions and NOT (...) when no item does. Each item counts only in the version the root's own commit holds, as seen on the queried branch. like and regex on a list of strings inside an object field match the list's text (like '%"billing"%').

A member of an object field reached across a reference returns that member, exactly as on the root entity: scalars as text, lists and objects as JSON text.

Reverse edges (child -> container)

Declared edges point parent -> child (Conversation.messages, Call.conversation). HQL also synthesizes the opposite direction: every entity type that contains a type gives that type a virtual field named after the container's snake_case class name. Message is referenced by Conversation.messages, Call.messages and SupportTicket.messages, so it has conversation, call and support_ticket.

# Messages of one conversation, from the child side
Message | conversation.id = "abc123" | select id, role, metadata | limit 30

# Any container field, and further hops through it
Message | conversation.status = "active" | select id, conversation.agent.name

# Bare edge in select = the container id
Message | id = "m1" | select id, conversation, call

# Single-ref containers work the same way (Call.conversation -> Conversation.call)
Conversation | call.status = "completed" | select id, call.id

Rules:

Equivalent container-side form (always available):

Conversation | id = "abc123" | flatten messages | select messages.id, messages.role, messages.metadata

Array Modifiers

Slice, index, and flatten array results.

Modifier Description Example
[n] Get nth element (0-indexed) messages.content[0]
[-n] Get nth from end messages.content[-1]
[:n] First n elements messages.content[:3]
[n:] From n to end messages.content[2:]
[n:m] Range slice messages.content[1:5]
[] Flatten nested arrays (one level; non-array items pass through) messages.content[]

The modifier applies to the array the projection produces: [n] returns a single element (a scalar, or a single lazy entity ref for messages[0]), slices return an array. An out-of-range index yields null.

Examples

# Role of the first / last message
Conversation | select id, messages.role[0], messages.role[-1]

# First two messages as lazy refs; the first message alone
Conversation | select id, messages[:2], messages[0]

# Through an entity hop
Call | select id, conversation.messages.role[:3]

# Slice then flatten
Call | select id, conversation.messages.content[:5][]

Where the modifier lands:


Grouped Field Selection

Select multiple fields from related entities as objects using {field1, field2} syntax.

Works with both list entities (returns array of objects) and singular entities (returns single object).

# List entity: Select fields from messages as array of objects
Call | select id, conversation.messages{content, id, role}
# Returns: [{'conversation.messages{content,id,role}': [{'content': [...], 'id': '...', 'role': 'assistant'}, ...]}]

# Singular entity: Select fields from a related entity as an object
TelnyxPhoneNumber | select id, inbound_agent{id, name}
# Returns: [{'id': '+15555550100', 'inbound_agent{id,name}': {'id': 'v3:9fQ2...', 'name': 'My Agent'}}]

# Nested singular entity path
Call | select id, conversation.agent{id, name}

# Combine with array modifiers (list entities)
Call | select id, conversation.messages{content, tool_calls[]}
# Returns objects with flattened tool_calls

Reserved words as field names

Inside {...} a reserved word (group, limit, order, ...) is always a field name, so select fields{id, group} works. The same holds for a filter whose field is named like a keyword when it is directly followed by an operator: FormTemplate | group = "Osteoarthritis". Dotted paths (foo.group) always work. A bare select group is still rejected — aggregates (count(*)) own that position; use select fields{group} or a dotted path instead.

Benefits


Branches

# Query a branch (entities it has not changed resolve to main)
Document @ feature-branch | status = "draft"

HQL reads the latest version of each entity on the branch. It does not read past versions: a pinned commit or point in time (@ main:<commit>) is refused, and so is a time-based branch (one created with a base_timestamp). To read a past version, list the entity's history in the Entities API and get it by commit id.


Return Modes

Control how results are returned.

Mode Description
llm_safe Flat rows of JSON-safe values: long strings are cut and binary values appear as their handle (the default when a query is run through the API)
matches Flat rows with matching items
entity Full root entities that contain matches
graph Full entity graph with all children
typed Flat rows plus each column's kind, for clients that render values

Polymorphic Queries (Abstract Base Classes)

You can query an abstract base entity (one with no table of its own, e.g. Touchpoint, Integration, IntegrationBackend) and HQL transparently runs the query across every concrete subclass.

# Returns rows of every concrete Touchpoint subclass
# (TelnyxPhoneNumber, EmailAddress, ...), each tagged with _concrete_type.
Touchpoint | limit 100

# With return mode entity: full entities, each as its concrete class
Touchpoint | id like "+1%"
# -> [TelnyxPhoneNumber(...), EmailAddress(...), ...]

How it works:

Rules and limits:

A query on a concrete class (TelnyxPhoneNumber | ...) reads that class alone.

The _concrete_type reserved field

_concrete_type is a reserved pseudo-field that names each row's concrete entity class. It is available in select and filters on any entity type — abstract base or concrete — so you always have a clean, uniform way to query the class name (no need to know whether the query is polymorphic):

# Select it on a concrete class (emitted as a literal of the class name):
Call | limit 5 | select id, _concrete_type
# -> [{"id": "...", "_concrete_type": "Call"}, ...]

# Select it on an abstract base (the real per-branch column):
Integration | limit 5 | select id, _concrete_type
# -> [{"id": "...", "_concrete_type": "EvetPracticePims"}, ...]

# Filter by concrete class — the idiomatic way to narrow a polymorphic query
# to one subclass (or to assert a concrete query's own type):
Integration | _concrete_type = "EvetPracticePims" | select id
Touchpoint | _concrete_type in ("TelnyxPhoneNumber", "EmailAddress")

Notes:


Value Normalization

Filter values are automatically normalized using entity field validators: phone numbers (phonenumber) to E.164, emails (email) to lowercase, URLs (url) to their full form, and dates as in "Smart Date Parsing". Only =, !=, in and the comparisons run the validator: like, ilike, contains, startswith and the regex operators match their pattern as written, so ilike "+1202%" is not turned into a phone number.

# Phone numbers are normalized automatically
Call | to_number = "5555550143"   # Becomes "+15555550143"

# Works with IN operator too
Call | to_number in ("5555550143", "5551234567")

# Emails are lowercased
Party | email_addresses = "Jane.Doe@Example.com"

An address (address) is compared as its text: it has no parts such as .city to filter on, so match a city or ZIP code inside the text (ilike "%Springfield, IL%").


DELETE Operations

HQL supports DELETE operations for removing entities with soft or hard delete.

Syntax

DELETE <Entity> [@ <branch>] | <filter> [| hard]

Safety Requirements

Branch Options

Syntax Behavior
DELETE Call | ... Delete from main branch (default)
DELETE Call @ feature | ... Delete from specific branch
DELETE Call @ * | ... Delete from all branches

Examples

# Soft delete by filter
DELETE Call | status = "cancelled"

# Delete specific IDs
DELETE Call | id in ("id1", "id2", "id3")

# Hard delete (permanent - use with caution!)
DELETE Call | status = "test" | hard

# Delete from specific branch
DELETE Document @ draft | status = "abandoned"

# Delete from all branches
DELETE Call @ * | id = "abc123"

Boolean Expressions

DELETE supports complex filters with AND/OR/NOT:

# Complex conditions
DELETE Call | (status = "cancelled" OR status = "failed") AND created_at < "2024-01-01"

# NOT operator
DELETE Call | status = "active" AND NOT provider = "test"

Warnings


Handle Sources (a stored value as a table)

A query can read a list inside a stored value (a tool result or report that came back as a handle) as a table. handle(...) takes the place of the entity type:

handle('<ref>' [, '<path>'] [, headers='<path>']) | <clause> | <clause> ...
Argument Meaning
ref The handle (tree-9gVb2kQ1). Unknown or not visible: 404 No stored value found: ...
path Dtypes path syntax. A JSON pointer must land on a list, whose items are the rows (/result/sections/0/rows); a glob makes every node it matches a row (orders[*].lines[*]). Omitted: the value itself is the list.
headers Path to a list of column names; required when the rows are lists.

Arguments may be :params. A handle source has no branch (@ ... is a parse error: stored values are not versioned). The value must be structured data (a JSON tool result (tree) or a table (table)); a PDF, recording or text is refused.

Columns

Types

A column's kind comes from all its non-empty values (every line of a multi-line cell):

Kind When Output
date at least 95% of values are M/D/YYYY (month first) or YYYY-MM-DD 2026-01-05
datetime the same, with ISO 8601 times ISO 8601
phone at least 95% of values normalise to a phone number E.164 +12065550101, as phone numbers (phonenumber) are stored
number, bool JSON numbers / booleans as is
text anything else as is

In a date or phone column, the few values that do not parse count as null, and a warning names them (due_date: 3 of 9,812 values are not dates and count as null ('N/A'); text(due_date) shows them as written.). An ordering comparison of a text column with a date matches nothing and warns: compare date(x).

A literal compared with a typed value is parsed to its kind: due_date <= '1/6/2026' compares dates ('2026-01-06' and 'Jan 6 2026' work too), so 12/30/2025 sorts before 1/5/2026; phone = '206-555-0101' matches (206) 555-0101. Numeric text stays text (ids with leading zeros keep them) but compares numerically against a number literal. A text cell ordered against a date literal (<, <=, >, >=, between) never matches. typed mode reports each column's kind.

Functions

Function Result
split_lines(x) The lines of a text cell, as a list
date(x), phone(x), number(x) x read as that kind; null when it does not parse
text(x) x as plain text, never parsed (text(phone) keeps how it was written)
lower(x) Lowercase text

Functions work in filters, select, group by, order by and aggregates (min(split_lines(due_date))). A selected function column is named as written: select lower(contact) returns lower(contact).

Multi-line cells: split_lines and explode

Reports often put one item per line inside a cell. A filter on a list-valued expression matches when any item matches:

handle('tree-abc', '/rows', headers='/headers') | split_lines(due_date) <= '1/6/2026'

Comparing the whole cell compares the whole text, and adds the warning due_date: 12 cells hold several lines; compare each line with split_lines(due_date) or explode due_date.

explode a, b, c makes one row per line, zipping the listed cells by position (line 1 of each, then line 2, ...); the other cells repeat. A text cell explodes into its lines (explode x = explode split_lines(x)), a JSON list into its items. Lists of unequal length are padded with null, with the warning explode a, b: 3 rows had lists of different lengths; the shorter ones were padded with null. A row whose listed cells are all empty stays one row, with nulls. At most 200,000 rows may result.

handle('tree-abc', '/rows', headers='/headers') | explode item, due_date | due_date < '1/5/2026' | select contact, item, due_date

Filters

Every comparison, set, null, like/ilike, regex (Python re, matching anywhere in the value) and between operator works, plus:

Operator Meaning Example
contains Case-insensitive substring contact contains 'lee'
startswith Case-insensitive prefix item startswith 'al'
in handle(...) / not in handle(...) Membership in a second stored value: a list of scalars, or one column of object rows with column= contact not in handle('tree-def', '/rows', column='contact')

in / not in also take a literal list or a :param holding a JSON list; x not in (...) is true when x is null. List values that equal no row's value are named in a warning (contact not in: 2 of 50 values match no row: ...), so a name spelled differently from the data does not go unnoticed; excluding by phone matches across formats. Search operators (~~, ~=, ~*, *~) need a search index and are refused: use contains, ilike or =~*. flatten, execute, [..] / {..} modifiers and field arithmetic are refused too.

Group, aggregate, having

Order, distinct, paging, select

Clause order

Clauses run in one fixed order, whatever order they are written in: source -> explode -> where -> group by + aggregates -> having -> order by -> distinct -> offset/limit. select shapes each output row; order by and distinct a read the full row.

handle('tree-abc', '/result/sections/0/rows', headers='/result/sections/0/headers')
| explode kind, item, due_date
| contact not in :done
| group by contact, phone
| min(due_date) as earliest, collect(subject, item, due_date) as items
| having earliest <= '1/6/2026'
| order by earliest asc, contact asc
| limit 20

Handle sources only, for now

explode, having, several group by or order by keys, standalone offset, distinct without on, collect(), as on an aggregate, contains, startswith, in handle(...) and the functions work only on a handle source. On an entity or Log query they are refused: having works only on a handle(...) source for now; entity and Log queries take one group by key, one order key and no functions.

Errors

Each names what exists, so one failed query says how to fix it:


Complete Examples

# Active calls since a date, newest first
Call | status = "active" | created_at >= "2024-01-01" | order created_at desc | limit 50

# Calls about appointments
Call | content ~~ "appointment scheduling" | status in ("completed", "active") | limit 20

# Complex boolean query
Call | (status = "active" OR status = "pending") | NOT provider = "test" | created_at BETWEEN "2024-01-01" AND "2024-06-30" | order score desc | limit 100

# Aggregation by status
Call | group by status | count

# Regex matching
Call | from_number =~* "^\+1555"

# Flatten nested entities
Conversation | flatten messages | messages.role = "user" | select id, messages.content

# Delete
DELETE Call | status = "cancelled"

Parameterized Queries

Use parameters to safely pass values and prevent SQL injection. A named parameter :name in the query takes its value from the params object sent with it.

# params {"status": "active", "limit": 10}
Call | status = :status | limit :limit

# params {"status": "active", "limit": 20, "offset": 40}
Call | status = :status | limit :limit offset :offset

# params {"status": "cancelled", "date": "2024-01-01"}
DELETE Call | status = :status AND created_at < :date

Benefits


Performance Tips

  1. Use limit - Always limit results for large tables
  2. Use indexed fields - Filter on indexed columns when possible
  3. Prefer in over OR - status in ("a", "b") is often faster than status = "a" OR status = "b"
  4. Use search operators for text search - ~*/~~/~= use GIN/HNSW indexes; like/ilike and regex operators scan rows and can time out on large text fields. For word/name lookups, content ~* "term" is the fast equivalent of content ilike "%term%"
  5. Select specific fields - Use select to reduce data transfer
  6. Use flatten sparingly - Only flatten when you need individual rows; aggregated results are more efficient
  7. Test DELETE filters - Run as SELECT query first to verify what will be deleted

Operator Reference

Filter Operators

Operator SQL Description
= = Equal
!= != Not equal
> > Greater than
>= >= Greater than or equal
< < Less than
<= <= Less than or equal
in IN Set membership
not in NOT IN Not in set
like LIKE Pattern match
ilike ILIKE Case-insensitive pattern
is null IS NULL Null check
is not null IS NOT NULL Not null check
BETWEEN BETWEEN Range check
EXISTS EXISTS Existence check
NOT EXISTS NOT EXISTS Non-existence check
contains (handle sources) Case-insensitive substring
startswith (handle sources) Case-insensitive prefix

Search Operators

Operator Function Description
~= vector_search() Semantic similarity (vector search)
~~ search() Hybrid (vector + fulltext combined)
~* fulltext_search() Keyword/token matching (fulltext)
*~ phrase_search() Phrase search (word order + proximity)

Regex Operators

Operator SQL Description
=~ ~ Regex match (case-sensitive)
=~* ~* Regex match (case-insensitive)
!~ !~ Regex NOT match (case-sensitive)
!~* !~* Regex NOT match (case-insensitive)

Boolean Operators

Operator Description
AND Logical AND (higher precedence than OR)
OR Logical OR (lower precedence than AND)
NOT Logical NOT (highest precedence)
() Grouping (override precedence)