Expand description
flusso-query — a typed query client for a flusso-maintained search index.
Targets OpenSearch and Elasticsearch 7.x, which share the _search query DSL
this crate emits; any future backend divergence is handled on the Client,
not by separate crates.
This is the runtime layer described in the
querying guide:
the transport, the field-handle / Query / Search builder, and the
typed SearchResponse. It is generic over the caller’s document type T.
§What this first cut covers
Clienttransport over OpenSearch (connect,basic_auth, search, msearch, get).- Field handles (
Keyword,Text,Bool,Number,Date,Nested,Binary,Json) with operators that build aQuery. Querycomposition (and/or/not) and theSearchbool-clause builder (query/filter/must_not/should, plussort/from/size/raw). ASearchis a plain client-free value — build it anywhere, store and reuse it; aClientappears only at the terminals:Search::send(a typed page),Search::ids(a page of bare document ids,_source: false), orSearch::count(just the number of matches, via_count).- Several searches in one round-trip:
Client::msearch(a tuple of&Search<T>, mixed document types, one typed response per slot) andClient::msearch_all(a slice of one type). - Combined (blended) search:
FlussoMultiDocument— a caller-owned enum with one variant per document type — and itsMultiSearchbuilder. One query across all the union’s indexes, one relevance-ranked result list, each hit decoded into the variant matching its physical_index. - Typed
SearchResponse/Hit.
Also covered: optional filters (Option<Q> is a Query); object/to-one-join
handles (Object); shaping returned nested arrays (Search::filter_nested
with Nested::matching, via inner_hits); and scope-tagged queries —
Query<S> carries the scope S it was built in (Root for the document
root and flattened objects, the element type for a nested array), so a nested
query must be lifted through Nested::any/Nested::all before it can join a
root query; the compiler enforces it.
§Not yet built
- The
#[derive(FlussoDocument)]and#[derive(FlussoMultiDocument)]proc-macros live influsso-query-derive(thederivefeature). Without them, document structs + handles and union impls are written by hand — exactly the calls this crate exposes (see the integration tests). filter_nested’skeep_source()opt-out (it always replaces the array insourcetoday) and a typedhit.nested(handle)accessor.
§Example (hand-written until the derive lands)
use flusso_query::{Client, Keyword, Number, Nested, kind};
#[derive(serde::Deserialize)]
struct User {
email: String,
#[serde(rename = "orderCount")]
order_count: i64,
}
impl User {
fn email() -> Keyword { Keyword::at("email") }
fn order_count() -> Number<kind::Long> { Number::at("orderCount") }
fn query() -> flusso_query::Search<User> {
flusso_query::Search::new("users", "xxxxxx")
}
}
// A query is a plain value — no client involved while building it.
let busy = User::query()
.filter(User::email().eq("ada@example.com"))
.filter(User::order_count().gte(5))
.size(20);
// The client appears once, when it's time to run.
let client = Client::connect("https://localhost:9200")?;
let page = busy.send(&client).await?;
println!("{} matches", page.total);Modules§
- kind
- Field-category markers for
FlussoValue. Zero-size and uninhabited — they exist only as theKtype parameter, so one type can be a valid value for several kinds (e.g.Stringis akind::Keyword,kind::Text, andkind::Datevalue).
Structs§
- Binary
- A
binaryfield — base64-encoded, not searchable. Only existence. - Bool
- A boolean field.
- Boosting
Query - A
boostingclause. - Client
- A connection to an OpenSearch cluster.
- Combined
Fields Query - A
combined_fieldsclause. - Constant
Score Query - A
constant_scoreclause. Set the fixed score viaboost. - Date
- A
date/timestampfield. Bounds are ISO-8601 strings. - DateMap
- A dynamic-key object whose values are dates (
mapwith adate/timestampvalue kind).keyyields aDateleaf for range/exact operators (gte/between/eq/…).sort_keyorders by a key, with.or(..)fallback. - DisMax
Query - A
dis_maxclause. - Distance
- A distance with an explicit unit — e.g.
Distance::km(12.0). Renders to the OpenSearch distance string ("12km"), so a malformed radius ("12 km", a typo’d unit) can’t reach the query. - Distance
Feature Query - A
distance_featureclause. - EqQuery
- An exact-match (
term) clause for a non-string value (number, bool, date), carrying the universalboost/namemodifiers. - Function
Score Query - A
function_scoreclause. Add functions withweight/functionand tune combination withscore_mode/boost_mode/max_boost/min_score. - Fuzzy
Query - A
fuzzyclause, withfuzziness/prefix_length/max_expansions/transpositionsplusboost/name. - Geo
- A
geo_pointfield — thewithinquery family (distance / box / polygon), plus sort-by-distance. - GeoDistance
Query - A
geo_distanceclause: points within a radius of a center, with thedistance_type/validation_methodoptions plusboost/name. - GeoPoint
- A geographic point — latitude/longitude in degrees.
- Highlight
- Match highlighting for a
Search(thehighlightblock). Name the fields to highlight and tune the tags / fragments; pass it toSearch::highlight. - Hit
- One search hit: the typed document plus its envelope metadata.
- IdsQuery
- An
idsclause. - Json
- An untyped
object/jsonfield. The escape hatch: existence, or a raw clause spliced in verbatim. - Keyword
- An exact, aggregatable string field (
keyword,enum,uuid).Subis aWithSubfields/NoSubfieldstype-state marker gating the subfield accessors. - Keyword
Map - A dynamic-key object whose values are exact strings (
mapwith akeyword/enum/uuidvalue kind).keyyields aKeywordleaf for exact match. Nosearch— exact-match maps usekey(..).eq(..)/has_key(..), consistent with the leaf split.sort_keyorders by a key, with.or(..)fallback. - MapKey
Sort - A sort over a dynamic-key
mapfield by an ordered fallback of keys — “sort byit, elseen, …”. Built with*Map::sort_key("it").or("en")and used like any other sortable handle:SortBuilder::by(handle, dir), or.asc()/.desc()for a bareSort. - MapSearch
- A cross-key full-text query over a
TextMap: one analyzedquerymatched against every key, with optional per-key preference. Renders amulti_matchoftype: best_fieldsover the preferred keys (eachfield^weight) plus the wildcardpath.*fallback, so the best-scoring key wins without double-counting.only_preferreddrops the fallback. - Match
Query - A
match-family clause (match,match_phrase,match_phrase_prefix,match_bool_prefix): the analyzedqueryvalue plus whichever options the kind supports, all written under the field as an object. Thekindselects the wrapper and which setters are meaningful; unset options are simply omitted. - Maybe
Order By - The optionality carrier for
SortBuilder::by: an absent order skips the field. A local newtype because coherence forbidsimpl From<…> for Option<_>. - More
Like This Query - A
more_like_thisclause. - Multi
Match Query - A
multi_matchclause: one analyzedqueryover severalfields, with thetype/operator/fuzziness/tie_breaker/minimum_should_matchoptions plusboost/name. - Multi
Search - A typed query across every index of a
FlussoMultiDocumentunion — the blended counterpart ofSearch, with the same clause builder and the same client-free shape. - Nested
- A
nestedarray of objects.Eis the enclosing scope (where queries over this array land —Rootat the top level, the parent element type when deeper);Cis the child scope (the element type). Lifting a child query (Query<C>) throughany/allproduces aQuery<E>. - Nested
Projection - A request to shape one nested array in the results (via
inner_hits). - Nested
Query - A
nestedclause (parents with a matching element), with thescore_mode/ignore_unmappedoptions plusboost/name.Eis the enclosing scope. - Number
- A numeric field.
Kis the numeric kind (kind::Byte…kind::Decimal),Sthe scope. Value operators accept any value of that kind — the matching primitive, a losslessly-widening one (i32on aLong/Double/Decimalfield),rust_decimal::Decimal(decimalfeature, on aDecimalfield), or a#[derive(FlussoValue)]numeric newtype — so a custom money/quantity type queries with no cast. A lossy value is a compile error (a float on an integer field, ani64on aShort). - Number
Map - A dynamic-key object whose values are numbers (
mapwith a numeric value kind —short…double,decimal).keyyields aNumberleaf for range/exact operators (gt/between/eq/…).has_key/existsare presence checks. Nosearch— numbers aren’t full text. - Object
- An
objectsub-document — agroupor a to-one (belongs_to/has_one) join. Objects are flattened, so their sub-fields are queried by their own scope-Sdotted-path handles directly (Account::tier()); this handle is for the object itself.Sis the enclosing scope (Rootat the top level). - OrderBy
- A field sort minus the field — a direction plus the field-sort modifiers,
ready to attach to whatever handle
SortBuilder::byis given. - Prefix
Query - A
prefixclause, withcase_insensitive/rewriteplusboost/name. - Query
- A composable query clause in scope
S. - Query
String Query - A
query_stringclause. - Range
Query - A
rangeclause with bounds plus the universalboost/nameand the range-specificformat/time_zone/relationmodifiers. - Rank
Feature Query - A
rank_featureclause. - Regexp
Query - A
regexpclause, withcase_insensitive/flags/max_determinized_statesplusboost/name. - Root
- The default query scope — the document root. Root fields and flattened object / to-one-join sub-fields share it.
- Script
Query - A
scriptclause. - Script
Score Query - A
script_scoreclause. - Search
- A typed query against one index — a plain, client-free value.
- Search
Response - A page of search results.
- Segment
- One level of a document path — a field name plus how it’s stored.
- Shard
Stats - Per-shard execution tally from a
_search/_countresponse’s_shards. - Simple
Query String Query - A
simple_query_stringclause. - Sort
- A single sort key. Produced by
.asc()/.desc()on a sortable handle, bySort::score/Sort::script, or byGeo::distance_sort; chain the option setters (missing_first,mode,unmapped_type, …) onto it. - Sort
Builder - Builds the
sortarray, one fluent verb per concern — each absorbing its own optionality so a request maps straight through with no per-fieldif let. - Term
Query - An exact-match (
term) clause on a string field, with optionalcase_insensitiveplus the universalboost/name. - Terms
Query - A multi-value (
terms) clause, carryingboost/name. Shared by the keyword and numericany_ofoperators. - Text
- An analyzed full-text field (
text,identifier). No exacteq.Subis aWithSubfields/NoSubfieldstype-state marker gating the subfield accessors (and theany_of/ascsugar built on them). - TextMap
- A dynamic-key object whose values are analyzed full text (
mapwith atext/identifiervalue kind).keyyields aTextleaf;searchruns full text across every key;sort_keyorders by a key, with.or(..)fallback. - Wildcard
Query - A
wildcardclause, withcase_insensitive/rewriteplusboost/name.
Enums§
- Boost
Mode - How a
function_score’s combined function score merges with the query score. - Distance
Type - How
geo_distancecomputes distance (distance_type). - Distance
Unit - A distance unit OpenSearch accepts in a
geo_distancequery or_geo_distancesort. - Error
- Anything that can go wrong building a request, talking to OpenSearch, or decoding a response.
- Fuzziness
- Allowed edit distance for fuzzy matching (
fuzziness). - MapKey
- Type-state marker: this leaf is one key of a dynamic-key
map(fromTextMap::key/KeywordMap::key). The key’s value ops work as usual, but it carries no flusso subfields and is not directlySortable— its real OpenSearch field is created by default dynamic mapping, which has nokeyword_lowercasesubfield, so a plain.asc()would target a path that doesn’t exist and 400 at query time. Sort a map by key throughTextMap::sort_key(thenSortBuilder::by) instead, which emits a correct (fallback-capable) sort. - Minimum
Should Match - How many clauses/terms must match (
minimum_should_match). Types the common cases — an absolute count and a percentage — whilerawkeeps the full mini-language ("3<90%","2<-25% 9<-3") reachable. - Missing
- Where to place documents missing the sorted field (a field-sort
missing). - Multi
Match Type - The scoring
typeof amulti_match. - Nested
Score Mode - How a
nestedquery’s matching-element scores combine into the parent score. Distinct fromScoreMode: nomultiply/first, plusNone(the nested clause acts as a pure filter, contributing no score). - NoSubfields
- Type-state marker: this handle’s field has no auto subfields, so the
subfield accessors don’t exist — calling one is a compile error, not a 400.
The derive stamps it when subfields aren’t provisioned; subfield leaves
(
.keyword()) also carry it, since a subfield has no further subfields. - Numeric
Type - Numeric type a sort coerces to across indexes (
numeric_type). - Operator
- Boolean combinator for analyzed terms (
operator/default_operator). - Range
Relation - How a
rangerelates to range-typed field values (relation). - Score
Mode - How a
function_score’s functions combine into one score. - Script
Sort Type - The value type a
_scriptsort emits (type). - Segment
Kind - How one path level is stored — the only shapes a level can take.
- Sort
Mode - How a multi-valued field collapses to one sort value.
- Sort
Order - Sort direction.
- Validation
Method - How malformed coordinates are handled (
validation_method). - With
Subfields - Type-state marker: this
text/keywordhandle’s field carries flusso’s auto subfields, so its subfield accessors (.keyword()/.text()/.keyword_lowercase()) — and the sugar built on them (Text::any_of,Text::asc) — are in scope. The default for a hand-written handle; the derive stamps it on a field only when every OpenSearch sink hasauto_subfieldson and the field declares no customfields. - Zero
Terms Query - What a
matchdoes when analysis yields no terms (zero_terms_query).
Traits§
- AsQuery
- Anything that can become a query clause in scope
S. A clause may be absent (into_queryreturnsNone) — that’s what makes anOption<Query<S>>a first-class optional filter. - Flusso
Document - A view onto a flusso-maintained index — the root document or any of its
nestedelement projections. Every struct#[derive(FlussoDocument)]generates carries aPATH: the chain of container levels from the index root down to this view, which a nesting-aware sort reads to render the rightnestedclause. The root’sPATHis empty. - Flusso
Index - The root document bound to a flusso-maintained index — the entry point for
queries.
#[derive(FlussoDocument)]implements this only for the struct with nopath(the index root). - Flusso
Map - A Rust type usable as the document type of a
mapfield of value kindK: a dynamic-key object whose values are all of kindK. - Flusso
Multi Document - A union of
FlussoDocumenttypes searched together — one query, one blended result list, each hit decoded into the variant matching its index. - Flusso
Value - A Rust type usable where a field of kind
Kis expected: as the field type in a#[derive(FlussoDocument)]struct, and as a query value — forkind::KeywordonKeyword::eq/Keyword::any_of, and forkind::DateonDate::eq/Date::gte/… (String/&str, or thechronodate types behind thechronofeature). - Msearch
Bundle - A bundle of searches runnable in one
Client::msearchrequest — implemented for tuples of&Search<T>up to arity 8, each slot with its own document type. You don’t implement this; you pass tuples. - Sortable
- A handle that can produce a
Sort. The compile-time gate forSortBuilder::by/tiebreak: implemented for the orderable leaf handles (Keyword,Text,Number<K>,Date,Bool) and for aMapKeySort(Type::field().sort_key(..)), but not for a bareGeo/Object/ map handle — soby(geo_handle, …)orby(map_handle, …)fails to compile (geo sorts go throughSortBuilder::near/raw; a map sorts via itssort_key).
Functions§
- boosting
- Keep documents matching
positive, but demote (don’t exclude) those that also matchnegativebynegative_boost(0.0–1.0). - combined_
fields - Term-centric full-text across several fields, treating them as one combined
field (
combined_fields). - constant_
score - Wrap a
filterso every match scores the same fixedboost(default 1.0). - dis_max
- Score by the single best-matching clause, optionally crediting the others
via
tie_breaker. - distance_
feature - Boost by proximity of a
field(date or geo) toorigin, decaying overpivot(distance_feature). - function_
score - Recompute relevance for
queryvia one or more scoring functions. - ids
- Match documents by a list of
_idvalues — typed get-many-by-id. - more_
like_ this - Find documents similar to
liketext(s) acrossfields(more_like_this). - multi_
match - A cross-field full-text query over several
Textfields in the same scope. Returns aMultiMatchQuerybuilder; weight individual fields withText::boosted. - nested_
boundaries - The
nestedboundaries alongpath: the cumulative dotted path of eachNestedlevel, outermost first. - query_
string - Full Lucene query-string syntax (power users; can error on malformed input).
Target fields with
default_fieldorfields. - rank_
feature - Boost by a
rank_feature/rank_featuresfield’s stored value. The default saturation function applies unless one is chosen. - script
- Keep documents for which a painless
sourcereturns true (a non-scoring filter). - script_
score - Recompute
query’s score with a painlesssource(script_score). - simple_
query_ string - Lenient search-bar syntax over chosen fields — never errors on bad input.