Skip to main content

Crate flusso_query

Crate flusso_query 

Source
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

  • Client transport over OpenSearch (connect, basic_auth, search, msearch, get).
  • Field handles (Keyword, Text, Bool, Number, Date, Nested, Binary, Json) with operators that build a Query.
  • Query composition (and / or / not) and the Search bool-clause builder (query / filter / must_not / should, plus sort / from / size / raw). A Search is a plain client-free value — build it anywhere, store and reuse it; a Client appears only at the terminals: Search::send (a typed page), Search::ids (a page of bare document ids, _source: false), or Search::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) and Client::msearch_all (a slice of one type).
  • Combined (blended) search: FlussoMultiDocument — a caller-owned enum with one variant per document type — and its MultiSearch builder. 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 in flusso-query-derive (the derive feature). Without them, document structs + handles and union impls are written by hand — exactly the calls this crate exposes (see the integration tests).
  • filter_nested’s keep_source() opt-out (it always replaces the array in source today) and a typed hit.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 the K type parameter, so one type can be a valid value for several kinds (e.g. String is a kind::Keyword, kind::Text, and kind::Date value).

Structs§

Binary
A binary field — base64-encoded, not searchable. Only existence.
Bool
A boolean field.
BoostingQuery
A boosting clause.
Client
A connection to an OpenSearch cluster.
CombinedFieldsQuery
A combined_fields clause.
ConstantScoreQuery
A constant_score clause. Set the fixed score via boost.
Date
A date/timestamp field. Bounds are ISO-8601 strings.
DateMap
A dynamic-key object whose values are dates (map with a date/timestamp value kind). key yields a Date leaf for range/exact operators (gte/between/eq/…). sort_key orders by a key, with .or(..) fallback.
DisMaxQuery
A dis_max clause.
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.
DistanceFeatureQuery
A distance_feature clause.
EqQuery
An exact-match (term) clause for a non-string value (number, bool, date), carrying the universal boost / name modifiers.
FunctionScoreQuery
A function_score clause. Add functions with weight / function and tune combination with score_mode / boost_mode / max_boost / min_score.
FuzzyQuery
A fuzzy clause, with fuzziness / prefix_length / max_expansions / transpositions plus boost / name.
Geo
A geo_point field — the within query family (distance / box / polygon), plus sort-by-distance.
GeoDistanceQuery
A geo_distance clause: points within a radius of a center, with the distance_type / validation_method options plus boost / name.
GeoPoint
A geographic point — latitude/longitude in degrees.
Highlight
Match highlighting for a Search (the highlight block). Name the fields to highlight and tune the tags / fragments; pass it to Search::highlight.
Hit
One search hit: the typed document plus its envelope metadata.
IdsQuery
An ids clause.
Json
An untyped object/json field. The escape hatch: existence, or a raw clause spliced in verbatim.
Keyword
An exact, aggregatable string field (keyword, enum, uuid). Sub is a WithSubfields/NoSubfields type-state marker gating the subfield accessors.
KeywordMap
A dynamic-key object whose values are exact strings (map with a keyword/enum/uuid value kind). key yields a Keyword leaf for exact match. No search — exact-match maps use key(..).eq(..) / has_key(..), consistent with the leaf split. sort_key orders by a key, with .or(..) fallback.
MapKeySort
A sort over a dynamic-key map field by an ordered fallback of keys — “sort by it, else en, …”. Built with *Map::sort_key("it").or("en") and used like any other sortable handle: SortBuilder::by(handle, dir), or .asc() / .desc() for a bare Sort.
MapSearch
A cross-key full-text query over a TextMap: one analyzed query matched against every key, with optional per-key preference. Renders a multi_match of type: best_fields over the preferred keys (each field^weight) plus the wildcard path.* fallback, so the best-scoring key wins without double-counting. only_preferred drops the fallback.
MatchQuery
A match-family clause (match, match_phrase, match_phrase_prefix, match_bool_prefix): the analyzed query value plus whichever options the kind supports, all written under the field as an object. The kind selects the wrapper and which setters are meaningful; unset options are simply omitted.
MaybeOrderBy
The optionality carrier for SortBuilder::by: an absent order skips the field. A local newtype because coherence forbids impl From<…> for Option<_>.
MoreLikeThisQuery
A more_like_this clause.
MultiMatchQuery
A multi_match clause: one analyzed query over several fields, with the type / operator / fuzziness / tie_breaker / minimum_should_match options plus boost / name.
MultiSearch
A typed query across every index of a FlussoMultiDocument union — the blended counterpart of Search, with the same clause builder and the same client-free shape.
Nested
A nested array of objects. E is the enclosing scope (where queries over this array land — Root at the top level, the parent element type when deeper); C is the child scope (the element type). Lifting a child query (Query<C>) through any/all produces a Query<E>.
NestedProjection
A request to shape one nested array in the results (via inner_hits).
NestedQuery
A nested clause (parents with a matching element), with the score_mode / ignore_unmapped options plus boost / name. E is the enclosing scope.
Number
A numeric field. K is the numeric kind (kind::Bytekind::Decimal), S the scope. Value operators accept any value of that kind — the matching primitive, a losslessly-widening one (i32 on a Long/Double/Decimal field), rust_decimal::Decimal (decimal feature, on a Decimal field), 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, an i64 on a Short).
NumberMap
A dynamic-key object whose values are numbers (map with a numeric value kind — shortdouble, decimal). key yields a Number leaf for range/exact operators (gt/between/eq/…). has_key/exists are presence checks. No search — numbers aren’t full text.
Object
An object sub-document — a group or a to-one (belongs_to/has_one) join. Objects are flattened, so their sub-fields are queried by their own scope-S dotted-path handles directly (Account::tier()); this handle is for the object itself. S is the enclosing scope (Root at the top level).
OrderBy
A field sort minus the field — a direction plus the field-sort modifiers, ready to attach to whatever handle SortBuilder::by is given.
PrefixQuery
A prefix clause, with case_insensitive / rewrite plus boost / name.
Query
A composable query clause in scope S.
QueryStringQuery
A query_string clause.
RangeQuery
A range clause with bounds plus the universal boost / name and the range-specific format / time_zone / relation modifiers.
RankFeatureQuery
A rank_feature clause.
RegexpQuery
A regexp clause, with case_insensitive / flags / max_determinized_states plus boost / name.
Root
The default query scope — the document root. Root fields and flattened object / to-one-join sub-fields share it.
ScriptQuery
A script clause.
ScriptScoreQuery
A script_score clause.
Search
A typed query against one index — a plain, client-free value.
SearchResponse
A page of search results.
Segment
One level of a document path — a field name plus how it’s stored.
ShardStats
Per-shard execution tally from a _search/_count response’s _shards.
SimpleQueryStringQuery
A simple_query_string clause.
Sort
A single sort key. Produced by .asc() / .desc() on a sortable handle, by Sort::score / Sort::script, or by Geo::distance_sort; chain the option setters (missing_first, mode, unmapped_type, …) onto it.
SortBuilder
Builds the sort array, one fluent verb per concern — each absorbing its own optionality so a request maps straight through with no per-field if let.
TermQuery
An exact-match (term) clause on a string field, with optional case_insensitive plus the universal boost / name.
TermsQuery
A multi-value (terms) clause, carrying boost / name. Shared by the keyword and numeric any_of operators.
Text
An analyzed full-text field (text, identifier). No exact eq. Sub is a WithSubfields/NoSubfields type-state marker gating the subfield accessors (and the any_of / asc sugar built on them).
TextMap
A dynamic-key object whose values are analyzed full text (map with a text/identifier value kind). key yields a Text leaf; search runs full text across every key; sort_key orders by a key, with .or(..) fallback.
WildcardQuery
A wildcard clause, with case_insensitive / rewrite plus boost / name.

Enums§

BoostMode
How a function_score’s combined function score merges with the query score.
DistanceType
How geo_distance computes distance (distance_type).
DistanceUnit
A distance unit OpenSearch accepts in a geo_distance query or _geo_distance sort.
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 (from TextMap::key / KeywordMap::key). The key’s value ops work as usual, but it carries no flusso subfields and is not directly Sortable — its real OpenSearch field is created by default dynamic mapping, which has no keyword_lowercase subfield, so a plain .asc() would target a path that doesn’t exist and 400 at query time. Sort a map by key through TextMap::sort_key (then SortBuilder::by) instead, which emits a correct (fallback-capable) sort.
MinimumShouldMatch
How many clauses/terms must match (minimum_should_match). Types the common cases — an absolute count and a percentage — while raw keeps the full mini-language ("3<90%", "2<-25% 9<-3") reachable.
Missing
Where to place documents missing the sorted field (a field-sort missing).
MultiMatchType
The scoring type of a multi_match.
NestedScoreMode
How a nested query’s matching-element scores combine into the parent score. Distinct from ScoreMode: no multiply/first, plus None (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.
NumericType
Numeric type a sort coerces to across indexes (numeric_type).
Operator
Boolean combinator for analyzed terms (operator / default_operator).
RangeRelation
How a range relates to range-typed field values (relation).
ScoreMode
How a function_score’s functions combine into one score.
ScriptSortType
The value type a _script sort emits (type).
SegmentKind
How one path level is stored — the only shapes a level can take.
SortMode
How a multi-valued field collapses to one sort value.
SortOrder
Sort direction.
ValidationMethod
How malformed coordinates are handled (validation_method).
WithSubfields
Type-state marker: this text/keyword handle’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 has auto_subfields on and the field declares no custom fields.
ZeroTermsQuery
What a match does 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_query returns None) — that’s what makes an Option<Query<S>> a first-class optional filter.
FlussoDocument
A view onto a flusso-maintained index — the root document or any of its nested element projections. Every struct #[derive(FlussoDocument)] generates carries a PATH: the chain of container levels from the index root down to this view, which a nesting-aware sort reads to render the right nested clause. The root’s PATH is empty.
FlussoIndex
The root document bound to a flusso-maintained index — the entry point for queries. #[derive(FlussoDocument)] implements this only for the struct with no path (the index root).
FlussoMap
A Rust type usable as the document type of a map field of value kind K: a dynamic-key object whose values are all of kind K.
FlussoMultiDocument
A union of FlussoDocument types searched together — one query, one blended result list, each hit decoded into the variant matching its index.
FlussoValue
A Rust type usable where a field of kind K is expected: as the field type in a #[derive(FlussoDocument)] struct, and as a query value — for kind::Keyword on Keyword::eq/Keyword::any_of, and for kind::Date on Date::eq/Date::gte/… (String/&str, or the chrono date types behind the chrono feature).
MsearchBundle
A bundle of searches runnable in one Client::msearch request — 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 for SortBuilder::by / tiebreak: implemented for the orderable leaf handles (Keyword, Text, Number<K>, Date, Bool) and for a MapKeySort (Type::field().sort_key(..)), but not for a bare Geo / Object / map handle — so by(geo_handle, …) or by(map_handle, …) fails to compile (geo sorts go through SortBuilder::near / raw; a map sorts via its sort_key).

Functions§

boosting
Keep documents matching positive, but demote (don’t exclude) those that also match negative by negative_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 filter so every match scores the same fixed boost (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) to origin, decaying over pivot (distance_feature).
function_score
Recompute relevance for query via one or more scoring functions.
ids
Match documents by a list of _id values — typed get-many-by-id.
more_like_this
Find documents similar to like text(s) across fields (more_like_this).
multi_match
A cross-field full-text query over several Text fields in the same scope. Returns a MultiMatchQuery builder; weight individual fields with Text::boosted.
nested_boundaries
The nested boundaries along path: the cumulative dotted path of each Nested level, outermost first.
query_string
Full Lucene query-string syntax (power users; can error on malformed input). Target fields with default_field or fields.
rank_feature
Boost by a rank_feature / rank_features field’s stored value. The default saturation function applies unless one is chosen.
script
Keep documents for which a painless source returns true (a non-scoring filter).
script_score
Recompute query’s score with a painless source (script_score).
simple_query_string
Lenient search-bar syntax over chosen fields — never errors on bad input.

Type Aliases§

Result
A Result whose error is this crate’s Error.