1
use bonsaidb::core::connection::Connection;
2
use bonsaidb::core::document::{BorrowedDocument, Emit};
3
use bonsaidb::core::key::Key;
4
use bonsaidb::core::schema::view::map::ViewMappedValue;
5
use bonsaidb::core::schema::{
6
    Collection, MapReduce, ReduceResult, SerializedCollection, View, ViewMapResult, ViewSchema,
7
};
8
use bonsaidb::core::Error;
9
use bonsaidb::local::config::{Builder, StorageConfiguration};
10
use bonsaidb::local::Database;
11
use serde::{Deserialize, Serialize};
12

            
13
// ANCHOR: enum
14
2
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Key, Clone)]
15
pub enum Category {
16
    Rust,
17
    Cooking,
18
}
19
// ANCHOR_END: enum
20

            
21
// ANCHOR: struct
22
2
#[derive(Serialize, Deserialize, Debug, Collection)]
23
#[collection(name = "blog-post", views = [BlogPostsByCategory])]
24
pub struct BlogPost {
25
    pub title: String,
26
    pub body: String,
27
    pub category: Option<Category>,
28
}
29
// ANCHOR_END: struct
30

            
31
// ANCHOR: view
32

            
33
20
#[derive(Debug, Clone, View, ViewSchema)]
34
#[view(collection = BlogPost, key = Option<Category>, value = u32, name = "by-category")]
35
pub struct BlogPostsByCategory;
36

            
37
impl MapReduce for BlogPostsByCategory {
38
    fn map<'doc>(&self, document: &'doc BorrowedDocument<'_>) -> ViewMapResult<'doc, Self> {
39
        let post = BlogPost::document_contents(document)?;
40
        document.header.emit_key_and_value(post.category, 1)
41
    }
42

            
43
2
    fn reduce(
44
2
        &self,
45
2
        mappings: &[ViewMappedValue<Self::View>],
46
2
        _rereduce: bool,
47
2
    ) -> ReduceResult<Self::View> {
48
2
        Ok(mappings.iter().map(|mapping| mapping.value).sum())
49
2
    }
50
}
51
// ANCHOR_END: view
52

            
53
#[allow(unused_variables)]
54
1
#[test]
55
1
fn example() -> Result<(), Error> {
56
1
    drop(std::fs::remove_dir_all("example.bonsaidb"));
57
1
    let db = Database::open::<BlogPost>(StorageConfiguration::new("example.bonsaidb"))?;
58
    // ANCHOR: query_with_docs
59
1
    let rust_posts = db
60
1
        .view::<BlogPostsByCategory>()
61
1
        .with_key(&Some(Category::Rust))
62
1
        .query_with_docs()?;
63
    // ANCHOR_END: query_with_docs
64
    // ANCHOR: reduce_one_key
65
1
    let rust_post_count = db
66
1
        .view::<BlogPostsByCategory>()
67
1
        .with_key(&Some(Category::Rust))
68
1
        .reduce()?;
69
    // ANCHOR_END: reduce_one_key
70
    // ANCHOR: reduce_multiple_keys
71
1
    let total_post_count = db.view::<BlogPostsByCategory>().reduce()?;
72
    // ANCHOR_END: reduce_multiple_keys
73
1
    Ok(())
74
1
}