pub trait View: Sized + Send + Sync + 'static {
type Collection: Collection;
type Key: for<'k> Key<'k> + PartialEq<Self::Key> + 'static;
type Value: Send + Sync;
// Required method
fn name(&self) -> Name;
// Provided method
fn view_name(&self) -> ViewName { ... }
}
Expand description
An lazy index of mapped and/or reduced data from a Collection
.
A view provides an efficient way to query data within a collection. BonsaiDb
indexes the associated View::Collection
by calling
CollectionMapReduce::map()
/MapReduce::map()
every time a document is
created or updated. The result Mappings
form a sorted index that can be
efficiently queried using the View::Key
type.
A View behaves similarly to the standard library’s BTreeMap with these
types: BTreeMap<View::Key, Vec<(Header, View::Value)>>
This trait only defines the types and functionality required to interact
with the view’s query system. The MapReduce
/CollectionMapReduce
traits define the map/reduce behavior, and the ViewSchema
trait defines
additional metadata such as the ViewUpdatePolicy
and view version.
For a deeper dive on Views, see the section in our user’s guide.
Views allow querying documents contained within Collection
s in
an efficient manner.
The MapReduce::map()
function is responsible for “mapping” data from the
stored document into the Key
type. In the example below, the field rank
is
being used as the View’s Key
type, and the field score
is being
used as the View’s Value
The MapReduce::reduce()
function is responsible for “reducing” a list of
Value
s into a single value. The example below implements
reduce()
to return an average value.
This enables querying the view in many powerful ways:
db.view::<MyView>().query().await
: Return all entries in the view (without the associated documents).db.view::<MyView>().query_with_docs().await
: Return all entries in the view, including the associatedOwnedDocument
s.db.view::<MyView>().query_with_collection_docs().await
: Return all entries in the view, including the associatedCollectionDocument<T>
s.db.view::<MyView>().reduce().await
: Returns the reduced value of the view query. For the example below, the result type of this call isf32
.db.view::<MyView>().reduce_grouped().await
: Returns the reduced value of the view query, grouped by key. For the example below, thevalue
returned will be anf32
that is the averagescore
of all documents with a matchingrank
.
All of the queries above can be filtered and customized by the methods available
on connection::View
.
For a more detailed walkthrough, see our user guide’s section on Views.
Required Associated Types§
type Collection: Collection
type Collection: Collection
The collection this view belongs to