Search
svi.search is an immutable fluent search builder over the SAND API. You compose a search by
chaining clauses, then call a terminal. The terminals are summary(), table(), count(),
facets(), iter(), and the graph and path terminals. Every one has an async sibling
(summary_async, table_async, and so on), so the same builder works in sync and async code.
All snippets below assume svi is an authenticated SVIClient.
Before this guide
Search snippets use placeholders because the real searchable types, fields, ids, and values differ by VI deployment. Use Discover Your Environment to find:
- entity type names behind
"<your-entity-type>" - searchable field names behind
"<your-status-field>"/"<your-score-field>" - concrete ids for
("<your-entity-type>", "<your-document-id>")
Simple search
results = svi.search.text("<your-search-text>").summary(limit=10)
print(results.total) # total hits across all pages
print([hit.label for hit in results]) # current-page labels
print(results[0]["<your-status-field>"]) # SearchHit is a Mapping
Search.text(...) is safe by default. It escapes Lucene metacharacters through
Q.safe_text(...), so any input (UI fields, URL parameters, third-party payloads) parses as
literal terms. A bare AND, OR or NOT in the input is sent as a quoted word, so x NOT y
searches for the three words and excludes nothing. For raw Lucene syntax, boolean operators
included, use svi.search.query(Q.text(...)).
To expand the tenant's synonym list or match sound-alike terms, pass modes=:
svi.search.text("<your-search-text>", modes=["synonym"]).count()
svi.search.text("<your-search-text>", modes=["phonetic"]).summary(limit=10)
The SDK always sends "standard" with them, so ordinary matches still count. These modes need SAND settings and field features
that are off by default; see Using synonyms in search
and the modes= reference.
Hydration to bound Documents and Alerts stays one call away:
docs = svi.search.text("<your-search-text>").summary(limit=3).hydrate_all()
The DSL: Q, F and field
The handwritten DSL has one canonical entry point per concept:
Q.*builds query clauses (Q.text,Q.safe_text,Q.ids,Q.compound)F.*builds filter clauses (F.term,F.terms,F.range,F.date_range,F.type,F.query,F.geo_radius,F.geo_box,F.geo_polygon,F.geo_shape)field("name")returns aFieldExprfor natural Python comparisons:field("score") > 7,field("status") == "OPEN",field("queue").in_([...])
Compose with Python operators:
&= AND|= OR~= NOT (filter expressions only; wrap a query as~F.query(Q...)to negate it)
from sasvi.search import F, Q, field
search = (
svi.search
.types("<your-entity-type>", "alerts")
.query(Q.safe_text("<your-search-text>") & Q.compound("<your-compound-value>"))
.filter(
(field("<your-status-field>") == "<your-status-value>")
& (field("<your-score-field>") >= 90)
& ~F.term("archived", True)
)
)
print(search.count())
The full DSL reference (operator precedence, Lucene escape rules,
geospatial coordinate order) lives in
website/docs/Guides/search-dsl.md.
Selection
A selection marks records in the results. It does not remove any. SAND sets
selected on each graph vertex that matches the selection, so a selection is useful
with the graph terminals, for example to highlight records on an around_graph()
result. Summary and table hits do not carry the mark. To narrow the hits, use
filter(...), exclude(...) or the query instead.
Search.select(...) builds a selection inline. You pass a lambda that configures a fresh
SelectionSpec. All clauses are additive, so repeated calls AND-combine filter and query
clauses and append to the id and compound-value lists.
graph = (
svi.search
.types("<your-entity-type>")
.text("<your-search-text>")
.select(
lambda s: s.include(
ids=[("<your-entity-type>", "<your-document-id>")],
compound_values=["<your-compound-value>"],
).deselect(ids=[("<your-entity-type>", "<another-document-id>")])
)
.around_graph()
)
marked = [vertex.id for vertex in graph.vertices if vertex.selected]
.deselect(...) compiles to SAND's exclude selection clause. The verb is
renamed in the SDK so it doesn't collide with Search.exclude(filter)
(which negates a filter into the main filter tree).
SelectionSpec also takes a filter(...) and a query= on include(...) and
deselect(...), as the SAND spec documents. On Stable 2026.10, SAND answers every
search or graph request whose selection holds a query or a filter with 400 (error
95014, "The request is invalid"), and the SDK raises InvalidSearchQueryError.
Selections made of ids and compound values work.
If you want to share one selection across multiple searches, build it
explicitly and pass via selection(...):
from sasvi.search import SelectionSpec
shared = (
SelectionSpec()
.include(ids=[("<your-entity-type>", "<your-document-id>")])
.deselect(ids=[("<your-entity-type>", "<another-document-id>")])
)
graph = svi.search.types("<your-entity-type>").selection(shared).around_graph()
Pagination
Use svi.search.iter(...) to lazily walk every hit across all pages. The
iterator pulls one page at a time and yields each SearchHit. When SAND
reports a hit count, the walk runs to that count and logs a WARNING if it ends
short; without one, it stops at the first short page. page_size must be
positive, and the single-page terminals (summary, table, edges,
paths_from, connect_to, find_paths) refuse a negative start or a
non-positive limit with InvalidSearchInputError before sending anything.
for hit in svi.search.types("<your-entity-type>").text("<your-search-text>").iter(page_size=200):
process(hit)
SearchResults paginates too, through next_page() and iter_all() (plus
next_page_async() and iter_all_async()), when you would rather work one page at a time.
All of these page by offset, and a search backend limits how deep an offset may go. When the
service answers 400 or 422 for a page after the first, iter(), iter_all() and their async
siblings raise IncompleteListingError with reason="server_rejected_offset". The rows
already yielded are valid, next_start is the offset of the refused page, pages_fetched
counts the pages read, and the service's own error is the __cause__. An error on the first
page is a problem with the query and propagates unchanged, as does a 401, 403 or 429 on any
page. The depth at which SAND refuses an offset has not yet been measured on a tenant, so do
not rely on a fixed number. To read past it, narrow the query (by type, date range or another
filter) and read each slice separately.
summary() / table() accept start= (zero-based offset) and limit=
(page size) for manual control.
first_page = svi.search.types("<your-entity-type>").summary(start=0, limit=50)
second_page = first_page.next_page()
Async
Every terminal has an _async sibling. They share the same builder, so
you compose your search exactly the same way:
async def collect():
page = await svi.search.types("<your-entity-type>").text("foo").summary_async(limit=50)
async for hit in page.iter_all_async():
await process(hit)
Async variants: summary_async, table_async, count_async, facets_async, execute_async,
around_graph_async, expand_graph_async, paths_from_async, connect_to_async,
explain_match_async, iter_async. SearchPattern has find_paths_async and count_async.
See Async patterns for orchestration examples (fan-out, gather, semaphore-bounded concurrency).
Sorting
Search.sort(...) accepts four input shapes:
from sasvi.search import Order
# Typed factories
svi.search.text("foo").sort(Order.relevance())
svi.search.text("foo").sort(Order.doc(direction="descending"))
svi.search.text("foo").sort(Order.field("<your-date-field>", direction="descending"))
svi.search.text("foo").sort(
Order.compose(
Order.field("<your-status-field>"),
Order.field("<your-score-field>", direction="descending"),
)
)
# String shorthand: comma-separated, optional :direction (asc/desc)
svi.search.text("foo").sort("<your-date-field>:desc")
svi.search.text("foo").sort("<your-status-field>,<your-score-field>:desc")
It also accepts a generated VisualizationRequestOrder model or a raw
mapping for full SAND control. SearchVisualization.summary(order=...) and
SearchVisualization.table(order=...) take the same four shapes.
SAND resolves a field sort against one entity type. When the search targets
exactly one type, the SDK fills that type in on every order entry. A search
over several types must say which type each field belongs to, with
Order.field("<your-field>", entity_type="<your-entity-type>") (the string
shorthand cannot), or SAND refuses the request.
Geospatial filters
All geo helpers use (longitude, latitude) order (GeoJSON convention).
from sasvi.search import F
results = (
svi.search
.types("<your-entity-type>")
.filter(F.geo_radius(center=(-104.9903, 39.7392), radius="5km"))
.summary()
)
The other helpers are F.geo_box(top_left=..., bottom_right=...), F.geo_polygon(...) and
F.geo_shape(...). SAND geo filters run against the entity type's canonical geo field. There is
no per-call field= parameter.
F.geo_shape(...) accepts:
relation="contains" | "disjoint" | "intersects" | "within"shape={...}for inline GeoJSON-like geometryid="<stored-shape-id>"for a preconfigured stored shapestored=<Shape>to reuse a managed shape fromsvi.admin.shapes
Graph terminals
around_graph() and expand_graph() return a handwritten GraphResult wrapper with .vertices,
.edges and .counts. Each vertex and edge is itself a typed wrapper with X | None field types,
so autocomplete works and the reprs are readable. .raw gives you the underlying generated
Graph, Vertex or Edge model when you need it.
Around a search
graph = (
svi.search
.text("<your-search-text>")
.types("alerts", "<your-entity-type>")
.around_graph(vertex_types=["alerts", "<your-entity-type>"])
)
# Vertex exposes id / type_name / label / degree / valid_from / etc.
for vertex in graph.vertices:
print(vertex.id, vertex.type_name, vertex.label, vertex.degree)
# GraphCounts mirrors SAND's totals.
if graph.counts:
print(graph.counts.vertices, graph.counts.edges)
Expand outward
traversal = svi.search.text("<your-search-text>").expand_graph(depth=2)
print(len(traversal.vertices), len(traversal.edges))
expand_graph() asks SAND for its extended format by default, so traversal.edges holds the
edges between the reached vertices and each vertex carries its degree and adjacent counts. Pass
extended_format=False when you need the vertices only.
Paths from one object
paths = svi.search.paths_from(("<your-entity-type>", "<your-document-id>"))
SAND takes either one start object or types and a query. The search's types and query are therefore not sent here. Its filter is: if the start object does not match it, there are no paths.
Connections between two searches
paths = (
svi.search
.text("<your-start-search-text>")
.types("<your-entity-type>")
.connect_to(
svi.search.text("<your-end-search-text>").types("<your-entity-type>"),
hops=2,
)
)
Explain one match
highlighting = svi.search.text("<your-search-text>").explain_match(
("<your-entity-type>", "<your-document-id>"),
include_field_highlighting=True,
)
print(highlighting.id, highlighting.type_name)
It returns a HighlightingResult wrapper. Drop down to .raw for the full generated
Highlighting model.
One vertex with its metrics
vertex = svi.search.vertex(type_name="<your-entity-type>", identifier="<your-document-id>")
if vertex is not None: # None when the object is not indexed
print(vertex.label, vertex.degree, vertex.degree_by_type)
Edges for a type and query
edges() lists relationship edges with summary information for the builder's
types and query. POST /graphs/edges has no filter clause, so a builder with a
.filter(...) raises InvalidSearchInputError rather than silently dropping it.
edges = svi.search.types("<your-entity-type>").text("<your-search-text>").edges(limit=50)
all_edges = svi.search.types("<your-entity-type>").edges_all(batch_size=200, max_items=1000)
for edge in edges:
print(edge.id, edge.type_name, edge.label)
Centrality of a network
centrality() takes the network explicitly (the builder's query and filter are
not involved) and returns one CentralityMetrics row per vertex:
graph = svi.search.text("<your-search-text>").around_graph()
edges = [
(edge.id, edge.endpoints[0].id, edge.endpoints[1].id)
for edge in graph.edges
if len(edge.endpoints) == 2
]
for row in svi.search.centrality(edges=edges):
print(row.id, row.degree, row.between, row.eigen)
Edges are (id, source, target) tuples, CentralityEdgeInput values, or
mappings with those keys; an empty network is rejected.
Each graph terminal has an _async sibling and, apart from edges_all, a *_preview
twin (see Dry-run below).
Pattern search
Use pattern() for path-shaped questions. Build per-node scopes with
Q.* / F.* (via query(...) / filter(...)):
paths = (
svi.search
.pattern()
.start("<your-start-entity-type>")
.query(Q.text("<your-start-search-text>"))
.within_hops(3)
.to("<your-end-entity-type>")
.filter(F.range("<your-numeric-field>", lt=500_000))
.find_paths()
)
Notes:
pattern()must be called on a freshsvi.search. Apply per-node clauses on the pattern'sstart(...)/to(...)scopes, not on the outer search.- The current SAND graph endpoints support neither edge-scoped patterns nor
exact-hop matches. The builder has no
edge(...)method, andpattern().at_hops(...)raisesNotImplementedErrorimmediately. start(...)needs no query. Without one, every object of the type is a start object, and SAND cancels the search (error 95140) when there are too many.- A
find_paths()result pages like any other:next_page()anditer_all()request the following page with the same limits, for one hop and for several. pattern().find_paths()andpattern().count()have async siblingsfind_paths_async()/count_async().pattern().preview()returns aRequestPreviewof the requestfind_paths()would fire at its defaultstart,limitand expansion limits; it takes no arguments, so afind_paths(start=..., limit=...)call with other values has no preview.
Multi-visualization requests
from sasvi.search import SearchVisualization
response = svi.search.text("<your-search-text>").execute(
SearchVisualization.summary(limit=10),
SearchVisualization.facets(),
)
Search.facets(...) returns a Facets wrapper with .by_type(),
.by_field(name), iteration, and .raw for the underlying SAND model.
Dry-run / inspection
Every executable terminal can be previewed as a RequestPreview. That is the full wire request
the SDK would fire (method, URL, query string, headers, body) without firing it. The hit-list
terminals (summary, table, count, facets, iter) are previewed with preview(...).
Each other terminal has its own *_preview twin, listed in the table below. Use
it for inspection, logging, snapshot tests, support tickets, or to render a copy-paste curl
command.
preview = svi.search.types("alerts").text("foo").preview()
print(preview.method) # "POST"
print(preview.url) # "https://svi.example.com/svi-sand/searches"
print(preview.headers) # {Accept, Content-Type}
print(preview.body_dict) # the JSON body as plain Python
print(preview.body_model) # typed SearchRequest model
A bare preview() shows the request summary() would send at its default start and limit.
A bare execute() has no such default and raises InvalidSearchInputError; pass the same
visualizations to preview(...) and execute(...) to preview an execute.
Render as a curl command
print(preview.to_curl())
Produces a multi-line, copy-paste-able command:
curl -X POST https://svi.example.com/svi-sand/searches \
-H "Authorization: Bearer $SASVI_ACCESS_TOKEN" \
-H 'Accept: application/vnd.sas.sand.search.response+json' \
-H 'Content-Type: application/vnd.sas.sand.search.request+json' \
--data @- <<'JSON'
{
"version": 3,
"types": [
"alerts"
],
"query": {
"type": "text",
"language": "lucene",
"text": "foo"
},
"visualizations": {
"summary": {
"type": "summary",
"start": 1,
"limit": 50
}
}
}
JSON
The Authorization line uses double quotes on purpose, so the shell expands $SASVI_ACCESS_TOKEN.
Every other header is single-quoted, and a real token you pass in is shell-quoted too.
Auth renders as a $SASVI_ACCESS_TOKEN placeholder by default. Export the variable in your shell
and the command runs as is. To substitute a literal token, for a one-off paste into a sealed
ticket say, pass token=:
preview.to_curl(token=svi.auth.get_token()) # literal Bearer abc.def.ghi
preview.to_curl(multiline=False) produces a single-line variant.
Terminals and their dry-run twins
| Terminal | Dry-run twin |
|---|---|
execute(...) | preview(...) |
around_graph(...) | around_graph_preview(...) |
expand_graph(...) | expand_graph_preview(...) |
paths_from(...) | paths_from_preview(...) |
connect_to(...) | connect_to_preview(...) |
explain_match(...) | explain_match_preview(...) |
pattern().find_paths(...) | pattern().preview() |
vertex(...) | vertex_preview(...) |
edges(...) | edges_preview(...) |
centrality(...) | centrality_preview(...) |
All ten return a RequestPreview. body_model carries the typed SAND request model
(SearchRequest, GraphRequest, PathsRequest, QueryRequest, CentralityNetwork and so on).
vertex_preview is a GET, so its body_dict is None. raw_dict() is still there on Search
for the dict-only view.
Every preview has both .to_curl() and .to_httpx(). They read the same data, so the
on-the-wire request is identical.
See Preview a search request as curl or Python for end-to-end recipes (support tickets, snapshot tests, fixture generation, request diffing).
Error types
Every search failure raises a subclass of SearchOperationError:
InvalidSearchQueryError(also aValidationError). SAND rejected the assembled query or filter. The SDK also raises it when a search response carries no visualization, or not the one the terminal asked for.InvalidSearchInputError(also aTypeError). A builder got the wrong input shape, such as an int where a query belongs, or a date in a numeric range.SearchScopeError. The search scope is inconsistent, such asfields()on a multi-type search with noentity_name=, orpattern()on a search that already carries a query, filter, types or selection.
Catch SearchOperationError to handle any search failure uniformly.
Raw escape hatch
from sasvi.types.sand import SearchRequest
request = SearchRequest.from_dict({
"version": 3,
"query": {"type": "text", "language": "lucene", "text": "<your-search-text>"},
"visualizations": {"summary": {"type": "summary", "start": 1, "limit": 10}},
})
response = svi.search.from_request(request).execute()
Fluent clauses added after from_request(...) narrow the seeded request rather than replace it:
.query(...) and .filter(...) are AND-ed with the seeded clause, .types(...) appends to the
seeded types, and .selection(...) replaces the seeded selection. pattern() refuses a seeded
search, as it refuses any search that already carries a clause.
For full low-level control, use svi.api.sand.*.
Go further
- Search DSL reference covers the
Q,Fandfieldoperators in depth, plus escape rules and geo coordinate order. - Search API reference lists every method, signature and return type.
- Pagination recipe covers
iteranditer_async. - From search to bound objects covers hydration.
- Async patterns covers fan-out, gather and semaphore-bounded concurrency.
- Visual Investigator vocabulary explains SAND concepts and compound values.
- Discover Your Environment finds your real entity types, fields and ids.