Skip to main content

Search DSL reference

This page is for the practitioner who is past the search guide and needs the canonical reference for the Q (query) and F (filter) operators, the geo helpers, composition, and the Lucene escape rules.

The Q and F builders generate SAND payloads. The DSL maps closely to SAND's internal filter syntax, but the names are Python-friendly and the operators compose through Python's & and |, plus ~ on filters.

Builders at a glance​

BuilderPurpose
QTop-level query (text search, id lookup, compound boolean queries)
FField-level filter (term, range, date, type, geo, query-as-filter)
Q & QBoolean AND on queries
Q | QBoolean OR on queries
F & FBoolean AND on filters
F | FBoolean OR on filters
~FNOT on a filter
Search.text(...)Convenience wrapper around Q.safe_text(...) (use this for user input)
Search.filter(...)Add an F-shaped filter to the search

Q, the query operators​

Q.text(text, *, language="lucene")​

Direct text query, Lucene by default. The metacharacters :, *, ?, [, ], (, ), {, }, ~, ^, \, +, -, &, | and ! are read as syntax. Use Q.safe_text(...) when the input is user-controlled.

from sasvi.search import Q

Q.text("invoice")
Q.text("status:OPEN", language="lucene")
Q.text("Smith AND (John OR Jane)")

language is one of Literal["lucene", "sas"]. sas selects the SAS proprietary parser; use only when the surrounding SAND configuration requires it.

Search modes​

Q.text, Q.safe_text and Search.text take a keyword-only modes=, a list of SearchMode values ("standard", "synonym", "phonetic"). SAND then matches the text the way each listed mode asks:

Q.text("zqxbeta", modes=["synonym"]) # sends ["standard", "synonym"]
Q.safe_text("smyth", modes=["phonetic"]) # sends ["standard", "phonetic"]: also matches "smith"
  • The SDK always sends "standard" first, then your other modes without duplicates, in your order. Without "standard", a synonym or phonetic search covers only the fields that have that feature, and a phonetic-only search also loses stemming and wildcards. There is no opt-out; for a synonym-only query, pass a raw query mapping to Search.query.
  • With modes=None (the default) no modes key is sent and SAND uses its default matching.
  • An empty list, a bare string or an unknown value raises InvalidSearchInputError before any request. SAND itself rejects these with HTTP 400.
  • A compound query keeps each child's modes: in Q.text(a, modes=["synonym"]) & Q.text(b), only the first clause asks for synonyms.

Synonym and phonetic modes only find extra matches when the tenant is set up for them. See Using synonyms in search.

Q.safe_text(text, *, language="lucene")​

Escapes every Lucene metacharacter so the text matches literally. Use for any value not constant in your source code.

user_input = request.args["query"]
Q.safe_text(user_input)
InputQ.text interpretationQ.safe_text interpretation
john*Prefix match on johnLiteral john*
status:OPENField-scoped searchLiteral status:OPEN
(a OR b)Boolean expressionLiteral (a OR b)
field~3Fuzzy matchLiteral field~3

Q.ids(*object_ids)​

Match documents by their object identifiers. It accepts (type, id) tuples, sasvi.types.sand.ObjectIdentifier instances, or bound objects carrying type and id attributes.

Q.ids(("alerts", "alert-1"), ("alerts", "alert-2"))

Q.compound(*values: str)​

Match documents by SAND compound values, the composite identifiers SAND uses to dedupe across systems. Pass the compound-value strings directly. To combine queries, use the & and | operators on Q expressions instead.

Q.compound("acct:1234", "acct:5678")

# Combining text queries: use operators, not Q.compound
Q.text("invoice") & Q.text("urgent")

F, the filter operators​

Filters scope the search to documents matching a structured condition. Use them when you have a clear field-and-value constraint. Use Q when you have a freeform text match.

F.term(field, value, *, object_type=None)​

Exact-match a single value:

F.term("status", "OPEN")
F.term("score", 100)
F.term("archived", False)
F.term("status", "OPEN", object_type="alerts") # when the name is ambiguous across types

F.terms(field, values, *, object_type=None)​

Exact-match any of several values (boolean OR within one field). object_type= disambiguates the field name the same way it does on F.term:

F.terms("status", ["OPEN", "TRIAGED", "ESCALATED"])
F.terms("queue_id", ["queue-1", "queue-2"])

values must be a list or tuple with at least one value. A bare string (F.terms("status", "OPEN") would otherwise send the terms O, P, E, N), an empty sequence and a None value all raise InvalidSearchInputError instead of building a filter that reads right and matches nothing. F.term(field, None) and field(name) == None raise for the same reason: SAND has no null term.

F.range(field, *, gt=None, gte=None, lt=None, lte=None)​

Numeric range filter. All bounds are floats; for dates use F.date_range.

F.range("score", gte=50, lt=100)
F.range("amount", gt=1_000_000)

Mix open and closed bounds freely.

F.date_range(field, *, gt=None, gte=None, lt=None, lte=None, accuracy=None)​

Date / datetime range with optional bucket accuracy. Bounds accept datetime.date or datetime.datetime (not strings).

from datetime import date, datetime

F.date_range("creation_date", gte=date(2024, 1, 1), lte=date(2024, 12, 31), accuracy="day")
F.date_range("creation_date", gt=datetime(2024, 6, 1, 9, 0))

accuracy is one of the DateAccuracy Literal values: "second" | "minute" | "hour" | "day" | "month" | "year". SAND uses the bucket boundary semantics for the chosen accuracy (e.g. "day" rounds the bounds to UTC day boundaries).

F.type(*types)​

Restrict the filter to one or more entity types. On the wire this is a filter clause ({"type": "type", "types": [...]}), distinct from the top-level types list that Search.types(...) sets; the SDK never merges the two:

F.type("alerts")
F.type("alerts", "cases")

F.query(q)​

Embed a Q as a filter (when you want a freeform text query to live alongside structured filters):

F.query(Q.text("invoice")) & F.term("status", "OPEN")

Geo filters​

All geo helpers use (longitude, latitude) order, the same as GeoJSON and the opposite of how most map UIs show coordinates.

SAND geo filters run against the entity type's canonical geo field, which is configured server-side. There is no per-call field= parameter, because the SAND filter shapes (FilterTypeRadius, FilterTypeBox, FilterTypePolygon, FilterTypeShape) carry only geometry and, where it applies, a relation.

F.geo_radius(*, center, radius)​

F.geo_radius(
center=(-74.0060, 40.7128), # NYC: (lng, lat)
radius="10km",
)

radius is a number plus a unit suffix. SAND accepts mi, yd, ft, in, km, m, cm, mm and nmi, and assumes meters when the suffix is missing.

F.geo_polygon(*coordinates)​

F.geo_polygon(
(-74.01, 40.70),
(-74.01, 40.73),
(-73.97, 40.73),
(-73.97, 40.70),
)

Each point is (lng, lat).

F.geo_box(*, top_left, bottom_right)​

Axis-aligned bounding box:

F.geo_box(
top_left=(-74.01, 40.73),
bottom_right=(-73.97, 40.70),
)

F.geo_shape(*, id=None, shape=None, relation=None, stored=None)​

Match against a stored SAND shape (managed via client.admin.shapes) or an inline GeoJSON-like mapping:

F.geo_shape(id="<shape-id>", relation="within")
F.geo_shape(shape={"type": "Point", "coordinates": [-74, 40.7]}, relation="contains")

relation is one of the GeoRelation Literal values: "contains" | "disjoint" | "intersects" | "within".

Composition​

Q and F clauses support Python boolean operators:

from sasvi.search import F, Q

q = Q.safe_text("invoice") & Q.safe_text("urgent")
q = Q.safe_text("alice") | Q.safe_text("bob")

f = F.term("status", "OPEN") & F.range("score", gte=50)
f = F.term("status", "OPEN") | F.term("status", "TRIAGED")
f = ~F.term("archived", True)

# Negation exists only on filters. To negate a text query, wrap it as a filter:
f = ~F.query(Q.safe_text("archived"))

~ is defined on F expressions only. Q expressions support & and | but not ~. Precedence is Python's own, so ~ binds tighter than &, which binds tighter than |. Use parentheses for clarity:

(F.term("status", "OPEN") | F.term("status", "TRIAGED")) & F.range("score", gte=50)

Putting it all together​

from sasvi.search import F, Q

results = (
client.search
.types("alerts")
.text(user_query) # safe-by-default: escapes Lucene metacharacters
.filter(
F.terms("status", ["OPEN", "TRIAGED"])
& F.range("current_score", gte=50)
& ~F.term("archived", True)
& F.geo_radius(center=(longitude, latitude), radius="50km")
)
.fields("display_label", "current_score", "queue_id", entity_name="alerts")
.sort("creation_date:desc")
.summary(start=0, limit=50)
)

print(repr(results))
# SearchResults(returned=27, total=148)

Lucene escape rules​

When using Q.text(...) directly (not Q.safe_text), these characters require a preceding backslash to match literally:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /

Q.safe_text(...) escapes all of them for you. The choice comes down to two cases:

  • The text is a constant in your source and you want Lucene syntax. Use Q.text(...).
  • Anything else. Use Q.safe_text(...).

SAND payload semantics at a glance​

OperatorSAND payload semantic
F.term(f, v)f == v
F.terms(f, vs)f in vs
F.range(f, gte=v)f >= v
F.range(f, lt=v)f < v
F.date_range(...)Same as range plus accuracy bucket
F.type(t)Entity-type filter clause (not merged with Search.types)
F.geo_*Geospatial constraint
F.query(q)Wraps a query expression as a filter clause
f1 & f2Boolean AND
f1 | f2Boolean OR
~fBoolean NOT
Q.text(t, modes=m)Text query with "modes": m (only when modes is given)

modes is sent only when you pass it, so a text query without it keeps the plain {"type": "text", "language": ..., "text": ...} shape. SAND's published OpenAPI schema for queryTypeText does not list modes. The field appears in the same spec's highlighting examples, and the Visual Investigator UI sends it for its synonym search.

Common mistakes​

SymptomLikely causeFix
0 results for known-good searchUnescaped Lucene metacharacter in user inputSwitch from Q.text to Q.safe_text
InvalidSearchQueryErrorMixed Lucene syntax with language="sas"Pick one language and stay consistent
SearchScopeError on fields(...)Multiple types in scope, no entity_name=Add entity_name= to the fields call
Wrong field scopedF.term("X", ...) where X is on type A but not type BPass object_type="A" to F.term / F.terms
Geo filter returns no rowsCoordinates passed (lat, lng)Swap to (lng, lat)

Go further​