Skip to main content

sasvi.search

Public surface for sasvi.search.

Import the canonical names from here:

from sasvi.search import F, Q, Search, SearchPattern, SearchVisualization

The implementation is split by responsibility into private modules, which are not part of the public API: _expressions (Q, F and the expression classes), _order and _selection (sort and selection input), _wire (the SAND vocabulary shared by all of them), _request (the client-free compile into SAND request bodies), _search and _pattern (the builders that send requests), and _responses (response normalization into the result objects of sasvi.search.results).

Query and filter expressions: what a search matches.

Owns Q, F, field and FieldExpr, the immutable expression classes they return, the Lucene escaping and term serialization those expressions apply, and the coercion of every accepted query or filter input (an expression, a generated model, or a mapping) into an expression or a SAND payload. Expressions are pure values: they compile to payloads and never send anything.

QueryExpr Objects​

class QueryExpr()

Base class for handwritten search query expressions.

to_payload​

def to_payload() -> JsonObject

Render the expression to a SAND query payload.

to_dict​

def to_dict() -> JsonObject

Return the constructor-shaped query expression snapshot.

raw_dict​

def raw_dict() -> JsonObject

Return the SAND payload for this query expression.

FilterExpr Objects​

class FilterExpr()

Base class for handwritten search filter expressions.

to_payload​

def to_payload() -> JsonObject

Render the expression to a SAND filter payload.

to_dict​

def to_dict() -> JsonObject

Return the constructor-shaped filter expression snapshot.

raw_dict​

def raw_dict() -> JsonObject

Return the SAND payload for this filter expression.

TextQueryExpr Objects​

@dataclass(frozen=True)
class TextQueryExpr(QueryExpr)

Free-text query expression.

modes lists the SAND text-query modes ("standard", "synonym", "phonetic"). Any non-empty value is normalized to start with "standard", followed by the other modes without duplicates in their given order. It is sent only when non-empty, so a query without modes keeps SAND's default matching.

text​

language​

modes​

to_payload​

def to_payload() -> JsonObject

Render the free-text query as a SAND payload.

to_dict​

def to_dict() -> JsonObject

Return the constructor-shaped snapshot, omitting modes when empty.

IdsQueryExpr Objects​

@dataclass(frozen=True)
class IdsQueryExpr(QueryExpr)

Object-id query expression.

object_ids​

to_payload​

def to_payload() -> JsonObject

Render the object-id query as a SAND payload.

CompoundQueryExpr Objects​

@dataclass(frozen=True)
class CompoundQueryExpr(QueryExpr)

Compound-value query expression.

compound_values​

to_payload​

def to_payload() -> JsonObject

Render the compound-value query as a SAND payload.

QueryBooleanExpr Objects​

@dataclass(frozen=True)
class QueryBooleanExpr(QueryExpr)

Boolean query expression composed of nested query clauses.

operator​

queries​

to_payload​

def to_payload() -> JsonObject

Render the boolean query as a SAND payload.

RawQueryExpr Objects​

@dataclass(frozen=True)
class RawQueryExpr(QueryExpr)

Wrapper for an already-formed raw/generated query payload.

payload​

to_payload​

def to_payload() -> JsonObject

Return a deep-copied raw query payload.

TermsFilterExpr Objects​

@dataclass(frozen=True)
class TermsFilterExpr(FilterExpr)

Exact-match filter over one or more serialized term values.

field​

terms​

object_type​

to_payload​

def to_payload() -> JsonObject

Render the terms filter as a SAND payload.

RangeFilterExpr Objects​

@dataclass(frozen=True)
class RangeFilterExpr(FilterExpr)

Numeric range filter expression.

field​

gt​

gte​

lt​

lte​

to_payload​

def to_payload() -> JsonObject

Render the numeric range filter as a SAND payload.

DateRangeFilterExpr Objects​

@dataclass(frozen=True)
class DateRangeFilterExpr(FilterExpr)

Date/datetime range filter expression.

field​

gt​

gte​

lt​

lte​

accuracy​

to_payload​

def to_payload() -> JsonObject

Render the date range filter as a SAND payload.

TypeFilterExpr Objects​

@dataclass(frozen=True)
class TypeFilterExpr(FilterExpr)

Entity-type filter expression.

types​

to_payload​

def to_payload() -> JsonObject

Render the type filter as a SAND payload.

QueryFilterExpr Objects​

@dataclass(frozen=True)
class QueryFilterExpr(FilterExpr)

Filter expression that embeds a nested query.

query​

to_payload​

def to_payload() -> JsonObject

Render the query-backed filter as a SAND payload.

GeoBoxFilterExpr Objects​

@dataclass(frozen=True)
class GeoBoxFilterExpr(FilterExpr)

Geographic bounding-box filter expression.

coordinates​

to_payload​

def to_payload() -> JsonObject

Render the box filter as a SAND payload.

GeoPolygonFilterExpr Objects​

@dataclass(frozen=True)
class GeoPolygonFilterExpr(FilterExpr)

Geographic polygon filter expression.

coordinates​

to_payload​

def to_payload() -> JsonObject

Render the polygon filter as a SAND payload.

GeoRadiusFilterExpr Objects​

@dataclass(frozen=True)
class GeoRadiusFilterExpr(FilterExpr)

Geographic radius filter expression.

coordinates​

radius​

to_payload​

def to_payload() -> JsonObject

Render the radius filter as a SAND payload.

GeoShapeFilterExpr Objects​

@dataclass(frozen=True)
class GeoShapeFilterExpr(FilterExpr)

Geographic shape filter expression.

relation​

shape​

id​

to_payload​

def to_payload() -> JsonObject

Render the shape filter as a SAND payload.

FilterBooleanExpr Objects​

@dataclass(frozen=True)
class FilterBooleanExpr(FilterExpr)

Boolean filter expression composed of nested filter clauses.

operator​

filters​

to_payload​

def to_payload() -> JsonObject

Render the boolean filter as a SAND payload.

FilterNotExpr Objects​

@dataclass(frozen=True)
class FilterNotExpr(FilterExpr)

Negated filter expression.

filter_​

to_payload​

def to_payload() -> JsonObject

Render the negated filter as a SAND payload.

RawFilterExpr Objects​

@dataclass(frozen=True)
class RawFilterExpr(FilterExpr)

Wrapper for an already-formed raw/generated filter payload.

payload​

to_payload​

def to_payload() -> JsonObject

Return a deep-copied raw filter payload.

FieldExpr Objects​

@dataclass(frozen=True, eq=False)
class FieldExpr()

Convenience field-centric filter builder used by F and comparisons.

name​

object_type​

to_dict​

def to_dict() -> JsonObject

Return the constructor-shaped field-expression snapshot.

in_​

def in_(values: Sequence[Any]) -> FilterExpr

Build a terms filter matching any of the supplied values.

Arguments:

  • values - Allowed field values; a list or tuple, never a bare string.

Returns:

A terms filter expression.

Raises:

  • InvalidSearchInputError - When values is a bare string, is empty, or holds None.

between​

def between(lower: float | date | datetime,
upper: float | date | datetime) -> FilterExpr

Build an inclusive range filter.

Arguments:

  • lower - Inclusive lower bound.
  • upper - Inclusive upper bound.

Returns:

A numeric or date-range filter expression.

date_between​

def date_between(lower: date | datetime,
upper: date | datetime,
*,
accuracy: str | None = None) -> FilterExpr

Build an inclusive date/datetime range filter.

Arguments:

  • lower - Inclusive lower bound.
  • upper - Inclusive upper bound.
  • accuracy - Optional SAND accuracy hint.

Returns:

A date-range filter expression.

contains_query​

def contains_query(value: str | TextQueryExpr,
*,
language: str = "lucene") -> FilterExpr

Build a field-scoped text query filter.

A prebuilt TextQueryExpr keeps its language and modes.

Arguments:

  • value - Search text or a prebuilt raw TextQueryExpr.
  • language - Query parser/language identifier accepted by SAND.

Returns:

A query-backed filter expression scoped to this field.

Raises:

  • InvalidSearchQueryError - If the field name is anything other than a letter or underscore followed by letters, digits, underscores, dots and hyphens.

GeoNamespace Objects​

class GeoNamespace()

Namespace for geographic filter helpers.

box​

def box(top_left: tuple[float, float],
bottom_right: tuple[float, float]) -> FilterExpr

Build a geographic bounding-box filter.

Arguments:

  • top_left - Longitude/latitude pair for the top-left corner.
  • bottom_right - Longitude/latitude pair for the bottom-right corner.

Returns:

A geographic box filter expression.

radius​

def radius(center: tuple[float, float], radius: str) -> FilterExpr

Build a geographic radius filter.

Arguments:

  • center - Longitude/latitude pair for the circle center.
  • radius - Radius string such as "5km" or "500m".

Returns:

A geographic radius filter expression.

polygon​

def polygon(*coordinates: tuple[float, float]) -> FilterExpr

Build a geographic polygon filter.

Arguments:

  • *coordinates - Polygon points as longitude/latitude pairs.

Returns:

A geographic polygon filter expression.

shape​

def shape(*,
relation: GeoRelation | None = None,
shape: Mapping[str, Any] | None = None,
id: str | None = None,
stored: Any = None) -> FilterExpr

Build a geographic shape filter from inline GeoJSON or a stored id.

Arguments:

  • relation - Optional spatial relation. Supported values are "contains", "disjoint", "intersects", and "within".
  • shape - Optional inline GeoJSON-like mapping. Coordinate arrays should use (longitude, latitude) order.
  • id - Optional identifier of a preconfigured stored shape. Use this instead of shape when the geometry already exists in SAND configuration.
  • stored - Optional stored-shape record (e.g. the Shape returned by client.admin.shapes). Its .id is used as the stored-shape reference.

Returns:

A geographic shape filter expression.

Q Objects​

class Q()

Namespace of query builder helpers for SAND searches.

text​

@staticmethod
def text(text: str,
*,
language: Language = "lucene",
modes: Iterable[SearchMode] | None = None) -> QueryExpr

Build a free-text query expression.

text is passed to SAND verbatim. When language="lucene" (the default), SAND interprets any Lucene metacharacters in text as query syntax. Use Q.safe_text instead whenever the value comes from untrusted input.

Arguments:

  • text - Search text in the syntax expected by language.
  • language - Query parser/language identifier accepted by SAND. The common default is "lucene".
  • modes - SAND text-query modes, for example ["synonym"] to expand the tenant's synonym list or ["phonetic"] to match sound-alike terms. "standard" is always sent first, because without it SAND searches only the fields that carry the synonym or phonetic feature; the other modes follow without duplicates in your order. None (the default) sends no modes. For a synonym-only or phonetic-only query, send a raw query mapping instead.

Returns:

A query expression that can be passed to Search.query() or combined with other query expressions.

Raises:

  • InvalidSearchInputError - When modes is empty, a bare string, or holds a value other than "standard", "synonym" or "phonetic".

safe_text​

@staticmethod
def safe_text(text: str,
*,
language: Literal["lucene"] = "lucene",
modes: Iterable[SearchMode] | None = None) -> QueryExpr

Build a free-text Lucene query with metacharacters escaped.

Use this instead of Q.text whenever text originates from untrusted input (UI fields, URLs, third-party payloads). Every reserved Lucene character (+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /) is escaped, and a bare AND, OR or NOT is sent as a quoted word, so the value parses as literal terms and cannot broaden or narrow the query's scope.

Arguments:

  • text - Search text. Treated as a literal.
  • language - Must be "lucene". Other parsers do not share Lucene's escape rules and would silently misinterpret the output.
  • modes - SAND text-query modes such as ["synonym"] or ["phonetic"]. "standard" is always sent first. None (the default) sends no modes. See Q.text.

Returns:

A query expression equivalent to a literal-match against text.

Raises:

  • InvalidSearchInputError - If language is not "lucene", or modes is empty, a bare string, or holds an unknown mode.

ids​

@staticmethod
def ids(*object_ids: ObjectIdentifier | tuple[str, str] | Any) -> QueryExpr

Build an object-id query from identifiers or bound objects.

Arguments:

  • *object_ids - ObjectIdentifier instances, (type, id) tuples, or bound objects exposing type/id-like attributes.

Returns:

A query expression that targets the supplied objects directly.

compound​

@staticmethod
def compound(*values: str) -> QueryExpr

Build a compound-value query expression.

Arguments:

  • *values - Compound values as returned by SAND result payloads.

Returns:

A query expression that targets the supplied compound values.

F Objects​

class F()

Namespace of filter builder helpers for SAND searches.

term​

@staticmethod
def term(field: str,
value: Any,
*,
object_type: str | None = None) -> FilterExpr

Build an exact-match filter for one field.

Arguments:

  • field - Field name to filter on.
  • value - Exact value to match. Dates, datetimes, booleans, and numerics are normalized into the corresponding SAND filter shape.
  • object_type - Optional object/entity type name when the field name is ambiguous across types.

Returns:

A filter expression for use with Search.filter().

Raises:

  • InvalidSearchInputError - When value is None; SAND has no null term.

terms​

@staticmethod
def terms(field: str,
values: Sequence[Any],
*,
object_type: str | None = None) -> FilterExpr

Build a multi-value terms filter for one field.

Arguments:

  • field - Field name to filter on.
  • values - Allowed values for the field.
  • object_type - Optional object/entity type name when the field name is ambiguous across types.

Returns:

A filter expression that matches any supplied value.

Raises:

  • InvalidSearchInputError - When values is a bare string, is empty, or holds None.

range​

@staticmethod
def range(field: str,
*,
gt: float | None = None,
gte: float | None = None,
lt: float | None = None,
lte: float | None = None) -> FilterExpr

Build a numeric range filter for one field.

Arguments:

  • field - Field name to filter on.
  • gt - Strict lower bound.
  • gte - Inclusive lower bound.
  • lt - Strict upper bound.
  • lte - Inclusive upper bound.

Returns:

A numeric range filter expression.

date_range​

@staticmethod
def date_range(field: str,
*,
gt: date | datetime | None = None,
gte: date | datetime | None = None,
lt: date | datetime | None = None,
lte: date | datetime | None = None,
accuracy: DateAccuracy | None = None) -> FilterExpr

Build a date/datetime range filter for one field.

Arguments:

  • field - Field name to filter on.
  • gt - Strict lower datetime/date bound.
  • gte - Inclusive lower datetime/date bound.
  • lt - Strict upper datetime/date bound.
  • lte - Inclusive upper datetime/date bound.
  • accuracy - Optional SAND accuracy hint such as "day" or "second".

Returns:

A date range filter expression.

type​

@staticmethod
def type(*types: str) -> FilterExpr

Build a filter that restricts results to one or more entity types.

Arguments:

  • *types - Entity type names accepted by SAND.

Returns:

A type filter expression.

query​

@staticmethod
def query(query: QueryInput) -> FilterExpr

Wrap a query expression so it can be used as a filter clause.

Arguments:

  • query - Handwritten query expression, generated query model, or raw mapping payload.

Returns:

A filter expression containing the supplied query.

geo_box​

@staticmethod
def geo_box(*, top_left: tuple[float, float],
bottom_right: tuple[float, float]) -> FilterExpr

Build a geographic bounding-box filter.

Arguments:

  • top_left - Longitude/latitude pair for the top-left corner.
  • bottom_right - Longitude/latitude pair for the bottom-right corner.

Returns:

A geographic box filter expression.

geo_radius​

@staticmethod
def geo_radius(*, center: tuple[float, float], radius: str) -> FilterExpr

Build a geographic radius filter.

Arguments:

  • center - Longitude/latitude pair for the circle center.
  • radius - Radius string such as "5km" or "500m".

Returns:

A geographic radius filter expression.

geo_polygon​

@staticmethod
def geo_polygon(*coordinates: tuple[float, float]) -> FilterExpr

Build a geographic polygon filter.

Arguments:

  • *coordinates - Polygon points as longitude/latitude pairs.

Returns:

A geographic polygon filter expression.

geo_shape​

@staticmethod
def geo_shape(*,
relation: GeoRelation | None = None,
shape: Mapping[str, Any] | None = None,
id: str | None = None,
stored: Any = None) -> FilterExpr

Build a geographic shape filter from inline GeoJSON or a stored shape id.

Arguments:

  • relation - Optional spatial relation. Supported values are "contains", "disjoint", "intersects", and "within".
  • shape - Optional inline GeoJSON-like mapping. Coordinate arrays should use (longitude, latitude) order.
  • id - Optional identifier of a preconfigured stored shape. Use this instead of shape when the geometry already exists in SAND configuration.
  • stored - Optional stored-shape record (e.g. the Shape returned by client.admin.shapes). Its .id is used as the stored-shape reference.

Returns:

A geographic shape filter expression.

field​

def field(name: str, *, object_type: str | None = None) -> FieldExpr

Return a FieldExpr for the named field.

field("score") > 7 is the canonical, Pythonic way to compose filters via operator overloads. Equivalent to FieldExpr(name=name) plus the optional object_type qualifier when the field name is ambiguous across entity types.

Arguments:

  • name - Field name to build a field expression for.
  • object_type - Optional entity-type qualifier when the field name collides across multiple entity types in the search scope.

Returns:

A FieldExpr supporting ==, !=, <, <=, >, >=, FieldExpr.in_, FieldExpr.between, FieldExpr.date_between, and FieldExpr.contains_query.

QueryInput​

FilterInput​

Sort order input: how summary and table hits are ordered.

Owns Order and the OrderExpr it builds, the "field:desc" string shorthand, the coercion of every accepted sort input into one order payload, and the rule that qualifies an unqualified order field with the search's single entity type.

OrderEntry Objects​

@dataclass(frozen=True)
class OrderEntry()

One field-direction entry inside a multi-field order expression.

name​

direction​

entity_type​

to_payload​

def to_payload() -> JsonObject

Render this order entry to a SAND order-field payload.

OrderExpr Objects​

@dataclass(frozen=True)
class OrderExpr()

Typed sort specification compiled to a SAND visualizationRequestOrder.

Build via Order factories (Order.relevance() / Order.doc() / Order.field("name", direction="descending") / Order.compose(...)), or via the string sugar accepted by Search.sort (e.g. .sort("created:desc,score:desc")).

type_​

direction​

fields​

to_payload​

def to_payload() -> JsonObject

Render this sort spec to a SAND visualizationRequestOrder payload.

to_dict​

def to_dict() -> JsonObject

Return a snapshot of the order expression.

Order Objects​

class Order()

Typed factories for the four SAND order shapes.

Pair with Search.sort to set the visualization sort order. Search.sort also accepts a string shorthand (e.g. "created:desc,score:desc") and a raw VisualizationRequestOrder model for full-control callers.

relevance​

@staticmethod
def relevance() -> OrderExpr

Sort by relevance score (highest first by SAND default).

doc​

@staticmethod
def doc(*, direction: OrderDirection = "ascending") -> OrderExpr

Sort by document/storage order ('insertion order' across the index).

Arguments:

  • direction - "ascending" (the default) or "descending".

Returns:

A doc order expression for Search.sort.

field​

@staticmethod
def field(name: str,
*,
direction: OrderDirection = "ascending",
entity_type: str | None = None) -> OrderExpr

Sort by a single field, optionally qualified to one entity type.

Arguments:

  • name - Name of the field to sort on.
  • direction - "ascending" (the default) or "descending".
  • entity_type - Entity type the field belongs to, sent as entityType. SAND rejects an order field without one. When None and the search is scoped to exactly one entity type, that type is filled in when the request is built.

Returns:

A field order expression for Search.sort or compose.

compose​

@staticmethod
def compose(*entries: OrderExpr | OrderEntry) -> OrderExpr

Compose a multi-field sort from per-field Order.field(...) calls.

Bare OrderEntry instances are accepted too for advanced use.

Arguments:

  • *entries - Order.field(...) results or OrderEntry values, in sort priority order. A field expression holding several fields contributes all of them.

Returns:

One field order expression holding every entry in order.

Raises:

  • InvalidSearchInputError - When an entry is not a field order (for example Order.relevance()), is of another type, or when no entries are given.

OrderInput​

Graph-pattern search: paths from one node type to another.

Owns SearchPattern and PatternNodeScope, the builder returned by Search.pattern(). A one-hop pattern runs as a paths search; a longer one runs as a related-objects search between the two node scopes.

SearchPattern Objects​

@dataclass(frozen=True)
class SearchPattern()

Path-pattern builder layered on top of the fluent Search API.

to_dict​

def to_dict() -> JsonObject

Return a constructor-shaped snapshot of the path-pattern builder.

start​

def start(type_name: str) -> PatternNodeScope

Define the starting node type for the pattern.

Arguments:

  • type_name - Entity type name for the starting node.

Returns:

A node-scope builder for the start side of the pattern.

to​

def to(type_name: str) -> PatternNodeScope

Define the ending node type for the pattern.

Arguments:

  • type_name - Entity type name for the ending node.

Returns:

A node-scope builder for the end side of the pattern.

within_hops​

def within_hops(hops: int) -> SearchPattern

Restrict the pattern to a maximum hop count.

Arguments:

  • hops - Maximum number of hops between the start and end nodes; must be at least 1.

Returns:

A new pattern with the hop cap applied.

Raises:

  • SearchScopeError - When hops is less than 1. A 0 would otherwise be silently treated as 1-hop (self._hop_limit or 1), giving wrong results with no error.

at_hops​

def at_hops(hops: int) -> SearchPattern

Request an exact hop count.

Exact-hop matching is not supported by the current SAND graph endpoints, so this method raises NotImplementedError at the call site instead of failing later from find_paths.

Arguments:

  • hops - Exact number of hops between the start and end nodes.

Raises:

  • NotImplementedError - Always, whatever hops is.

find_paths​

def find_paths(*,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Execute the pattern as a path search.

Arguments:

  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • edge_expansion_limit - Cap on edges SAND follows per vertex.
  • expansion_limit - Cap on adjacent vertices SAND inspects.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • SearchScopeError - When the pattern lacks a start or an end node.
  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

find_paths_async​

async def find_paths_async(*,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Async sibling of find_paths.

Arguments:

  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • edge_expansion_limit - Cap on edges SAND follows per vertex.
  • expansion_limit - Cap on adjacent vertices SAND inspects.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • SearchScopeError - When the pattern lacks a start or an end node.
  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

count​

def count() -> int

Return the path count for the current pattern.

Returns:

The total number of paths the server reported.

Raises:

  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the server reported no path count.

count_async​

async def count_async() -> int

Asynchronously return the path count for the current pattern.

Returns:

The total number of paths the server reported.

Raises:

  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the server reported no path count.

graph​

def graph() -> GraphResult

Pattern graph rendering is not currently supported by the endpoints.

Raises:

  • NotImplementedError - Always; the graph endpoints cannot render a pattern without approximation.

preview​

def preview() -> RequestPreview

Preview the request that find_paths would fire at its defaults.

Dispatches to the same SAND operation find_paths would call (one-hop → /paths, multi-hop → /relatedObjects) and returns a RequestPreview capturing the full wire request. The typed body model is reachable via .body_model. This method takes no arguments, so the preview shows the default start, limit and expansion limits; a find_paths(start=..., limit=...) call with other values is not previewable.

Raises:

  • SearchScopeError - When the pattern lacks a start or an end node.

PatternNodeScope Objects​

@dataclass(frozen=True)
class PatternNodeScope()

Fluent scope for adding query and filter clauses to a graph pattern node.

query​

def query(query: QueryInput) -> PatternNodeScope

Add a query clause to the current pattern node.

Arguments:

  • query - Handwritten query expression, generated query model, or raw mapping.

Returns:

The updated node-scope builder.

filter​

def filter(filter_: FilterInput) -> PatternNodeScope

Add a filter clause to the current pattern node.

Arguments:

  • filter_ - Handwritten filter expression, generated filter model, or raw mapping.

Returns:

The updated node-scope builder.

exclude​

def exclude(filter_: FilterInput) -> PatternNodeScope

Exclude matches from the current pattern node.

Arguments:

  • filter_ - Filter expression to negate and apply.

Returns:

The updated node-scope builder.

within_hops​

def within_hops(hops: int) -> SearchPattern

Restrict the overall pattern to a maximum hop count.

Arguments:

  • hops - Maximum number of hops between the start and end nodes.

Returns:

The updated pattern.

at_hops​

def at_hops(hops: int) -> SearchPattern

Request an exact hop count on the overall pattern.

Forwards to SearchPattern.at_hops, which raises NotImplementedError immediately.

Arguments:

  • hops - Exact number of hops between the start and end nodes.

Raises:

  • NotImplementedError - Always, whatever hops is.

to​

def to(type_name: str) -> PatternNodeScope

Define the ending node type for the pattern.

Arguments:

  • type_name - Entity type name for the ending node.

Returns:

The end-node scope builder.

find_paths​

def find_paths(*,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Execute the current pattern as a path search.

Arguments:

  • start - Zero-based offset of the first path to return.
  • limit - Maximum number of paths per page.
  • edge_expansion_limit - Maximum number of edges the service expands.
  • expansion_limit - Maximum number of vertices the service expands.

Returns:

Normalized path results.

find_paths_async​

async def find_paths_async(*,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Async sibling of find_paths, forwarding to the pattern.

Arguments:

  • start - Zero-based offset of the first path to return.
  • limit - Maximum number of paths per page.
  • edge_expansion_limit - Maximum number of edges the service expands.
  • expansion_limit - Maximum number of vertices the service expands.

Returns:

Normalized path results.

count​

def count() -> int

Return the path count for the current pattern.

count_async​

async def count_async() -> int

Async sibling of count, forwarding to the pattern.

Returns:

The path count for the current pattern.

preview​

def preview() -> RequestPreview

Forward to SearchPattern.preview.

graph​

def graph() -> GraphResult

Forward to the pattern graph helper.

Raises NotImplementedError immediately, because the current SAND graph endpoints do not support pattern graph rendering.

Request building: the client-free compile from search state to SAND requests.

Owns _SearchClauses, which holds the clauses of a search and compiles them into each SAND request body (search, graph, traversal, paths, related objects, edges, highlighting), and SearchVisualization, which builds the visualization blocks of a search request. Also owns the request-level rules that are not part of any one expression: page bounds, type lists, the match-all query some endpoints need, combining a seeded clause with a built one, the centrality network body, and the one-hop path body of a pattern.

Nothing here holds a client, so every request a search would send can be built and inspected without one.

SearchVisualization Objects​

@dataclass(frozen=True)
class SearchVisualization()

Visualization request helper for search responses.

name​

request​

summary​

@classmethod
def summary(cls,
*,
name: str = "summary",
start: int = 1,
limit: int = 50,
fields: Sequence[ObjectTypeFields] | None = None,
order: OrderInput | None = None) -> SearchVisualization

Request summary-style hits from a search execution.

Arguments:

  • name - Visualization key used in the request payload.
  • start - One-based result offset used by SAND summary views.
  • limit - Maximum number of hits to return.
  • fields - Optional explicit field selection payloads.
  • order - Optional sort, in any form Search.sort accepts.

Returns:

A visualization request wrapper for Search.execute().

Raises:

  • InvalidSearchInputError - When order is not a supported sort input.

table​

@classmethod
def table(cls,
*,
name: str = "table",
start: int = 1,
limit: int = 50,
fields: Sequence[ObjectTypeFields] | None = None,
order: OrderInput | None = None) -> SearchVisualization

Request table-style hits from a search execution.

Arguments:

  • name - Visualization key used in the request payload.
  • start - One-based result offset used by SAND table views.
  • limit - Maximum number of hits to return.
  • fields - Optional explicit field selection payloads.
  • order - Optional sort, in any form Search.sort accepts.

Returns:

A visualization request wrapper for Search.execute().

Raises:

  • InvalidSearchInputError - When order is not a supported sort input.

count​

@classmethod
def count(cls, *, name: str = "hits") -> SearchVisualization

Request a hit-count visualization.

Arguments:

  • name - Visualization key used in the request payload.

Returns:

A visualization request wrapper for hit counts.

facets​

@classmethod
def facets(cls,
*,
name: str = "facets",
facet_types: str | Sequence[str] | None = None,
mode: FacetMode = "filter") -> SearchVisualization

Request a facets visualization.

Arguments:

  • name - Visualization key used in the request payload.
  • facet_types - Optional type restriction for the facet calculation.
  • mode - Facet mode sent to SAND, typically "filter".

Returns:

A visualization request wrapper for facets.

to_payload​

def to_payload() -> JsonObject

Return the visualization request as a plain payload dictionary.

to_dict​

def to_dict() -> JsonObject

Return a constructor-shaped snapshot of the visualization request.

raw_dict​

def raw_dict() -> JsonObject

Return the SAND visualization request payload.

CentralityEdgeInput Objects​

@dataclass(frozen=True, slots=True)
class CentralityEdgeInput()

One edge of the network handed to Search.centrality.

Attributes:

  • id - The edge's identifier (any string unique within the network).
  • source - The vertex id the edge starts at.
  • target - The vertex id the edge ends at.

id​

source​

target​

coerce​

@classmethod
def coerce(
cls, value: CentralityEdgeInput | tuple[str, str, str] | Mapping[str, Any]
) -> CentralityEdgeInput

Lift an (id, source, target) tuple or mapping into an edge input.

Arguments:

  • value - A CentralityEdgeInput, a three-tuple of (id, source, target), or a mapping with those keys.

Returns:

The edge input.

Raises:

  • InvalidSearchInputError - When value has none of those shapes.

to_dict​

def to_dict() -> JsonObject

Return {"id": ..., "source": ..., "target": ...}.

raw_dict​

def raw_dict() -> JsonObject

Return the SAND CentralityEdge wire shape (adds version).

Response normalization: turning SAND responses into result objects.

Owns the facets result (Facets, FacetBucket), the lookup of one visualization in a search response, hit counts, and the conversion of summary hits, table rows and path collections into the result objects of sasvi.search.results.

FacetBucket Objects​

@dataclass(frozen=True)
class FacetBucket()

One bucket inside a facet result, holding a value and its hit count.

label​

count​

raw​

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the bucket.

Facets Objects​

@dataclass(frozen=True)
class Facets()

Lightweight wrapper over a SAND facets visualization response.

Exposes the buckets through Pythonic helpers (by_type, by_field, iteration) so callers don't need to walk the raw nested SAND model.

The raw model is still available via raw for advanced cases.

raw​

mode​

@property
def mode() -> str | None

The mode echoed back by SAND on the facets response.

fields​

def fields() -> list[str]

Return the field names that produced facet buckets.

by_field​

def by_field(name: str) -> list[FacetBucket]

Return the buckets for one field, or an empty list if absent.

Arguments:

  • name - Field name as SAND reports it, one of fields. When several entity types facet the same field name, the first group's buckets are returned.

Returns:

The field's buckets, or [] when no facet has that name.

by_type​

def by_type() -> dict[str, int]

Return a {entity_type_name: hit_count} mapping.

Mirrors the per-type breakdown that SAND surfaces when the facets request returns type-level aggregations.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the facet buckets.

The Search builder and its execution against SAND.

Search is the fluent, immutable entry point: its chaining methods record clauses, and its terminals (summary, count, facets, execute, the graph and path operations, and their _async and _preview siblings) compile the clauses through _request._SearchClauses, send the request through the SAND API, and normalize the response.

Search Objects​

@dataclass(frozen=True)
class Search()

Immutable fluent search builder over the handwritten SAND layer.

Each chaining method returns a new Search instance so callers can reuse base searches and derive narrower variants without mutating shared state.

sand_api​

documents​

alerts​

from_request​

def from_request(request: SearchRequest | Mapping[str, Any]) -> Search

Seed the search from an existing raw/generated search request.

Fluent clauses added afterwards narrow the seeded request: a later query or filter is AND-ed with the seeded clause, and types appends to the seeded types. selection replaces the seeded selection.

Arguments:

  • request - Generated SearchRequest model or plain payload mapping.

Returns:

A new Search rooted in the supplied request payload.

to_dict​

def to_dict() -> JsonObject

Return a constructor-shaped snapshot of the fluent search builder.

raw_dict​

def raw_dict() -> JsonObject

Return the compiled SAND request payload for the current search.

query​

def query(query: QueryInput) -> Search

Add a query expression to the search.

Arguments:

  • query - Handwritten query expression, generated query model, or raw mapping payload.

Returns:

A new Search with the additional query clause applied.

filter​

def filter(filter_: FilterInput) -> Search

Add a filter expression to the search.

Arguments:

  • filter_ - Handwritten filter expression, generated filter model, or raw mapping payload.

Returns:

A new Search with the additional filter clause applied.

exclude​

def exclude(filter_: FilterInput) -> Search

Exclude results matching the given filter expression.

Arguments:

  • filter_ - Handwritten filter expression, generated filter model, or raw mapping payload to negate and apply.

Returns:

A new Search with the exclusion filter applied.

text​

def text(text: str, *, modes: Iterable[SearchMode] | None = None) -> Search

Add a free-text query clause, escaping Lucene metacharacters.

Search.text is safe by default. Q.safe_text escapes every Lucene metacharacter in text and quotes a bare AND, OR or NOT, so any value (including untrusted input) parses as literal terms.

For raw Lucene syntax (wildcards, field-scoped searches, boolean operators), use Search.query(Q.text(...)). For the SAS parser, use Search.query(Q.text(..., language="sas")).

Arguments:

  • text - Search text. Treated as a literal, so special characters do not retain their Lucene meaning.
  • modes - SAND text-query modes such as ["synonym"] or ["phonetic"]. "standard" is always sent first. None (the default) sends no modes. See Q.text.

Returns:

A new Search with the safe text query applied.

Raises:

  • InvalidSearchInputError - When modes is empty, a bare string, or holds an unknown mode.

types​

def types(*type_names: str) -> Search

Restrict the search to one or more entity types.

Repeated calls append: .types("alerts").types("cases") produces a search scoped to both alerts and cases. Duplicate names are kept, and in their original order, so the payload on the wire matches what the caller asked for exactly.

Arguments:

  • *type_names - Entity type names accepted by SAND.

Returns:

A new Search restricted to those types in addition to any previously scoped types.

selection​

def selection(selection: SelectionInput) -> Search

Attach a SAND selection payload used by graph-style operations.

Arguments:

  • selection - SelectionSpec, generated Selection model, or raw mapping payload.

Returns:

A new Search with the selection payload attached.

fields​

def fields(*field_names: str, entity_name: str | None = None) -> Search

Request a narrower field set for summary/table visualizations.

Repeated calls accumulate per-entity-type selections:

  • Same entity_name twice: field names are merged into one ObjectTypeFields payload, preserving order, dropping duplicates.
  • Different entity_name values: separate ObjectTypeFields payloads are appended, enabling multi-type table views.

entity_name defaults to the search's single scoped type when the search targets exactly one type. When the search targets multiple types, entity_name must be supplied explicitly so the SDK knows which type the fields belong to.

Arguments:

  • *field_names - Field names to request in summary/table visualizations.
  • entity_name - Explicit entity type name. Required when the search targets more than one type; inferred from types() when the search is scoped to exactly one type.

Returns:

A new Search with the visualization field selection attached.

Raises:

  • SearchScopeError - If entity_name cannot be inferred and was not supplied.

sort​

def sort(order: OrderInput) -> Search

Set the visualization ordering for summary/table views.

order accepts:

  • An OrderExpr from the Order factories (Order.relevance(), Order.doc(), Order.field("name"), Order.compose(...)).
  • A string shorthand: "created:desc" or "status:asc,score:desc" (comma-separated field[:dir] entries; dir is asc/ascending/desc/descending).
  • A generated VisualizationRequestOrder model or a raw mapping payload for full SAND control.

Arguments:

  • order - The ordering, in any of the forms above. It replaces any ordering set before.

Returns:

A new Search with the ordering attached.

Raises:

  • InvalidSearchInputError - When order is none of the forms above, or a string shorthand is empty or names an unknown direction.

select​

def select(builder: Callable[[SelectionSpec], SelectionSpec]) -> Search

Build and attach a selection inline.

The builder callable receives a fresh SelectionSpec and returns the configured spec. The resulting selection is attached to the search via selection.

For reusable / standalone selections, instantiate SelectionSpec directly and pass the result to selection.

Arguments:

  • builder - Callable that takes an empty SelectionSpec and returns the configured spec.

Returns:

A new Search with the selection attached.

Example:

search.select( lambda s: s.include(ids=[("alerts", "alert-1"), ("alerts", "alert-2")]) .deselect(ids=[("alerts", "alert-2")]) )

pattern​

def pattern() -> SearchPattern

Start a graph/path pattern builder from this search root.

Must be called on a fresh search. Apply per-node query/filter on the resulting pattern's start(...) / to(...) scopes instead of chaining clauses onto the outer search. The outer search's query and filter would otherwise be silently dropped.

Raises:

  • SearchScopeError - If the search already has a query, filter, explicit types, selection or seeded request attached.

summary​

def summary(*, start: int = 0, limit: int = 50) -> SearchResults

Execute the search as a summary-hit request.

Arguments:

  • start - Zero-based result offset within the full result set.
  • limit - Maximum number of hits to return for this page.

Returns:

A SearchResults page that knows how to fetch siblings via SearchResults.next_page / SearchResults.iter_all.

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no summary visualization.

table​

def table(*, start: int = 0, limit: int = 50) -> SearchResults

Execute the search as a table-hit request.

Arguments:

  • start - Zero-based result offset within the full result set.
  • limit - Maximum number of hits to return for this page.

Returns:

A SearchResults page (table view).

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no table visualization.

summary_async​

async def summary_async(*, start: int = 0, limit: int = 50) -> SearchResults

Asynchronously execute the search as a summary-hit request.

Arguments:

  • start - Zero-based result offset within the full result set.
  • limit - Maximum number of hits to return for this page.

Returns:

A SearchResults page (summary view).

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no summary visualization.

table_async​

async def table_async(*, start: int = 0, limit: int = 50) -> SearchResults

Asynchronously execute the search as a table-hit request.

Arguments:

  • start - Zero-based result offset within the full result set.
  • limit - Maximum number of hits to return for this page.

Returns:

A SearchResults page (table view).

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no table visualization.

iter​

def iter(*,
page_size: int = 100,
view: SearchView = "summary") -> Iterator[SearchHit]

Lazily walk every hit by paginating page_size at a time.

This is the canonical pagination helper for large result sets. It 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. Halt iteration to halt paging.

Arguments:

  • page_size - Number of hits to request per page; must be positive.
  • view - Which visualization shape SAND returns per page, "summary" (default) or "table".

Yields:

Every SearchHit matching the current search scope.

Raises:

  • InvalidSearchInputError - When page_size is not positive.
  • SearchOperationError - When SAND rejects a page request.
  • InvalidSearchQueryError - When a response carries no hit visualization.
  • IncompleteListingError - When the server stops advancing, the page cap is reached, or a page after the first is refused.

iter_async​

async def iter_async(*,
page_size: int = 100,
view: SearchView = "summary") -> AsyncIterator[SearchHit]

Asynchronously walk every hit by paginating page_size at a time.

Same completeness contract as iter.

Arguments:

  • page_size - Number of hits to request per page; must be positive.
  • view - Which visualization shape SAND returns per page, "summary" (default) or "table".

Yields:

Every SearchHit matching the current search scope.

Raises:

  • InvalidSearchInputError - When page_size is not positive.
  • SearchOperationError - When SAND rejects a page request.
  • InvalidSearchQueryError - When a response carries no hit visualization.
  • IncompleteListingError - When the server stops advancing, the page cap is reached, or a page after the first is refused.

count​

def count() -> int

Execute the search as a hit-count request.

Returns:

Total matching hits for the current builder state.

Raises:

  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no hit count.

facets​

def facets(*,
facet_types: str | Sequence[str] | None = None,
mode: FacetMode = "filter") -> Facets

Execute the search as a facets request.

Arguments:

  • facet_types - Optional type restriction for the facet calculation.
  • mode - Facet mode sent to SAND.

Returns:

The generated facets visualization payload.

execute​

def execute(
*visualizations: SearchVisualization | Mapping[str, Any] | Any
) -> SearchResponseSnapshot

Execute the search with one or more visualization requests.

Arguments:

  • *visualizations - SearchVisualization helpers, generated visualization models, or raw payload mappings.

Returns:

A SearchResponseSnapshot wrapping the SAND SearchResponse with a readable visualizations dict and clean repr(). Drop down to .raw for the typed model.

execute_async​

async def execute_async(
*visualizations: SearchVisualization | Mapping[str, Any] | Any
) -> SearchResponseSnapshot

Asynchronously execute the search.

Arguments:

  • *visualizations - SearchVisualization helpers, generated visualization models, or raw payload mappings.

Returns:

A SearchResponseSnapshot (see execute).

count_async​

async def count_async() -> int

Asynchronously execute the search as a hit-count request.

Returns:

Total matching hits for the current builder state.

Raises:

  • SearchOperationError - When SAND rejects the request.
  • InvalidSearchQueryError - When the response carries no hit count.

facets_async​

async def facets_async(*,
facet_types: str | Sequence[str] | None = None,
mode: FacetMode = "filter") -> Facets

Asynchronously execute the search as a facets request.

Arguments:

  • facet_types - Optional type restriction for the facet calculation.
  • mode - Facet mode sent to SAND.

Returns:

The generated facets visualization payload.

around_graph_preview​

def around_graph_preview(
*,
vertex_types: str | Sequence[str] | None = None,
edge_types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
selection: SelectionInput | None = None,
calculate_metrics: bool = True,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> RequestPreview

Preview the request that around_graph would fire.

Nothing is sent. Call .to_curl() on the result to render a copy-paste curl command, or read .body_model for the typed GraphRequest.

Arguments:

  • vertex_types - Entity types to place in the graph, sent as vertexTypes. Defaults to the search's types; with neither, SAND includes every type.
  • edge_types - Relationship types to include, sent as edgeTypes. None includes every type.
  • filters - Extra filter AND-ed with the search's filter.
  • selection - Selection to send in place of the one attached with selection.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex. The calculation is slow on highly connected vertices; pass False when the counts are not needed.
  • expansion_limit - Most adjacent vertices a vertex may have. A vertex above the limit is left out of the edge search and the metrics.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

A RequestPreview holding the method, URL, query string, headers, and body.

around_graph​

def around_graph(*,
vertex_types: str | Sequence[str] | None = None,
edge_types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
selection: SelectionInput | None = None,
calculate_metrics: bool = True,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> GraphResult

Build a graph around the current query/filter scope.

Arguments:

  • vertex_types - Entity types to place in the graph, sent as vertexTypes. Defaults to the search's types; with neither, SAND includes every type.
  • edge_types - Relationship types to include, sent as edgeTypes. None includes every type.
  • filters - Extra filter AND-ed with the search's filter.
  • selection - Selection to send in place of the one attached with selection.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex. The calculation is slow on highly connected vertices; pass False when the counts are not needed.
  • expansion_limit - Most adjacent vertices a vertex may have. A vertex above the limit is left out of the edge search and the metrics.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

The objects that matched the search as vertices, and the relationships between them as edges.

Raises:

  • SearchOperationError - When SAND rejects the request.

around_graph_async​

async def around_graph_async(
*,
vertex_types: str | Sequence[str] | None = None,
edge_types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
selection: SelectionInput | None = None,
calculate_metrics: bool = True,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> GraphResult

Async sibling of around_graph.

Arguments:

  • vertex_types - Entity types to place in the graph, sent as vertexTypes. Defaults to the search's types; with neither, SAND includes every type.
  • edge_types - Relationship types to include, sent as edgeTypes. None includes every type.
  • filters - Extra filter AND-ed with the search's filter.
  • selection - Selection to send in place of the one attached with selection.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex. The calculation is slow on highly connected vertices; pass False when the counts are not needed.
  • expansion_limit - Most adjacent vertices a vertex may have. A vertex above the limit is left out of the edge search and the metrics.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

The objects that matched the search as vertices, and the relationships between them as edges.

Raises:

  • SearchOperationError - When SAND rejects the request.

centrality_preview​

def centrality_preview(
*, edges: Sequence[CentralityEdgeInput | tuple[str, str, str]
| Mapping[str, Any]]
) -> RequestPreview

Preview the request that centrality would fire.

Arguments:

  • edges - The network's edges as CentralityEdgeInput, (id, source, target) tuples or mappings.

Returns:

A RequestPreview; .body_model is the typed CentralityNetwork.

Raises:

  • InvalidSearchInputError - When edges is empty or an edge is malformed.

centrality​

def centrality(
*, edges: Sequence[CentralityEdgeInput | tuple[str, str, str]
| Mapping[str, Any]]
) -> list[CentralityMetrics]

Compute centrality metrics for a network (POST /centrality).

The network is given explicitly; the builder's query, filter and types are not involved. Vertex ids are whatever the edges reference, e.g. "person~123" from a GraphResult.

Arguments:

  • edges - The network's edges as CentralityEdgeInput, (id, source, target) tuples or mappings.

Returns:

One CentralityMetrics row per vertex.

Raises:

  • InvalidSearchInputError - When edges is empty or an edge is malformed.
  • SearchOperationError - When SAND rejects the request.

centrality_async​

async def centrality_async(
*, edges: Sequence[CentralityEdgeInput | tuple[str, str, str]
| Mapping[str, Any]]
) -> list[CentralityMetrics]

Async sibling of centrality.

Arguments:

  • edges - The network's edges as CentralityEdgeInput, (id, source, target) tuples or mappings.

Returns:

One CentralityMetrics row per vertex.

Raises:

  • InvalidSearchInputError - When edges is empty or an edge is malformed.
  • SearchOperationError - When SAND rejects the request.

edges_preview​

def edges_preview(*, start: int = 0, limit: int = 100) -> RequestPreview

Preview the request that edges would fire.

Arguments:

  • start - Zero-based offset of the first edge.
  • limit - Page size.

Returns:

A RequestPreview; .body_model is the typed QueryRequest.

Raises:

  • InvalidSearchInputError - When the builder carries a filter or no query.

edges​

def edges(*, start: int = 0, limit: int = 100) -> list[Edge]

Find edges matching the builder's types and query (POST /graphs/edges).

Arguments:

  • start - Zero-based offset of the first edge.
  • limit - Page size.

Returns:

One page of Edge wrappers with summary information.

Raises:

  • InvalidSearchInputError - When the builder carries a filter (the endpoint has no filter clause) or no query (the endpoint rejects an empty query), or when start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

edges_async​

async def edges_async(*, start: int = 0, limit: int = 100) -> list[Edge]

Async sibling of edges.

Arguments:

  • start - Zero-based offset of the first edge.
  • limit - Page size.

Returns:

One page of Edge wrappers.

Raises:

  • InvalidSearchInputError - When the builder carries a filter or no query, or when start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

edges_all​

def edges_all(*,
batch_size: int = 100,
max_items: int | None = None) -> list[Edge]

Collect every matching edge, paging until exhausted.

Arguments:

  • batch_size - Page size per request; must be greater than 0.
  • max_items - Optional ceiling on the number of edges returned.

Returns:

Every matching Edge across the pages.

Raises:

  • InvalidSearchInputError - When batch_size is not positive or the builder carries a filter.
  • SearchOperationError - When SAND rejects a page.

edges_all_async​

async def edges_all_async(*,
batch_size: int = 100,
max_items: int | None = None) -> list[Edge]

Async sibling of edges_all.

Arguments:

  • batch_size - Page size per request; must be greater than 0.
  • max_items - Optional ceiling on the number of edges returned.

Returns:

Every matching Edge across the pages.

Raises:

  • InvalidSearchInputError - When batch_size is not positive or the builder carries a filter.
  • SearchOperationError - When SAND rejects a page.

vertex_preview​

def vertex_preview(*,
type_name: str,
identifier: str,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> RequestPreview

Preview the request that vertex would fire.

Arguments:

  • type_name - The SAND type of the vertex.
  • identifier - The object id within that type.
  • expansion_limit - Cap on adjacent vertices SAND inspects.
  • metrics_limit - Cap on edges SAND inspects for the metrics.
  • metrics_aggregation_limit - Cap on per-type aggregation (-1 for no cap).

Returns:

A RequestPreview for the GET.

vertex​

def vertex(*,
type_name: str,
identifier: str,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> Vertex | None

Fetch one vertex with its degree metrics (GET /vertices/{type}/{id}).

Arguments:

  • type_name - The SAND type of the vertex.
  • identifier - The object id within that type.
  • expansion_limit - Cap on adjacent vertices SAND inspects.
  • metrics_limit - Cap on edges SAND inspects for the metrics.
  • metrics_aggregation_limit - Cap on per-type aggregation (-1 for no cap).

Returns:

The Vertex, or None when the object is not indexed.

Raises:

  • SearchOperationError - When SAND rejects the request.

vertex_async​

async def vertex_async(*,
type_name: str,
identifier: str,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> Vertex | None

Async sibling of vertex.

Arguments:

  • type_name - The SAND type of the vertex.
  • identifier - The object id within that type.
  • expansion_limit - Cap on adjacent vertices SAND inspects.
  • metrics_limit - Cap on edges SAND inspects for the metrics.
  • metrics_aggregation_limit - Cap on per-type aggregation.

Returns:

The Vertex, or None when the object is not indexed.

Raises:

  • SearchOperationError - When SAND rejects the request.

expand_graph_preview​

def expand_graph_preview(
*,
vertex_types: str | Sequence[str] | None = None,
vertex_filter: FilterInput | None = None,
edge_types: str | Sequence[str] | None = None,
edge_filter: FilterInput | None = None,
depth: int = 1,
extended_format: bool = True,
graph_object_ids: Sequence[ObjectIdentifier | tuple[str, str] | Any]
| None = None,
graph_compound_values: Sequence[str] | None = None,
calculate_metrics: bool = True,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> RequestPreview

Preview the request that expand_graph would fire.

Arguments:

  • vertex_types - Entity types the traversal may reach. Defaults to the builder's types.
  • vertex_filter - Filter every reached vertex must match.
  • edge_types - Relationship types the traversal may follow.
  • edge_filter - Filter every followed edge must match.
  • depth - Number of hops to expand from the search scope.
  • extended_format - Ask SAND for the extended format, which returns the edges and each vertex's degree and adjacent counts. On by default; False returns the vertices only.
  • graph_object_ids - Extra vertices to include, as ObjectIdentifier values or (type, id) pairs.
  • graph_compound_values - Extra compound values to include.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

The request, built but not sent.

expand_graph​

def expand_graph(*,
vertex_types: str | Sequence[str] | None = None,
vertex_filter: FilterInput | None = None,
edge_types: str | Sequence[str] | None = None,
edge_filter: FilterInput | None = None,
depth: int = 1,
extended_format: bool = True,
graph_object_ids: Sequence[ObjectIdentifier | tuple[str, str]
| Any] | None = None,
graph_compound_values: Sequence[str] | None = None,
calculate_metrics: bool = True,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> GraphResult

Traverse outward from the current search scope to expand a graph.

Arguments:

  • vertex_types - Entity types the traversal may reach. Defaults to the builder's types.
  • vertex_filter - Filter every reached vertex must match.
  • edge_types - Relationship types the traversal may follow.
  • edge_filter - Filter every followed edge must match.
  • depth - Number of hops to expand from the search scope.
  • extended_format - Ask SAND for the extended format, which returns the edges and each vertex's degree and adjacent counts. On by default; False returns the vertices only.
  • graph_object_ids - Extra vertices to include, as ObjectIdentifier values or (type, id) pairs.
  • graph_compound_values - Extra compound values to include.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

The traversed graph.

Raises:

  • SearchOperationError - When SAND rejects the traversal.

expand_graph_async​

async def expand_graph_async(
*,
vertex_types: str | Sequence[str] | None = None,
vertex_filter: FilterInput | None = None,
edge_types: str | Sequence[str] | None = None,
edge_filter: FilterInput | None = None,
depth: int = 1,
extended_format: bool = True,
graph_object_ids: Sequence[ObjectIdentifier | tuple[str, str] | Any]
| None = None,
graph_compound_values: Sequence[str] | None = None,
calculate_metrics: bool = True,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> GraphResult

Asynchronously traverse outward from the current search scope.

Arguments:

  • vertex_types - Entity types the traversal may reach. Defaults to the builder's types.
  • vertex_filter - Filter every reached vertex must match.
  • edge_types - Relationship types the traversal may follow.
  • edge_filter - Filter every followed edge must match.
  • depth - Number of hops to expand from the search scope.
  • extended_format - Ask SAND for the extended format, which returns the edges and each vertex's degree and adjacent counts. On by default; False returns the vertices only.
  • graph_object_ids - Extra vertices to include, as ObjectIdentifier values or (type, id) pairs.
  • graph_compound_values - Extra compound values to include.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

The traversed graph.

Raises:

  • SearchOperationError - When SAND rejects the traversal.

paths_from_preview​

def paths_from_preview(object_ref: ObjectIdentifier | tuple[str, str] | Any,
*,
types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
next_level: Any | None = None,
start: int = 0,
limit: int = 20,
calculate_metrics: bool = False,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> RequestPreview

Preview the request that paths_from would fire.

Nothing is sent, and start and limit are not range-checked.

Arguments:

  • object_ref - The seed object, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • types - Not sent, and neither are the search's types and query: SAND takes either one start object or types and a query. To restrict the hops, use next_level.
  • filters - Extra filter AND-ed with the search's filter. The seed object has to match it, or SAND returns no paths.
  • next_level - Raw nextLevel payload that restricts the next hop, with the SAND keys vertexTypes, vertexFilter, edgeTypes, edgeFilter and a nested nextLevel.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex on the paths. Off by default because it is slow on highly connected vertices.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

A RequestPreview holding the method, URL, query string, headers, and body.

Raises:

  • InvalidSearchInputError - When object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.

paths_from​

def paths_from(object_ref: ObjectIdentifier | tuple[str, str] | Any,
*,
types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
next_level: Any | None = None,
start: int = 0,
limit: int = 20,
calculate_metrics: bool = False,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> PathResults

Find paths that start from a concrete object and match this search scope.

Arguments:

  • object_ref - The seed object, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • types - Not sent, and neither are the search's types and query: SAND takes either one start object or types and a query. To restrict the hops, use next_level.
  • filters - Extra filter AND-ed with the search's filter. The seed object has to match it, or SAND returns no paths.
  • next_level - Raw nextLevel payload that restricts the next hop, with the SAND keys vertexTypes, vertexFilter, edgeTypes, edgeFilter and a nested nextLevel.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex on the paths. Off by default because it is slow on highly connected vertices.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • InvalidSearchInputError - When start is negative, limit is not positive, or object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.
  • SearchOperationError - When SAND rejects the request.

paths_from_async​

async def paths_from_async(object_ref: ObjectIdentifier | tuple[str, str]
| Any,
*,
types: str | Sequence[str] | None = None,
filters: FilterInput | None = None,
next_level: Any | None = None,
start: int = 0,
limit: int = 20,
calculate_metrics: bool = False,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000,
metrics_limit: int = 5000,
metrics_aggregation_limit: int = -1) -> PathResults

Async sibling of paths_from.

Arguments:

  • object_ref - The seed object, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • types - Not sent, and neither are the search's types and query: SAND takes either one start object or types and a query. To restrict the hops, use next_level.
  • filters - Extra filter AND-ed with the search's filter. The seed object has to match it, or SAND returns no paths.
  • next_level - Raw nextLevel payload that restricts the next hop, with the SAND keys vertexTypes, vertexFilter, edgeTypes, edgeFilter and a nested nextLevel.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • calculate_metrics - Calculate degree and adjacent counts for every vertex on the paths. Off by default because it is slow on highly connected vertices.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.
  • metrics_limit - Most new vertices found while calculating metrics before SAND cancels the search.
  • metrics_aggregation_limit - Leaf-vertex count above which the aggregation that excludes highly connected vertices is skipped. -1 always runs it, 0 never does.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • InvalidSearchInputError - When start is negative, limit is not positive, or object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.
  • SearchOperationError - When SAND rejects the request.

connect_to_preview​

def connect_to_preview(other: Search | QueryInput,
*,
end_types: str | Sequence[str] | None = None,
end_filters: FilterInput | None = None,
hops: int = 1,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> RequestPreview

Preview the request that connect_to would fire.

Nothing is sent, and start and limit are not range-checked.

Arguments:

  • other - The target scope: another Search or a query input.
  • end_types - Entity types at the far end; defaults to the target's types.
  • end_filters - Filter on the far end; defaults to the target's filter.
  • hops - Most relationships on each path, from 1 (the default) to 4.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.

Returns:

A RequestPreview holding the method, URL, query string, headers, and body.

connect_to​

def connect_to(other: Search | QueryInput,
*,
end_types: str | Sequence[str] | None = None,
end_filters: FilterInput | None = None,
hops: int = 1,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Find related paths between this search scope and another search/query.

Arguments:

  • other - The target scope: another Search or a query input.
  • end_types - Entity types at the far end; defaults to the target's types.
  • end_filters - Filter on the far end; defaults to the target's filter.
  • hops - Most relationships on each path, from 1 (the default) to 4.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

connect_to_async​

async def connect_to_async(other: Search | QueryInput,
*,
end_types: str | Sequence[str] | None = None,
end_filters: FilterInput | None = None,
hops: int = 1,
start: int = 0,
limit: int = 20,
edge_expansion_limit: int = 10000,
expansion_limit: int = 2000) -> PathResults

Async sibling of connect_to.

Arguments:

  • other - The target scope: another Search or a query input.
  • end_types - Entity types at the far end; defaults to the target's types.
  • end_filters - Filter on the far end; defaults to the target's filter.
  • hops - Most relationships on each path, from 1 (the default) to 4.
  • start - Zero-based offset of the first path in the page.
  • limit - Maximum number of paths to return for this page.
  • edge_expansion_limit - Most new vertices found while traversing edges before SAND cancels the search.
  • expansion_limit - Most new vertices found while searching vertices before SAND cancels the search.

Returns:

One page of PathResults that can fetch the pages after it.

Raises:

  • InvalidSearchInputError - When start is negative or limit is not positive.
  • SearchOperationError - When SAND rejects the request.

explain_match_preview​

def explain_match_preview(
object_ref: ObjectIdentifier | tuple[str, str] | Any,
*,
query: QueryInput | None = None,
include_field_highlighting: bool | None = None,
default_child_entity_limit: int | None = None,
child_entity_highlighting_parameters: Any | None = None
) -> RequestPreview

Preview the request that explain_match would fire.

Nothing is sent.

Arguments:

  • object_ref - The object to explain, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • query - Query to highlight against, in place of the search's own query. None uses the search's query.
  • include_field_highlighting - Whether SAND returns highlighting snippets for the object's top-level fields. None leaves the field out of the request and takes the server default.
  • default_child_entity_limit - Most child objects highlighted per child entity when child_entity_highlighting_parameters sets no limit for it. 0 leaves child highlighting out. None takes the server default of 10.
  • child_entity_highlighting_parameters - Paging per child entity, keyed by child entity name, each with start and limit. A generated model or a raw mapping; sent as given.

Returns:

A RequestPreview holding the method, URL, query string, headers, and body.

Raises:

  • InvalidSearchInputError - When object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.

explain_match​

def explain_match(
object_ref: ObjectIdentifier | tuple[str, str] | Any,
*,
query: QueryInput | None = None,
include_field_highlighting: bool | None = None,
default_child_entity_limit: int | None = None,
child_entity_highlighting_parameters: Any | None = None
) -> HighlightingResult

Explain why one object matches a query by requesting highlighting.

Arguments:

  • object_ref - The object to explain, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • query - Query to highlight against, in place of the search's own query. None uses the search's query.
  • include_field_highlighting - Whether SAND returns highlighting snippets for the object's top-level fields. None leaves the field out of the request and takes the server default.
  • default_child_entity_limit - Most child objects highlighted per child entity when child_entity_highlighting_parameters sets no limit for it. 0 leaves child highlighting out. None takes the server default of 10.
  • child_entity_highlighting_parameters - Paging per child entity, keyed by child entity name, each with start and limit. A generated model or a raw mapping; sent as given.

Returns:

The highlighting snippets for the object's fields and child objects.

Raises:

  • InvalidSearchInputError - When object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.
  • SearchOperationError - When SAND rejects the request.

explain_match_async​

async def explain_match_async(
object_ref: ObjectIdentifier | tuple[str, str] | Any,
*,
query: QueryInput | None = None,
include_field_highlighting: bool | None = None,
default_child_entity_limit: int | None = None,
child_entity_highlighting_parameters: Any | None = None
) -> HighlightingResult

Async sibling of explain_match.

Arguments:

  • object_ref - The object to explain, as an ObjectIdentifier, a (type, id) tuple, or an object exposing type/id.
  • query - Query to highlight against, in place of the search's own query. None uses the search's query.
  • include_field_highlighting - Whether SAND returns highlighting snippets for the object's top-level fields. None leaves the field out of the request and takes the server default.
  • default_child_entity_limit - Most child objects highlighted per child entity when child_entity_highlighting_parameters sets no limit for it. 0 leaves child highlighting out. None takes the server default of 10.
  • child_entity_highlighting_parameters - Paging per child entity, keyed by child entity name, each with start and limit. A generated model or a raw mapping; sent as given.

Returns:

The highlighting snippets for the object's fields and child objects.

Raises:

  • InvalidSearchInputError - When object_ref is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.
  • SearchOperationError - When SAND rejects the request.

preview​

def preview(
*visualizations: SearchVisualization | Mapping[str, Any] | Any
) -> RequestPreview

Preview the request that execute would fire.

Returns a RequestPreview capturing method, URL, query string, headers, and body. Call .to_curl() to render a copy-paste curl command, or read .body_model for the typed SearchRequest.

When no visualizations are supplied, this previews the request summary would send at its default start and limit, so callers can preview a search without constructing a visualization by hand. A bare execute has no such default and refuses to send; pass the same visualizations to both to preview an execute.

Arguments:

  • *visualizations - SearchVisualization helpers, generated visualization models, or raw payload mappings. None previews the summary request.

Returns:

A RequestPreview holding the method, URL, query string, headers, and body.

Selection input: which objects a graph operation includes or deselects.

Owns SelectionSpec and the coercion of every accepted selection input into the SAND selection payload.

SelectionSpec Objects​

@dataclass(frozen=True)
class SelectionSpec()

Immutable builder for SAND selection include / deselect rules.

All composition methods are additive:

  • filter AND-combines new filter clauses with the existing one.
  • include and deselect append ids and compound values, and AND-combine query clauses across repeated calls.

Note: SAND's wire payload still has an exclude field. The SDK surface uses deselect so the verb doesn't collide with Search.exclude (which negates a filter). The on-wire shape is unchanged.

filter_​

include_query​

include_ids​

include_compound_values​

deselect_query​

deselect_ids​

deselect_compound_values​

filter​

def filter(
filter_: FilterExpr | GeneratedFilterModel | Mapping[str, Any]
) -> SelectionSpec

AND-combine the supplied filter with the existing selection filter.

Arguments:

  • filter_ - Filter to add, as an F.* expression, a generated filter model, or a raw mapping. A mapping or model is copied, so later edits to it do not reach the spec.

Returns:

A new spec with the combined filter; this one is unchanged.

include​

def include(*,
query: QueryExpr | GeneratedQueryModel | Mapping[str, Any]
| None = None,
ids: Sequence[ObjectIdentifier | tuple[str, str] | Any]
| None = None,
compound_values: Sequence[str] | None = None) -> SelectionSpec

Append include clauses to the selection.

Repeated calls accumulate. Query clauses AND-combine across calls; ids and compound values append in order.

Arguments:

  • query - Query whose matches are included, as a Q.* expression, a generated query model, or a raw mapping.
  • ids - Objects to include, as ObjectIdentifier values, (type, id) tuples, or objects exposing a type and id.
  • compound_values - Compound values to include.

Returns:

A new spec with the clauses added; this one is unchanged.

Raises:

  • InvalidSearchInputError - When an entry in ids is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.

deselect​

def deselect(*,
query: QueryExpr | GeneratedQueryModel | Mapping[str, Any]
| None = None,
ids: Sequence[ObjectIdentifier | tuple[str, str] | Any]
| None = None,
compound_values: Sequence[str] | None = None) -> SelectionSpec

Append deselect clauses to the selection.

Same additive semantics as include: query AND-combines, ids and compound values append. Compiles to SAND's on-wire exclude field. The SDK renames the verb to keep it distinct from Search.exclude (which negates a filter).

Arguments:

  • query - Query whose matches are deselected, as a Q.* expression, a generated query model, or a raw mapping.
  • ids - Objects to deselect, as ObjectIdentifier values, (type, id) tuples, or objects exposing a type and id.
  • compound_values - Compound values to deselect.

Returns:

A new spec with the clauses added; this one is unchanged.

Raises:

  • InvalidSearchInputError - When an entry in ids is not an ObjectIdentifier, a (type, id) tuple, or an object exposing a type and id.

to_payload​

def to_payload() -> JsonObject

Return the selection as a plain payload dictionary.

to_dict​

def to_dict() -> JsonObject

Return a constructor-shaped snapshot of the selection spec.

raw_dict​

def raw_dict() -> JsonObject

Return the SAND selection payload.

SelectionInput​

The SAND wire vocabulary every search module shares.

Owns the unions of generated query and filter models, the type discriminators SAND needs on each of them, the public Literal aliases for the values SAND accepts, and the rules that make a caller's payload safe to keep and send: copy it so later edits cannot reach a frozen builder, tag the discriminators the generated to_dict leaves out, and turn an object reference into an ObjectIdentifier. Nothing here builds a request or talks to a client.

GeneratedQueryModel​

GeneratedFilterModel​

QueryModel​

FilterModel​

Language​

SearchMode​

DateAccuracy​

GeoRelation​

FacetMode​

OrderDirection​

SearchView​

QUERY_TYPES​

FILTER_TYPES​

QUERY_DISCRIMINATORS​

FILTER_DISCRIMINATORS​

Result wrappers for sasvi.search terminals.

This module owns the public result-shape vocabulary: SearchHit, SearchResults, SearchResultRef, PathEndpoint, PathResult, PathResults. Each collection supports len(), iteration and indexing where those make sense, SearchHit supports Mapping[str, Any] access, and the results collections paginate from both sync and async callers.

SearchQueryModel​

SearchResultRef Objects​

@dataclass(repr=False, eq=False, frozen=True)
class SearchResultRef()

Lightweight, persistable reference to a search hit.

Holds just enough to round-trip back through a search service: entity_type_name + document_id (plus an optional label). Call hydrate to fetch the full bound Document or Alert.

A reference is immutable, because its hash is keyed on entity_type_name and document_id. That makes it safe as a dict key or a set member, which is how the search-hydration recipe uses it.

entity_type_name​

document_id​

label​

hydrate​

def hydrate() -> Document | Alert | None

Resolve the reference to a bound document or alert.

Returns:

The resolved Document (or Alert when the reference targets the alerts type), or None when the object no longer exists.

Raises:

  • SearchOperationError - If the reference was deserialized without a bound search service and therefore cannot be hydrated.

hydrate_async​

async def hydrate_async() -> Document | Alert | None

Asynchronously resolve the reference to a bound document or alert.

Returns:

The resolved Document (or Alert when the reference targets the alerts type), or None when the object no longer exists.

Raises:

  • SearchOperationError - If the reference was deserialized without a bound search service and therefore cannot be hydrated.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the search result reference.

SearchHit Objects​

class SearchHit(Mapping[str, Any])

Normalized search hit with Mapping access over its field values.

A SearchHit behaves like a read-only dict[str, Any] over the hit's field values. hit["status"], "status" in hit, iter(hit) (field names) and len(hit) (field count) all work. The canonical identifiers live on the named attributes:

  • entity_type_name: the SAND entity-type the hit belongs to
  • document_id: the document/alert id within that type
  • label: human-readable label, when SAND surfaced one
  • fields: the raw underlying field dict (kept for advanced use)
  • raw: the raw SAND hit payload

Hits are equal when their (entity_type_name, document_id) pair matches, regardless of which fields each carries. That pair is read-only; label, fields and raw are not.

entity_type_name​

@property
def entity_type_name() -> str

The SAND entity type this hit belongs to.

Read-only, because the hash is keyed on it.

document_id​

@property
def document_id() -> str

The document or alert id within this hit's entity type.

Read-only, because the hash is keyed on it.

hydrate​

def hydrate() -> Document | Alert | None

Resolve this hit to a bound document or alert.

Returns:

The resolved Document (or Alert when the hit targets the alerts type), or None when the object no longer exists.

hydrate_async​

async def hydrate_async() -> Document | Alert | None

Asynchronously resolve this hit to a bound document or alert.

Returns:

The resolved Document (or Alert when the hit targets the alerts type), or None when the object no longer exists.

to_ref​

def to_ref() -> SearchResultRef

Convert the hit into a lightweight reference object.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the normalized search hit.

raw_dict​

def raw_dict() -> JsonObject

Return the original search-hit payload as plain Python data.

SearchResults Objects​

class SearchResults()

One page of normalized search hits with pagination helpers.

The wrapper carries enough state to fetch the next page via next_page (or next_page_async for async callers), and exposes iter_all / iter_all_async for callers who want to walk the full result set without hand-rolling the loop.

Attributes:

  • items - The hits in this page (length is at most the requested limit).
  • total - Server-estimated total hits across all pages. Falls back to len(items) when the server omitted a hit count.
  • server_total - The server-reported hit count (hitCount), or None when the response omitted it. When present, pagination is exhaustive. When None, has_next falls back to a page-size heuristic that stops at the first short page.
  • offset - Zero-based offset of this page within the full result set.
  • limit - Page size used for this request.
  • view - Which visualization produced the page, "summary" or "table".
  • raw - The underlying SearchResponse for advanced inspection.

to_refs​

def to_refs() -> list[SearchResultRef]

Return lightweight references for every hit.

hydrate_all​

def hydrate_all() -> list[Document | Alert | None]

Resolve every hit to its bound document or alert wrapper.

Reads one hit at a time, in hit order, and stops at the first read that fails; the hits before it are discarded with the error. The async twin hydrate_all_async settles every read first.

Returns:

One resolved Document or Alert per hit, with None in place of any hit whose object no longer exists.

Raises:

  • DocumentOperationError - When a document read fails.
  • AlertOperationError - When an alert read fails.

hydrate_all_async​

async def hydrate_all_async() -> list[Document | Alert | None]

Asynchronously resolve every hit to its bound document or alert wrapper.

Reads at most eight hits at once. When a read fails, the rest still finish before the first failure in hit order is raised, so no request is left running behind the caller.

Returns:

One resolved Document or Alert per hit, in hit order, with None in place of any hit whose object no longer exists.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the search results page.

raw_dict​

def raw_dict() -> JsonObject

Return the original SAND response payload as plain Python data.

has_next​

@property
def has_next() -> bool

Whether at least one more page is likely available.

When the server reported a hit count, the answer is exact. In that case a short page does not end iteration early, and a page that lands exactly on the last hit does not trigger an extra request. Without a server hit count, this falls back to the page-size heuristic, where a short page is assumed final.

next_page​

def next_page() -> SearchResults | None

Fetch the next page synchronously, or None when exhausted.

next_page_async​

async def next_page_async() -> SearchResults | None

Fetch the next page asynchronously, or None when exhausted.

iter_all​

def iter_all() -> Iterator[SearchHit]

Yield every hit across all pages starting from this one.

When the server reports a hit count (see server_total), the walk runs to that count and a short page does not end it. Without one, it stops at the first short page. A WARNING is logged when the walk ends before the reported total; a server-side count can include rows the caller may not see, so that alone is not proof of a broken read.

Yields:

Every hit across every page, starting from this one.

Raises:

  • IncompleteListingError - When the server stops advancing, the page cap is reached, or the service refuses a page after the first with a 400 or 422, so the results cannot be read to the end. The offset to resume from is on the error.
  • SearchOperationError - When SAND rejects a page request outright.

iter_all_async​

async def iter_all_async() -> AsyncIterator[SearchHit]

Asynchronously yield every hit across all pages.

Same completeness contract as iter_all.

Yields:

Every hit across every page, starting from this one.

Raises:

  • IncompleteListingError - When the server stops advancing, the page cap is reached, or the service refuses a page after the first with a 400 or 422, so the results cannot be read to the end.
  • SearchOperationError - When SAND rejects a page request outright.

PathEndpoint Objects​

class PathEndpoint(RawBackedHandle)

Normalized vertex/edge endpoint within a returned path.

endpoint_type​

@property
def endpoint_type() -> str | None

Whether this endpoint is a "vertex" or an "edge".

type​

@property
def type() -> str | None

SAND entity-type (for a vertex) or relationship type (for an edge).

id​

@property
def id() -> str | None

The endpoint's object id within its type.

label​

@property
def label() -> str | None

Human-readable label SAND attached to the endpoint, if any.

type_label​

@property
def type_label() -> str | None

Display label for the endpoint's type, if SAND supplied one.

subtype​

@property
def subtype() -> str | None

Relationship subtype for an edge endpoint, if any.

valid_from​

@property
def valid_from() -> datetime | None

Bitemporal validity start of the endpoint, if versioned.

Raises:

  • MalformedResponseError - When SAND sent a value that is not an ISO 8601 timestamp.

valid_to​

@property
def valid_to() -> datetime | None

Bitemporal validity end of the endpoint, if versioned.

Raises:

  • MalformedResponseError - When SAND sent a value that is not an ISO 8601 timestamp.

is_edge​

@property
def is_edge() -> bool

Whether this endpoint is an edge rather than a vertex.

connected_endpoints​

@property
def connected_endpoints() -> list[JsonObject]

For an edge, the raw endpoints it connects; empty for a vertex.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the endpoint wrapper.

PathResult Objects​

class PathResult(RawBackedHandle)

Normalized path wrapper.

The endpoints sequence is ordered as SAND emitted it. Use head for the first vertex (the path's seed) and tail for the last.

vertices​

@property
def vertices() -> list[PathEndpoint]

The vertex endpoints of the path, in traversal order.

edges​

@property
def edges() -> list[PathEndpoint]

The edge endpoints connecting the path's vertices.

@property
def head() -> PathEndpoint | None

First vertex in the path (the seed object SAND started from).

tail​

@property
def tail() -> PathEndpoint | None

Last vertex in the path (where SAND ended the traversal).

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the path wrapper.

PathResults Objects​

class PathResults(RawBackedHandle)

Collection wrapper for normalized path results with pagination.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the path-results wrapper.

has_next​

@property
def has_next() -> bool

Whether at least one more page is available.

next_page​

def next_page() -> PathResults | None

Fetch the next page synchronously, or None when exhausted.

Returns:

The next page, or None when no page follows.

Raises:

  • SearchOperationError - If more pages exist and this result can only be continued asynchronously.

next_page_async​

async def next_page_async() -> PathResults | None

Fetch the next page asynchronously, or None when exhausted.

Returns:

The next page, or None when no page follows.

Raises:

  • SearchOperationError - If more pages exist and this result can only be continued synchronously.

iter_all​

def iter_all() -> Iterator[PathResult]

Yield every path across all pages starting from this one.

Same completeness contract as SearchResults.iter_all, with the server's count in place of its hit count.

Yields:

Every path across every page, starting from this one.

Raises:

  • IncompleteListingError - When the server stops advancing, the page cap is reached, or the service refuses a page after the first with a 400 or 422, so the paths cannot be read to the end. The offset to resume from is on the error.
  • SearchOperationError - When SAND rejects a page request outright.

iter_all_async​

async def iter_all_async() -> AsyncIterator[PathResult]

Asynchronously yield every path across all pages.

Yields:

Every path across every page, starting from this one.

Raises:

  • IncompleteListingError - When the server stops advancing, the page cap is reached, or the service refuses a page after the first with a 400 or 422, so the paths cannot be read to the end.
  • SearchOperationError - When SAND rejects a page request outright.

GraphCounts Objects​

class GraphCounts()

Vertex / edge counts attached to a GraphResult.

raw​

@property
def raw() -> _GeneratedGraphCounts

The underlying generated SAND GraphCounts model.

vertices​

@property
def vertices() -> int | None

Number of vertices in the graph, or None when not reported.

edges​

@property
def edges() -> int | None

Number of edges in the graph, or None when not reported.

to_dict​

def to_dict() -> JsonObject

Return the counts as a plain {"vertices": ..., "edges": ...} dict.

Vertex Objects​

class Vertex()

Normalized graph vertex returned by graph terminals.

Wraps the generated SAND Vertex model with clean X | None field types so IDE autocomplete and repr() stay readable. Drop down to raw for any SAND attribute not exposed as a typed property.

raw​

@property
def raw() -> _GeneratedVertex

The underlying generated SAND Vertex model.

id​

@property
def id() -> str | None

The vertex's object id within its entity type.

type_name​

@property
def type_name() -> str | None

SAND entity-type name (the generated model calls this type_).

type_label​

@property
def type_label() -> str | None

Display label for the vertex's entity type, if supplied.

label​

@property
def label() -> str | None

Human-readable label for the vertex, if SAND supplied one.

compound_values​

@property
def compound_values() -> list[str]

The vertex's compound (multi-part identity) values, if any.

attachments_count​

@property
def attachments_count() -> int | None

Number of attachments on the underlying object, if reported.

adjacent​

@property
def adjacent() -> int | None

Count of adjacent vertices reachable in one hop, if reported.

degree​

@property
def degree() -> int | None

Total number of edges incident to the vertex, if reported.

adjacent_by_type​

@property
def adjacent_by_type() -> VertexAdjacentByType | None

Breakdown of adjacent-vertex counts keyed by entity type.

degree_by_type​

@property
def degree_by_type() -> VertexDegreeByType | None

Breakdown of the vertex's degree keyed by relationship type.

fields​

@property
def fields() -> list[SummaryField]

The summary fields SAND returned for the vertex.

valid_from​

@property
def valid_from() -> datetime | None

Bitemporal validity start of the vertex, if versioned.

valid_to​

@property
def valid_to() -> datetime | None

Bitemporal validity end of the vertex, if versioned.

selected​

@property
def selected() -> bool | None

Whether SAND flagged this vertex as part of the selection.

to_dict​

def to_dict() -> JsonObject

Return the vertex as a plain-Python dict of its SAND fields.

Edge Objects​

class Edge()

Normalized graph edge returned by graph terminals.

raw​

@property
def raw() -> _GeneratedEdge

The underlying generated SAND Edge model.

id​

@property
def id() -> str | None

The edge's object id within its relationship type.

type_name​

@property
def type_name() -> str | None

SAND relationship-type name (the generated model calls this type_).

subtype​

@property
def subtype() -> str | None

The edge's relationship subtype, if any.

label​

@property
def label() -> str | None

Human-readable label for the edge, if SAND supplied one.

compound_values​

@property
def compound_values() -> list[str]

The edge's compound (multi-part identity) values, if any.

endpoints​

@property
def endpoints() -> list[_GeneratedEndpoint]

The vertices this edge connects, as generated Endpoint models.

fields​

@property
def fields() -> list[SummaryField]

The summary fields SAND returned for the edge.

valid_from​

@property
def valid_from() -> datetime | None

Bitemporal validity start of the edge, if versioned.

valid_to​

@property
def valid_to() -> datetime | None

Bitemporal validity end of the edge, if versioned.

style​

@property
def style() -> RelationshipStyle | None

Rendering style SAND associated with the relationship, if any.

to_dict​

def to_dict() -> JsonObject

Return the edge as a plain-Python dict of its SAND fields.

CentralityMetrics Objects​

class CentralityMetrics()

Centrality scores of one vertex, returned by Search.centrality.

Wraps the generated SAND CentralityMetrics model. Every metric is float | None; SAND omits a metric it did not compute.

raw​

@property
def raw() -> _GeneratedCentralityMetrics

The underlying generated SAND CentralityMetrics model.

id​

@property
def id() -> str | None

The vertex id the metrics belong to (as given in the edges).

degree​

@property
def degree() -> float | None

Degree centrality: how many edges touch the vertex.

eigen​

@property
def eigen() -> float | None

Eigenvector centrality: influence weighted by neighbours' influence.

close​

@property
def close() -> float | None

Closeness centrality: inverse mean distance to every other vertex.

between​

@property
def between() -> float | None

Betweenness centrality: share of shortest paths through the vertex.

influence1​

@property
def influence1() -> float | None

First-order influence centrality.

influence2​

@property
def influence2() -> float | None

Second-order influence centrality.

to_dict​

def to_dict() -> JsonObject

Return the metrics as {"id": ..., "degree": ..., ...}.

GraphResult Objects​

class GraphResult()

Normalized graph result returned by Search.around_graph / expand_graph.

Provides typed access to vertices, edges and counts, with no Unset sentinels in user-facing field types. Drop down to raw for any field not surfaced as a typed property.

raw​

@property
def raw() -> _GeneratedGraph

The underlying generated SAND Graph model.

version​

@property
def version() -> int | None

SAND schema version of the graph payload, if reported.

vertices​

@property
def vertices() -> list[Vertex]

The graph's vertices as typed Vertex wrappers (cached).

edges​

@property
def edges() -> list[Edge]

The graph's edges as typed Edge wrappers (cached).

counts​

@property
def counts() -> GraphCounts | None

Vertex/edge totals for the graph, or None when not reported.

expansion_limit​

@property
def expansion_limit() -> int | None

Per-node expansion cap SAND applied while building the graph.

expansion_limit_exceeded​

@property
def expansion_limit_exceeded() -> list[ObjectIdentifier]

Objects whose expansion was truncated because the limit was hit.

errors​

@property
def errors() -> list[Error2]

Work SAND cancelled while it built the graph; empty when it finished everything.

SAND still returns the vertices and edges when it cancels part of the work. On a large graph it skips the metrics calculation (error code 95232), so each vertex's degree and adjacent counts are missing.

to_dict​

def to_dict() -> JsonObject

Return the whole graph as a plain-Python dict of its SAND fields.

HighlightingResult Objects​

class HighlightingResult()

Normalized highlighting result returned by Search.explain_match.

raw​

@property
def raw() -> _GeneratedHighlighting

The underlying generated SAND Highlighting model.

version​

@property
def version() -> int | None

SAND schema version of the highlighting payload, if reported.

id​

@property
def id() -> str | None

The id of the document the match was explained for.

type_name​

@property
def type_name() -> str | None

SAND entity-type of the explained document (model's type_).

query​

@property
def query() -> SearchQueryModel | None

The query whose match against the document was highlighted.

include_field_highlighting​

@property
def include_field_highlighting() -> bool | None

Whether per-field highlighting fragments were requested.

default_child_entity_limit​

@property
def default_child_entity_limit() -> int | None

Default cap on highlighted child-entity matches, if set.

field_highlighting​

@property
def field_highlighting() -> HighlightingFieldHighlighting | None

Per-field highlighting fragments keyed by field, if present.

child_entity_highlighting​

@property
def child_entity_highlighting() -> HighlightingChildEntityHighlighting | None

Highlighting fragments for matched child entities, if present.

masked_fields​

@property
def masked_fields() -> HighlightingMaskedFields | None

Fields hidden from the highlighting result by access control.

errors​

@property
def errors() -> list[Error2]

Any per-field highlighting errors SAND reported.

to_dict​

def to_dict() -> JsonObject

Return the highlighting result as a plain-Python dict.

SearchResponseSnapshot Objects​

class SearchResponseSnapshot()

Readable wrapper over a raw SAND SearchResponse.

Search.execute(...) is the multi-visualization escape hatch. It accepts any combination of summary / table / count / facets requests and returns SAND's nested response shape. This wrapper trades the raw model's ugly repr (<Unset object at 0x...> + nested additional_properties={...}) for a clean {name: payload} snapshot of the visualizations dict, while keeping the typed model accessible via raw.

raw​

@property
def raw() -> SearchResponse

The underlying generated SAND SearchResponse model.

version​

@property
def version() -> int | None

SAND schema version of the response payload, if reported.

types​

@property
def types() -> list[str]

The entity types the search was scoped to.

query​

@property
def query() -> SearchQueryModel | None

The query SAND echoed back for this response, if present.

visualizations​

@property
def visualizations() -> JsonObject

Visualizations as {name: decoded-payload}.

Each entry is a plain-Python deep-copy of the visualization's to_dict(), safe to json.dumps and printable without Unset noise. The original typed model is on raw.

to_dict​

def to_dict() -> JsonObject

Return the full response as a plain-Python dict of its SAND fields.