Skip to contentSkip to navigationSkip to topbar
On this page
Looking for more inspiration?Visit the
(information)
You're in the right place! Segment documentation is now part of Twilio Docs. The content you are used to is still here—just in a new home with a refreshed look.

Segment Query Language Reference


FREE x
TEAM
BUSINESS
ADDON x

Segment's query language lets you define audience segments and computed traits. With clear syntax and practical functionality, the language simplifies the process of defining conditions and computations, helping you extract valuable insights from customer data.

This reference provides a comprehensive overview of the Segment query language.

(information)

Segment's query language in private beta

Segment's query language is in private beta, and Segment is actively working on this feature. Some functionality may change before it becomes generally available.


Overview

overview page anchor

Audience definitions specify the criteria for identifying users or accounts as members of a particular audience, while computed trait definitions outline the logic for aggregating or calculating values stored as traits on user or account level profiles.

With Segment's query language, you can create these definitions and use them with Segment APIs to generate audiences and computed traits.


Available functions and operators

available-functions-and-operators page anchor

This section outlines the functions and operators you can use with the query language.

Syntax

syntax page anchor

Follow these syntax rules when you create definitions:

  • All definitions consist of expressions connected by optional junctions.
  • Expressions are composed of chained functions, starting with an extractor and ending with a result.
  • . serves as the delimiter when chaining functions.
  • Audience definitions must return a boolean result (for example, a comparator), while computed trait definitions must return a scalar.
  • Functions have well-defined return types that determine the permissible functions in the call chain.
  • When you use junctions, AND holds precedence over OR, but parentheses offer control over expression combination.
  • Each definition allows a maximum of 50 primary expressions.

The language supports the following syntactic sugar adjustments:

  • The language automatically wraps a 'literal' extractor function around string or number inputs wherever a scalar expression expects them.
  • You can invoke the boolean comparator functions equals, differs, greater_than, at_least, less_than, and at_most by omitting the period and parenthesis and replacing the function name with the equivalent symbols =, !=, >, >=, <, and <=. Regardless of the syntactic sugar, the comparison still dictates the operations allowed in the call-chain.

The definition type (USERS or ACCOUNTS) determines whether the computation operates at the user or account level. For account-level audiences, you can apply additional functions ANY (to verify that all underlying users meet the defined conditions) and ALL (to check if any of the underlying users meet the defined conditions).

These functions use the association between accounts and users to determine audience membership.


The following tables list the query languages's available functions.

event
Syntaxevent({s: String})
s - the name of the event to build an extractor for
Return TypeVectorExtractor
Exampleevent('Shoes Bought')
trait
Syntaxtrait({s: String})
s - the name of the trait to reference
Return TypeScalarExtractor
DescriptionSimilar to the event operator, the trait operator is used to specify profile trait filter criteria.
NotesYou can reference other audiences by using the audience key as the trait name. The . character indicates traversal through nested structures. If the trait name contains a literal period (.), it must be escaped using \\\\.
Exampletrait('total_spend')
entity
Syntaxentity({s: String})
s - the relationship slug of the entity to build an extractor for
Return TypeVectorExtractor
DescriptionSimilar to the event operator, the entity operator is used to specify entity filter criteria.
NotesEntity is only used with Linked Audiences.
Exampleentity('accounts')
property
Syntaxproperty({s: String})
s - the name of the property to build an extractor for
In the context of funnel audiences, you can add a parent prefix to reference the parent event.
property(parent: {s: String})
Return TypeScalarExtractor
NotesOnly valid within a where function or a Reducer. The . character indicates traversal through nested structures. If the trait name contains a literal period (.), it must be escaped using \\\\.
Exampleproperty('total')
context
Syntaxcontext({s: String})
s - the name of the context to build an extractor for
Return TypeScalarExtractor
NotesOnly valid within a where function or a Reducer.
Examplecontext('page.url')
literal
Syntaxliteral({a: Any})
a - the value to treat as a literal expression
Operations allowed in call-chainNone allowed; typically used within another function, like a comparison (with syntactic sugar, this would appear on the right side of the comparison). The outer function or comparison dictates the operations allowed in the call-chain.
NotesLiterals can be int, float, string, date or timestamp, where date uses the format yyyy-mm-dd and timestamp follows the ISO 8601(link takes you to an external page) format. string is generally interchangeable with all other formats, except when used in a property chained to an entity. In this case, Segment recommends matching the data type of the entity property being targeted.
Exampleliteral(100), literal('value'), or literal(2022-10-17T00:00:00)
where
Syntaxwhere({e: Comparator})
e - a subexpression terminating in a boolean Comparator
Return TypeStreamFilter
DescriptionFilters the stream to only items where a property satisfies a particular condition.
NotesThe parameter is a sub-expression, something that terminates in a boolean Comparator.
Examplewhere({property('price_usd') > 100})
sources
Syntaxsources({exclude: {a: Array}})
a - an array of source ids to exclude
Return TypeStreamFilter
DescriptionFilters the stream to only items whose source id does not match the exclusion list.
Examplesources({exclude: 'QgRHeujRJBM9j18yChyC', '/;hSBZDqGDPvXCKHbikPm'})
within
Syntaxwithin({d: Integer} {u: TimeUnit})
d - duration value
u - hour (s) day (s)
In the context of funnel audiences, you can add a parent prefix to reference the parent event.
within(parent: {d: Integer} {u: TimeUnit})
Return TypeWindowedFilter
DescriptionProvides time windowing so that events are only looked at over a specified number of hours or days into the past. You can add a prefix to direct the evaluation to be relative to the timestamp of a different event.
Examplewithin(7 days)
between
Syntaxbetween({s: Integer} {su: TimeUnit}, {e: Integer} {eu: TimeUnit})
s - start value
su - hour (s) day (s)
e - end value
eu - hour (s) day (s)
Return TypeWindowedFilter
DescriptionYou can add a prefix to direct the evaluation to be relative to the timestamp of a different event.
Examplebetween(7 days, 10 days)
expires_after
Syntaxexpires_after({d: Integer} {u: TimeUnit})
d - duration value
u - second (s) hour (s) day (s)
Return TypeWindowedFilter
DescriptionYou can add a prefix to direct the evaluation to be relative to the timestamp of a different event.
Notesexpires_after is meant to be used with Computed Traits in order to handle session windows.
Exampleexpires_after(1 hour)
count
Syntaxcount()
Return TypeScalar
DescriptionCounts the number of entries in a stream and returns the result.
Examplecount()
sum
Syntaxsum({s: EventPropertyExtractor})
s - property to sum
Return TypeScalar
Examplesum(property('spend'))
avg
Syntaxavg({s: EventPropertyExtractor})
s - property to average
Return TypeScalar
Exampleavg(property('spend'))
max
Syntaxmax({s: EventPropertyExtractor}) or max({s: EventPropertyExtractor} as type)
s - property to get the maximum value of
type - number, string
Return TypeScalar
NotesIf no type is passed, Segment assumes number as the type and selects the greatest value. You can override the behavior to select the max based on lexicographical ordering by specifying as string.
Examplemax(property('spend'))
max(property('spend') as string)
min
Syntaxmin({s: EventPropertyExtractor}) or min({s: EventPropertyExtractor} as type)
s - property to get the minimum value of
type - number, string
Return TypeScalar
NotesIf no type is passed, Segment assumes number as the type and selects the smallest value. You can override the behavior to select the max based on lexicographical ordering by specifying as string.
Examplemin(property('spend'))
min(property('spend') as string)
mode
Syntaxmode({s: EventPropertyExtractor}, {d: Integer}) or mode({s: EventPropertyExtractor} as type, {d: Integer})
s - the property to find the most frequent value of
d - minimum frequency expected
type - number, string, array
Return TypeScalar
DescriptionFind the most frequent value for a given property name.
NotesIf no type is passed, Segment assumes string as the type and selects the most frequent value assuming all data is a string. number will behave the same as string. array will also behave the same way, except when used in combination with the $ operator where instead of treating each individual value within the array separately Segment will instead treat the whole array as a string.
Examplemode(property('spend'), 2)
mode(property('spend') as array, 2)
first
Syntaxfirst({s: EventPropertyExtractor})
s - the property to find the first value of
Return TypeScalar
DescriptionFind the first value for the given property name within the stream of filterable data extracted.
Examplefirst(property('spend'))
last
Syntaxlast({s: EventPropertyExtractor})
s - the property to find the last value of
Return TypeScalar
DescriptionFind the last value for the given property name within the stream of filterable data extracted.
Examplelast(property('spend'))
unique
Syntaxunique({s: EventPropertyExtractor})
s - property to get the unique values of
Return TypeListScalar
DescriptionGenerate a unique list of values for the given property name.
Exampleunique(property('spend'))
equals
Syntaxequals({v: Scalar})
v - value to compare for equality
Return TypeComparator
Exampleequals(500)
Syntactic Sugar: == 500
differs
Syntaxdiffers({v: Scalar})
v - value to compare for inequality
Return TypeComparator
Notes'differs' only returns true if the value exists and is not equal. If null values need to be considered then use 'NOT (expression) = (value)' or add a condition to check for nulls '(expression) != (value) OR (expression).absent()'.
Examplediffers(500)
Syntactic Sugar: != 500
absent
Syntaxabsent()
Return TypeComparator
DescriptionReturns true when a value is null. Equivalent to NOT (expression).exists().
Exampleabsent()
exists
Syntaxexists()
Return TypeComparator
DescriptionReturns true when a value is set, meaning not null. Equivalent to NOT (expression).absent().
Exampleexists()
greater_than
Syntaxgreater_than({n: Scalar})
n - value to compare
Return TypeComparator
Examplegreater_than(500)
Syntactic Sugar: > 500
at_least
Syntaxat_least({n: Scalar})
n - value to compare
Return TypeComparator
Exampleat_least(500)
Syntactic Sugar: >= 500
less_than
Syntaxless_than({n: Scalar})
n - value to compare
Return TypeComparator
Exampleless_than(500)
Syntactic Sugar: < 500
at_most
Syntaxat_most({n: Scalar})
n - value to compare
Return TypeComparator
Exampleat_most(500)
Syntactic Sugar: <= 500
contains
Syntaxcontains({a: Array})
a - array of possible values
Return TypeComparator
DescriptionMatches when the value contains one of the elements of the parameter array as a substring.
Examplecontains('shoes','shirts')
omits
Syntaxomits({s: String})
s - string to search for if missing in a containing string
Return TypeComparator
DescriptionEvaluates to true when a substring isn't present in a containing string, equivalent to NOT (expression).contains(<argument>).
Exampleomits('shoes')
starts_with
Syntaxstarts_with({s: String})
s - string to search for at start of containing string
Return TypeComparator
Examplestarts_with('total')
ends_with
Syntaxends_with({s: String})
s - string to search for at end of containing string
Return TypeComparator
Exampleends_with('total')
one_of
Syntaxone_of({a: Array})
a - array of possible values
Return TypeComparator
DescriptionMatches when the value exactly matches one of the values from the parameter array.
Exampleone_of('shoes','shirts')
none_of
Syntaxnone_of({a: Array})
a - array of possible values
Return TypeComparator
DescriptionMatches when the value does not exactly match one of the values from the parameter array.
Examplenone_of('shoes','shirts')
before_date
Syntaxbefore_date({t: Timestamp})
t - ISO 8601 timestamp
Return TypeComparator
Notesstring format can also be used
Examplebefore_date(2023-12-07T18:50:00Z) or before_date('2023-12-07T18:50:00Z')
after_date
Syntaxafter_date({t: Timestamp})
t - ISO 8601 timestamp
Return TypeComparator
Notesstring format can also be used
Exampleafter_date(2023-12-07T18:50:00Z) or after_date('2023-12-07T18:50:00Z')
within_last
Syntaxwithin_last({d: Integer} {u: TimeUnit})
d - duration value
u - hour(s), day(s)
Return TypeComparator
DescriptionRepresents the date range between today and the past d days - inclusive where today represents the current date at the time Segment determines audience membership or calculates the trait.
Examplewithin_last(7 days)
within_next
Syntaxwithin_next({d: Integer} {u: TimeUnit})
d - duration value
u - hour(s), day(s)
Return TypeComparator
DescriptionRepresents the date range between today and the next d days - inclusive where today represents the current date at the time Segment determines audience membership or calculates the trait.
Examplewithin_next(7 days)
before_last
Syntaxbefore_last({d: Integer} {u: TimeUnit})
d - duration value
u - hour(s), day(s)
Return TypeComparator
DescriptionRepresents the date range between today - d days and any past date prior to that - inclusive where today represents the current date at the time Segment determines audience membership or calculates the trait.
Examplebefore_last(7 days)
after_next
Syntaxafter_next({d: Integer} {u: TimeUnit})
d - duration value
u - hour(s), day(s)
Return TypeComparator
DescriptionRepresents the date range between today + d days and any future date - inclusive where today represents the current date at the time Segment determines audience membership or calculates the trait.
Exampleafter_next(7 days)
AND
Syntax{Comparator} AND {Comparator}
Base TypeJunction
Return TypeComparator
DescriptionTrue only if both subexpressions evaluate to true.
OR
Syntax{Comparator} OR {Comparator}
Base TypeJunction
Return TypeComparator
DescriptionTrue if either subexpression evaluates to true.
NOT
SyntaxNOT ({Comparator})
Base TypeJunction
Return TypeComparator
DescriptionTrue only if the subexpression evaluates to false.
ANY
SyntaxANY ({Comparator})
Base TypeJunction
Return TypeComparator
DescriptionUsed to evaluate an aggregatable boolean expression to determine if any expression is true. Used to specify account-level audience queries that aggregate across user-level queries.
ALL
SyntaxALL ({Comparator})
Base TypeJunction
Return TypeComparator
NotesUsed to evaluate an aggregatable boolean expression to determine if every expression is true. Used to specify account-level audience queries that aggregate across user-level queries.

Extractor
OperationsNone included
VectorExtractor (extends Extractor, StreamFilter)
Base TypeExtractor, StreamFilter
Operations allowed in call-chainwhere, sources, within, between, count, sum, avg, max, min, mode, first, last, unique (inherited from StreamFilter)
NotesA VectorExtractor represents extractions of data sets that need to be filtered and reduced to a scalar. Adds isVector property to entire expression.
ScalarExtractor (extends Extractor, Scalar)
Base TypeExtractor, Scalar
Operations allowed in call-chainequals, differs, absent, exists, greater_than, at_least, less_than, at_most, contains, omits, starts_with, ends_with, one_of, none_of, before_date, after_date, within_last, before_last, after_next (inherited from Scalar)
NotesA ScalarExtractor represents extractions of a single data element, like a field value or a trait value.
EventPropertyExtractor (extends Extractor)
Base TypeExtractor, Scalar
Operations allowed in call-chainNone
NotesUsed to refer to properties for comparison purposes.
Filter
Operations allowed in call-chainNone included
StreamFilter (extends Filter)
Base TypeFilter
Operations allowed in call-chainwhere, sources, within, between, count, sum, avg, max, min, mode, first, last, unique
WindowedFilter (extends StreamFilter)
Base TypeStreamFilter
Operations allowed in call-chainwhere, sources, within, between, count, sum, avg, max, min, mode, first, last, unique
Scalar
Operations allowed in call-chainequals, differs, absent, exists, greater_than, at_least, less_than, at_most, contains, omits, starts_with, ends_with, one_of, none_of, before_date, after_date, within_last, before_last, after_next, within_next
ListScalar
Operations allowed in call-chaincount
Comparator
Base TypeComparator
Operations allowed in call-chainNone allowed; once an expression is terminated with a Comparator, it is completed.
Junction
Base TypeJunction
NotesPreserves any set properties set by subexpressions.

Suppose you wanted to collect all users who performed the Shoes Bought event at least once within the last seven days, where the purchase price was greater than or equal to 100.

Another way to think of this scenario would be:

  • Collect all users who performed the Shoes Bought event.
  • Filter down to only consider events with a price greater than or equal to 100.
  • Filter for events that occurred within the last seven days.
  • Only include users who have one or more of the previous events.

Here's how you could do that in Segment's query language:

event('Shoes Bought').where( property('price') >= 100 ).within(7 days).count() >= 1

Bought and returned

bought-and-returned page anchor

This example collects:

  • all users who performed the Shoes Bought event at least once within the last 30 days
  • where the price was greater than or equal to the average spend
  • and the user performed the Shoes Returned event at least once, five days after the Shoes Bought event
1
event('Shoes Bought').where(
2
property('price') >= trait('avg_spend')
3
AND
4
event('Shoes Returned').within(parent: 5 days).count() >= 1
5
).within(30 days).count() >= 1

Did not perform Shoes Bought

did-not-perform-shoes-bought page anchor

This example collects all users who did not perform the Shoes Bought event at least once and don't have a total_spend trait with a value greater than 200:

NOT ( event('Shoes Bought').count() >= 1 AND trait('total_spend') > 200 )

Bought with minimum total spend

bought-with-minimum-total-spend page anchor

This example collects all accounts where all associated users performed the Shoes Bought event at least once and have a total_spend trait greater than 200:

ALL ( event('Shoes Bought').count() >= 1 AND trait('total_spend') > 200 )

No users bought at least once

no-users-bought-at-least-once page anchor

This example collects all accounts where no associated users performed the Shoes Bought event at least once:

ALL NOT event('Shoes Bought').count() >= 1

Any users bought at least once

any-users-bought-at-least-once page anchor

This example collects all accounts where any associated users performed the Shoes Bought event at least once:

ANY event('Shoes Bought').count() >= 1

Associated with Orders that have an association to Order Products

associated-with-orders-that-have-an-association-to-order-products page anchor

This example collects all users who have at least 1 association to an orders entity where the orders entity has at least 1 association to an order-products entity:

entity('orders').where(entity('order-products').count() >= 1).count() >= 1

Associated to Orders or is a VIP user

associated-to-orders-or-is-a-vip-user page anchor

This example collects all users who have at least 1 association to an order entity or have a VIP trait equal to true:

entity('orders').count() >= 1 OR trait('VIP') = 'true'

Associated with orders that have a total greater than 500

associated-with-orders-that-have-a-total-greater-than-500 page anchor

This example collects all users with at least 1 association to an orders entity where the orders entity has a total property greater than 500:

entity('orders').where(property('total') > 500).count() >= 1

Suppose you wanted to calculate the average spend based on all Shoes Bought events performed within the last 30 days for each user.

Another way to think of this would be:

  • Find all Shoes Bought events.
  • Filter down to only consider events that occurred within the last 30 days.
  • For these events, calculate the average spend for each user.

Here's how you could do that in Segment's query language:

event('Shoes Bought').within(30 days).avg(property('spend'))

This example calculates the minimum spend for each user, based on all Shoes Bought events, where the price was greater than 100 and the brand was My_Brand:

event('Shoes Bought').where( property('price') > 100 AND property('brand') = 'My Brand' ).min(property('spend'))

Calculate first seen spend

calculate-first-seen-spend page anchor

This example calculates the first-seen spend value for each user, based on all Shoes Bought events performed within the last 30 days:

event('Shoes Bought').within(30 days).first(property('spend'))

Most frequent spend value

most-frequent-spend-value page anchor

This example calculates the most frequent spend value for each user, based on all Shoes Bought events performed within the last 30 days. It only considers spend values that have a minimum frequency of 2:

event('Shoes Bought').within(30 days).mode(property('spend'), 2)