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:
%- matches any sequence of characters_- matches any single character
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:
- Pipe clause (
Call | ... | content ~~ "x" | limit 10): ranking — the top-K best matches by relevance score, ordered by score. Approximate under heavy competition (top-K is global), which is the point of ranked retrieval. - Inside a boolean expression under
OR/NOT, or with an explicit threshold (created_at >= X AND content ~= "x" >= 0.5): an exact predicate — "does this row have a match", uncapped, ordered bycreated_at DESClike any filter query. Every matching row is returned; nothing can be starved out by higher-ranking matches elsewhere. - One un-thresholded
~~/~=among AND conjuncts (role = "user" AND content ~~ "x") is the ranking form: it means exactlyrole = "user" | content ~~ "x"— filter by the siblings, rank by relevance. There is only one sensible reading of that query, so the two spellings compile identically.
Predicate-context rules:
~*and*~are exact via the text index.~=underOR/NOTrequires an explicit threshold (content ~= "x" >= 0.5) — an unthresholded similarity predicate would match everything.~~underOR/NOTdegrades to fulltext-only unless a threshold is given; with one, it matches rows passing EITHER the text or the similarity test.NOT (content ~* "x")means "has no matching row" (exact).- Exception: with no other root-level filter at AND level, a non-negated expression search keeps the ranked top-K shape (documented approximate) — there is no selective driver for the exact per-root probe.
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:
- The key must be a field of the queried entity (not a joined/nested path).
- Not combinable with
group by/aggregates,flatten, or search operators — those define their own row semantics; the compiler raises naming the conflict.
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):
- List items return as arrays
- One row per root entity
- A condition on a list field means "some item matches", and each condition may match a different item
- A negative condition on a list field (
!=,not in,!~,not exists, orNOT (...)around any condition) means "no item matches", so a root with an empty list qualifies
With flatten:
- List items expand to individual rows
- Multiple rows per root entity (one per item); a root with an empty list keeps one row with empty item fields
- Every condition on the flattened path applies to that row's item, so conditions joined with
ANDmust hold on the same item - Without
order, rows list the newest root first and each root's items in list order, as long as no condition is on the flattened items. With such a condition, rows come in no particular order; addorderif you need one
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
- Use flatten when: You need individual rows for nested items (e.g., exporting message data)
- Skip flatten when: You want aggregated data (default behavior is more efficient)
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:
- The edge resolves to the container's current head on the query branch (the same visibility every join uses), so historical versions of the container never duplicate rows.
- A field the class declares itself always wins; a reverse edge is only added when the name is free.
- The edge is unambiguous only when the container points at the type through
one field.
CallreferencesPartyvia bothfrom_partyandto_party, soParty | call.id = ...raises and tells you to query fromCall. - Formally many-valued (a
Messagecan sit in aConversationand aCall— use the edge you mean). Inselect, the projection is scalar and returns the most recently created matching container. flatten <reverse edge>is rejected: flatten from the container instead (Conversation | flatten messages | select messages.id).- Reverse edges are listed as
name (-> Container)in unknown-field errors, and the error also names every container of the type with a working rewrite.
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:
- Dotted form (
messages.role[0]): the aggregated array of that field across the list, i.e. the first message's role. A modified path is never merged into the groupedmessagesobject with unmodified siblings. messages.content(a list-of-dtype leaf) aggregates content items across all messages into one flat array, somessages.content[0]is the first content item of the first message. To index per message, useflattenor the grouped form below.- Under
flatten messages, a leaf is one row's value, somessages.content[0]is that message's first content item. - Grouped form (
messages{role, content[0]}): the modifier applies to the inner field of each object, not to the list of objects. - A modifier on a scalar field (
status[0]) is an error rather than a silent no-op.
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
- Structured output: Get objects with named fields instead of separate columns
- Reduced queries: Fetch multiple fields in one query
- Works with any entity: Both list entities (arrays) and singular entity references
- Modifier support: Apply
[],[:n]to individual fields within the group
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:
- The query runs across every concrete subclass as one statement, even when only one subclass exists.
- Every result row carries a synthetic
_concrete_typecolumn naming the concrete class. Inentity/graphmode each row is loaded as its concrete class. - A concrete class that also has subclasses (e.g.
Agent) is not an abstract base: it has rows of its own, soAgent | ...reads them directly.
Rules and limits:
- Fields: you can only filter/select/order on fields declared on the abstract base. A subclass-only field raises a helpful error — filter to that subclass (or query it directly) instead.
- Search: cross-subclass search is supported and stays a single statement.
Fulltext (
~*,*~) gives exact global top-K; vector (~=) and hybrid (~~) give approximate global top-K (per-branch top-K then merge/re-rank — the standard cross-shard ANN trade-off). The searched field must have the required index on every branch, else you get an error naming the branch. - Schema drift: if a base field hasn't been materialized as a column on
some older subclass table yet, it is returned as
NULLfor that branch rather than failing the query.
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:
- On a concrete query it compiles to a constant (
'Call' = 'Call'), so_concrete_type = "Call"matches all rows and_concrete_type = "Other"matches none — never an error about a missing field. - On a polymorphic query it is the real union column, so filtering on it is pushed down to the union and prunes branches cleanly.
selectand filters work on any entity type.order byandgroup by_concrete_typeare meaningful only on a polymorphic query (where it is a real column); on a concrete query it is a constant, soorder byfalls back to the default ordering andgroup byis not supported (there is no such column to group on there).
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
- At least one filter is required for safety (prevents accidental deletion of all data)
- By default, performs soft delete (sets
deleted_attimestamp) - Use
| hardflag for permanent deletion (cannot be undone)
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
- Hard delete is permanent - Use only for GDPR compliance or test data cleanup
- Always test filters - Use a regular query first to verify what will be deleted
- Backup important data - Hard deletes cannot be recovered
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
- List rows (with
headers): one column per header, by position. Every row needs one cell per header. - Object rows: the union of their keys. Nested objects are read with
a.b(meta.tag = 'x'). - Scalar rows: one column,
value. - Names are normalised: lowercase, runs of other characters become
_, a leading digit getsc_(Due Date->due_date,Item / Code->item_code,2nd->c_2nd). Two names that normalise alike: the later one gets_2and a warning. - Empty cells are null: an empty or whitespace-only string is null.
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
group by a, b: several keys.- Aggregates go in one clause, comma-separated, each optionally named with
as:min(due_date) as earliest, count(*) as n. Withoutgroup bythey make one row. collect(x): the group's values ofx, in row order.collect(a, b, c): a list of{a, b, c}objects.- Default names:
countforcount(*),<func>_<column>otherwise (min_due_date),collect_a_b_cfor several columns. Two output columns with one name are refused. having <filter>: filters groups by their keys and aggregate names. An aggregate name in a plain filter is refused with a pointer tohaving.
Order, distinct, paging, select
order by a asc, b desc: several keys (each defaults todesc); nulls sort last either way. It may use a column that is not selected. Rows that tie keep the order of the value (groups: the order of their first row), soorder by earliest ascalone keeps a report's own order within a date.distinct: drops repeated output rows (afterselect).distinct a, b: keeps the first row per value of the keys, under the order.offset Non its own, orlimit N offset M.run_hqlreturnstotal_rows, the rows matched before offset and limit.select a, b: the output columns. Without it every column is returned.
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:
Column 'due' does not exist in handle('tree-abc', '/rows'). Available columns: contact, phone, subject, kind, item, due_date (from the headers at /headers). Did you mean 'due_date'?Row 17 (/rows/17) has 6 cells, but the headers at /headers name 7 columns: Contact, Phone, .... Every row needs one cell per header./result in handle('tree-abc') is an object, not a list of rows; its keys are: title, sections. Point the path at a list.The rows at /rows in handle('tree-abc') are lists; name their columns with headers='<path to a list of names>'.handle('tree-abc') has nothing at /result/sheets/0: at /result its keys are: title, sections.return_mode 'entity' needs an entity source; handle(...) queries return rows (llm_safe, matches or typed).
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
- SQL Injection Prevention: Values are escaped automatically
- Type Safety: Parameters are properly typed
- Reusability: Same query with different values
Performance Tips
- Use
limit- Always limit results for large tables - Use indexed fields - Filter on indexed columns when possible
- Prefer
inoverOR-status in ("a", "b")is often faster thanstatus = "a" OR status = "b" - Use search operators for text search -
~*/~~/~=use GIN/HNSW indexes;like/ilikeand regex operators scan rows and can time out on large text fields. For word/name lookups,content ~* "term"is the fast equivalent ofcontent ilike "%term%" - Select specific fields - Use
selectto reduce data transfer - Use flatten sparingly - Only flatten when you need individual rows; aggregated results are more efficient
- 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) |