-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
view-example-string.rs
95 lines (83 loc) · 2.49 KB
/
view-example-string.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use bonsaidb::{
core::{
connection::Connection,
document::Document,
schema::{
view::map::ViewMappedValue, Collection, CollectionName, DefaultSerialization,
DefaultViewSerialization, Name, ReduceResult, View, ViewMapResult, ViewSchema,
},
Error,
},
local::{
config::{Builder, StorageConfiguration},
Database,
},
};
use serde::{Deserialize, Serialize};
// ANCHOR: struct
#[derive(Serialize, Deserialize, Debug)]
pub struct BlogPost {
pub title: String,
pub body: String,
pub category: Option<String>,
}
// ANCHOR_END: struct
impl Collection for BlogPost {
fn collection_name() -> CollectionName {
CollectionName::new("view-example", "blog-post")
}
fn define_views(schema: &mut bonsaidb::core::schema::Schematic) -> Result<(), Error> {
schema.define_view(BlogPostsByCategory)
}
}
impl DefaultSerialization for BlogPost {}
#[derive(Debug, Clone)]
pub struct BlogPostsByCategory;
// ANCHOR: view
impl View for BlogPostsByCategory {
type Collection = BlogPost;
type Key = Option<String>;
type Value = u32;
fn name(&self) -> Name {
Name::new("by-category")
}
}
impl ViewSchema for BlogPostsByCategory {
type View = Self;
fn map(&self, document: &Document) -> ViewMapResult<Self::View> {
let post = document.contents::<BlogPost>()?;
Ok(document.emit_key_and_value(post.category, 1))
}
fn reduce(
&self,
mappings: &[ViewMappedValue<Self::View>],
_rereduce: bool,
) -> ReduceResult<Self::View> {
Ok(mappings.iter().map(|mapping| mapping.value).sum())
}
}
// ANCHOR_END: view
impl DefaultViewSerialization for BlogPostsByCategory {}
#[allow(unused_variables)]
#[tokio::test]
async fn example() -> Result<(), Error> {
let db = Database::open::<BlogPost>(StorageConfiguration::new("example.bonsaidb")).await?;
// ANCHOR: query_with_docs
let rust_posts = db
.view::<BlogPostsByCategory>()
.with_key(Some(String::from("Rust")))
.query_with_docs()
.await?;
// ANCHOR_END: query_with_docs
// ANCHOR: reduce_one_key
let rust_post_count = db
.view::<BlogPostsByCategory>()
.with_key(Some(String::from("Rust")))
.reduce()
.await?;
// ANCHOR_END: reduce_one_key
// ANCHOR: reduce_multiple_keys
let total_post_count = db.view::<BlogPostsByCategory>().reduce().await?;
// ANCHOR_END: reduce_multiple_keys
Ok(())
}