caio.co/de/cantine


Move business logic out of cantine by Caio 5 years ago (log)

Blob crates/cantine/src/index.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::{cmp::Ordering, convert::TryFrom, path::Path};

use bincode;
use tantivy::{
    self,
    query::{AllQuery, BooleanQuery, Occur, Query},
    schema::{Field, Schema, SchemaBuilder, Value, FAST, STORED, TEXT},
    DocId, Document, Index, Result, Searcher, SegmentReader, TantivyError,
};

use crate::model::{
    FeaturesAggregationQuery, FeaturesAggregationResult, FeaturesCollector, FeaturesFilterFields,
    Recipe, RecipeId, SearchCursor, SearchQuery, Sort,
};

use tique::{
    queryparser::QueryParser,
    top_collector::{ordered_by_u64_fast_field, ConditionalTopCollector, SearchMarker},
};

#[derive(Clone)]
pub struct IndexFields {
    pub id: Field,
    pub fulltext: Field,
    pub features_bincode: Field,
    pub features: FeaturesFilterFields,
}

const FIELD_ID: &str = "id";
const FIELD_FULLTEXT: &str = "fulltext";
const FIELD_FEATURES_BINCODE: &str = "features_bincode";

impl IndexFields {
    pub fn make_document(&self, recipe: &Recipe) -> Document {
        let mut doc = Document::new();
        doc.add_u64(self.id, recipe.recipe_id);

        let mut fulltext = Vec::new();

        fulltext.push(recipe.name.as_str());
        for ingredient in &recipe.ingredients {
            fulltext.push(ingredient.as_str());
        }
        for instruction in &recipe.instructions {
            fulltext.push(instruction.as_str());
        }
        doc.add_text(self.fulltext, fulltext.join("\n").as_str());

        doc.add_bytes(
            self.features_bincode,
            bincode::serialize(&recipe.features).unwrap(),
        );

        self.features.add_to_doc(&mut doc, &recipe.features);
        doc
    }
}

impl From<&mut SchemaBuilder> for IndexFields {
    fn from(builder: &mut SchemaBuilder) -> Self {
        IndexFields {
            id: builder.add_u64_field(FIELD_ID, STORED | FAST),
            fulltext: builder.add_text_field(FIELD_FULLTEXT, TEXT),
            features_bincode: builder.add_bytes_field(FIELD_FEATURES_BINCODE),
            features: FeaturesFilterFields::from(builder),
        }
    }
}

impl TryFrom<&Schema> for IndexFields {
    type Error = TantivyError;

    fn try_from(schema: &Schema) -> Result<Self> {
        let id = schema
            .get_field(FIELD_ID)
            .ok_or_else(|| TantivyError::SchemaError(format!("Missing field {}", FIELD_ID)))?;

        let fulltext = schema.get_field(FIELD_FULLTEXT).ok_or_else(|| {
            TantivyError::SchemaError(format!("Missing field {}", FIELD_FULLTEXT))
        })?;

        let features_bincode = schema.get_field(FIELD_FEATURES_BINCODE).ok_or_else(|| {
            TantivyError::SchemaError(format!("Missing field {}", FIELD_FEATURES_BINCODE))
        })?;

        Ok(IndexFields {
            id,
            fulltext,
            features_bincode,
            features: FeaturesFilterFields::try_from(schema)?,
        })
    }
}

pub struct Cantine {
    fields: IndexFields,
    query_parser: QueryParser,
}

pub type CantineSearchResult = (
    usize,
    Vec<RecipeId>,
    Option<SearchCursor>,
    Option<FeaturesAggregationResult>,
);

impl Cantine {
    pub fn open<P: AsRef<Path>>(base_path: P) -> Result<(Index, Self)> {
        let index = Index::open_in_dir(base_path.as_ref())?;
        let cantine = Self::try_from(&index)?;

        Ok((index, cantine))
    }

    pub fn interpret_query(&self, query: &SearchQuery) -> Result<Box<dyn Query>> {
        let mut subqueries: Vec<(Occur, Box<dyn Query>)> = Vec::new();

        if let Some(fulltext) = &query.fulltext {
            if let Some(parsed) = self.query_parser.parse(fulltext.as_str())? {
                subqueries.push((Occur::Must, parsed));
            }
        }

        if let Some(filter) = &query.filter {
            for query in self.fields.features.interpret(filter).into_iter() {
                subqueries.push((Occur::Must, query));
            }
        }

        match subqueries.len() {
            0 => Ok(Box::new(AllQuery)),
            1 => Ok(subqueries.pop().expect("length has been checked").1),
            _ => Ok(Box::new(BooleanQuery::from(subqueries))),
        }
    }

    fn addresses_to_ids<T>(
        &self,
        searcher: &Searcher,
        addresses: &[SearchMarker<T>],
    ) -> Result<Vec<RecipeId>> {
        let mut items = Vec::with_capacity(addresses.len());

        for addr in addresses.iter() {
            let doc = searcher.doc(addr.doc)?;
            if let Some(&Value::U64(id)) = doc.get_first(self.fields.id) {
                items.push(id);
            } else {
                panic!("Found document without a stored id");
            }
        }

        Ok(items)
    }

    pub fn search(
        &self,
        searcher: &Searcher,
        interpreted_query: &dyn Query,
        limit: usize,
        sort: Sort,
        after: SearchCursor,
    ) -> Result<(usize, Vec<RecipeId>, Option<SearchCursor>)> {
        macro_rules! condition_from_score {
            ($score:expr) => {{
                let after_score = $score;
                let after_id = after.recipe_id();
                let is_start = after.is_start();

                let id_field = self.fields.id;
                move |reader: &SegmentReader| {
                    let id_reader = reader
                        .fast_fields()
                        .u64(id_field)
                        .expect("id field is indexed with the FAST flag");

                    move |_segment_id, doc_id, score| {
                        if is_start {
                            return true;
                        }

                        let recipe_id = id_reader.get(doc_id);
                        match after_score.partial_cmp(&score) {
                            Some(Ordering::Greater) => true,
                            Some(Ordering::Equal) => after_id < recipe_id,
                            _ => false,
                        }
                    }
                }
            }};
        }

        macro_rules! collect_unsigned {
            ($field:ident) => {{
                let condition = condition_from_score!(after.score());
                let top_collector =
                    ordered_by_u64_fast_field(self.fields.features.$field, limit, condition);

                let result = searcher.search(interpreted_query, &top_collector)?;
                let items = self.addresses_to_ids(&searcher, &result.items)?;

                let num_items = items.len();
                let cursor = if result.visited.saturating_sub(num_items) > 0 {
                    let last_score = result.items[num_items - 1].score;
                    let last_id = items[num_items - 1];
                    Some(SearchCursor::new(last_score, last_id))
                } else {
                    None
                };

                Ok((result.total, items, cursor))
            }};
        }

        match sort {
            Sort::Relevance => {
                let condition = condition_from_score!(after.score_f32());
                let top_collector = ConditionalTopCollector::with_limit(limit, condition);

                let result = searcher.search(interpreted_query, &top_collector)?;
                let items = self.addresses_to_ids(&searcher, &result.items)?;

                let num_items = items.len();
                let cursor = if result.visited.saturating_sub(num_items) > 0 {
                    let last_score = result.items[num_items - 1].score;
                    let last_id = items[num_items - 1];
                    Some(SearchCursor::from_f32(last_score, last_id))
                } else {
                    None
                };

                Ok((result.total, items, cursor))
            }
            Sort::Calories => collect_unsigned!(calories),
            Sort::NumIngredients => collect_unsigned!(num_ingredients),
            Sort::InstructionsLength => collect_unsigned!(instructions_length),
            Sort::TotalTime => collect_unsigned!(total_time),
            Sort::CookTime => collect_unsigned!(cook_time),
            Sort::PrepTime => collect_unsigned!(prep_time),
            _ => unimplemented!(),
        }
    }

    pub fn aggregate_features(
        &self,
        searcher: &Searcher,
        interpreted_query: &dyn Query,
        agg_query: FeaturesAggregationQuery,
    ) -> Result<FeaturesAggregationResult> {
        let features_field = self.fields.features_bincode;
        let collector = FeaturesCollector::new(agg_query, move |reader: &SegmentReader| {
            let features_reader = reader
                .fast_fields()
                .bytes(features_field)
                .expect("bytes field is indexed");

            move |doc: DocId| {
                let buf = features_reader.get_bytes(doc);
                bincode::deserialize(buf).unwrap()
            }
        });

        Ok(searcher.search(interpreted_query, &collector)?)
    }
}

impl TryFrom<&Index> for Cantine {
    type Error = TantivyError;
    fn try_from(index: &Index) -> Result<Self> {
        let fields = IndexFields::try_from(&index.schema())?;

        let query_parser = QueryParser::new(
            fields.fulltext,
            index.tokenizer_for_field(fields.fulltext)?,
            true,
        );

        Ok(Self {
            fields,
            query_parser,
        })
    }
}