Skip to main content

devpage_core/search/
index.rs

1//! The tantivy index: its schema and tokenizers, and turning each page
2//! published into the sections it is searched by.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::path::Path;
6use std::sync::{Mutex, RwLock};
7
8use tantivy::schema::{
9    FAST, Field, IndexRecordOption, STORED, Schema, TextFieldIndexing, TextOptions,
10};
11use tantivy::tokenizer::{LowerCaser, TextAnalyzer, WhitespaceTokenizer};
12use tantivy::{IndexWriter, ReloadPolicy, TantivyDocument};
13
14use crate::index::Index;
15
16use super::*;
17
18/// The tokenizers: the ranked fields' — tantivy's default, lowercased, with
19/// English stemming — their unstemmed twins', for near and prefix matches,
20/// code's, and the whole-title fields', which keep a value as one term.
21pub(super) const STEMMED: &str = "en_stem";
22pub(super) const PLAIN: &str = "default";
23pub(super) const CODE: &str = "code";
24pub(super) const RAW: &str = "raw";
25
26#[derive(Clone, Copy)]
27pub(super) struct Fields {
28    pub(super) page: Field,
29    pub(super) url: Field,
30    pub(super) path: Field,
31    pub(super) title: Field,
32    pub(super) heading: Field,
33    pub(super) prose: Field,
34    pub(super) code: Field,
35    pub(super) code_text: Field,
36    pub(super) notes: Field,
37    pub(super) meta: Field,
38    pub(super) title_words: Field,
39    pub(super) heading_words: Field,
40    pub(super) prose_words: Field,
41    pub(super) title_exact: Field,
42    pub(super) heading_exact: Field,
43}
44
45/// One section, ready to be a tantivy document.
46pub(super) struct Entry<'a> {
47    pub(super) page: &'a Page,
48    pub(super) heading: &'a str,
49    pub(super) url: String,
50    pub(super) path: Vec<String>,
51    pub(super) depth: u8,
52    pub(super) order: usize,
53    pub(super) prose: &'a str,
54    pub(super) code: &'a str,
55    pub(super) notes: &'a str,
56    pub(super) meta: &'a str,
57}
58
59impl Search {
60    /// Indexes what the document `entry` publishes, among those `index` holds.
61    pub fn build(index: &Index, entry: &Path) -> Self {
62        let mut schema = Schema::builder();
63        let text = |tokenizer: &str, record: IndexRecordOption, stored: bool| {
64            let options = TextOptions::default().set_indexing_options(
65                TextFieldIndexing::default()
66                    .set_tokenizer(tokenizer)
67                    .set_index_option(record),
68            );
69            if stored {
70                options.set_stored()
71            } else {
72                options
73            }
74        };
75        let ranked = |stored| text(STEMMED, IndexRecordOption::WithFreqsAndPositions, stored);
76        let plain = text(PLAIN, IndexRecordOption::Basic, false);
77        let raw = text(RAW, IndexRecordOption::Basic, false);
78        let fields = Fields {
79            page: schema.add_text_field("page", STORED),
80            url: schema.add_text_field("url", STORED),
81            path: schema.add_text_field("path", STORED),
82            title: schema.add_text_field("title", ranked(true)),
83            heading: schema.add_text_field("heading", ranked(true)),
84            prose: schema.add_text_field("prose", ranked(true)),
85            code: schema.add_text_field("code", text(CODE, IndexRecordOption::WithFreqs, false)),
86            code_text: schema.add_text_field("code_text", STORED),
87            notes: schema.add_text_field("notes", ranked(true)),
88            meta: schema.add_text_field("meta", ranked(true)),
89            title_words: schema.add_text_field("title_words", plain.clone()),
90            heading_words: schema.add_text_field("heading_words", plain.clone()),
91            prose_words: schema.add_text_field("prose_words", plain),
92            title_exact: schema.add_text_field("title_exact", raw.clone()),
93            heading_exact: schema.add_text_field("heading_exact", raw),
94        };
95        for name in ["depth", "order", "nav"] {
96            schema.add_u64_field(name, FAST);
97        }
98        let tantivy = tantivy::Index::create_in_ram(schema.build());
99        tantivy.tokenizers().register(
100            CODE,
101            TextAnalyzer::builder(WhitespaceTokenizer::default())
102                .filter(LowerCaser)
103                .build(),
104        );
105        let analyzer = |name: &str| {
106            tantivy
107                .tokenizers()
108                .get(name)
109                .expect("tantivy registers its default and en_stem tokenizers")
110        };
111        let (stemmed, plain) = (analyzer(STEMMED), analyzer(PLAIN));
112        // One thread at the smallest budget tantivy allows, 15 MB: a docs
113        // folder is small, and the index lives in memory.
114        let writer = tantivy
115            .writer_with_num_threads(1, 15_000_000)
116            .expect("an index in memory has no lock to contend for");
117        let reader = tantivy
118            .reader_builder()
119            .reload_policy(ReloadPolicy::Manual)
120            .try_into()
121            .expect("an index in memory can always be read");
122        let search = Self {
123            fields,
124            reader,
125            writer: Mutex::new(writer),
126            stemmed,
127            plain,
128            entry: entry.to_path_buf(),
129            pages: RwLock::new(BTreeMap::new()),
130        };
131        search.rebuild(index);
132        search
133    }
134
135    /// Reads everything published again, into a fresh index, in one commit.
136    pub(super) fn rebuild(&self, index: &Index) {
137        let mut writer = lock(&self.writer);
138        let _ = writer.delete_all_documents();
139        let mut pages = BTreeMap::new();
140        for (nav, unit) in scope(index, &self.entry).into_iter().enumerate() {
141            self.add(&writer, &unit, nav as u64, &mut pages);
142        }
143        if writer.commit().is_ok() {
144            let _ = self.reader.reload();
145        }
146        *self.pages.write().unwrap_or_else(|p| p.into_inner()) = pages;
147    }
148
149    /// Adds the sections of one page, and its record.
150    pub(super) fn add(&self, writer: &IndexWriter, unit: &Unit, nav: u64, pages: &mut Pages) {
151        let Ok(source) = std::fs::read_to_string(&unit.file) else {
152            return;
153        };
154        let front = FrontMatter::read(&source);
155        if front.search == Some(false) {
156            return;
157        }
158        let read = read(&source);
159        let title = match unit.kind {
160            PageKind::Slide => slide_title(&source, &read, unit.name.as_deref().unwrap_or("")),
161            _ => crate::markup::title(&source, &unit.file),
162        };
163        let url = match &unit.name {
164            Some(name) => format!("{}#{name}", unit.address),
165            None => unit.address.clone(),
166        };
167        let page = Page {
168            title,
169            url,
170            trail: unit.trail.clone(),
171            document: unit.document.clone(),
172            kind: unit.kind,
173            lede: read.lede.clone(),
174            nav,
175            title_stems: BTreeSet::new(),
176            meta_stems: self.stems(&front.meta),
177        };
178        let page = Page {
179            title_stems: self.stems(&page.title),
180            ..page
181        };
182        let add = |entry: Entry| self.add_entry(writer, entry);
183        match unit.kind {
184            // A slide is one section, at its number: all its text, and its notes.
185            PageKind::Slide => {
186                let prose: Vec<&str> = read
187                    .sections
188                    .iter()
189                    .flat_map(|s| [s.heading.as_str(), s.prose.as_str()])
190                    .collect();
191                let code: Vec<&str> = read.sections.iter().map(|s| s.code.as_str()).collect();
192                let notes: Vec<String> = crate::markup::notes(&source)
193                    .into_iter()
194                    .map(|note| note.text)
195                    .collect();
196                add(Entry {
197                    page: &page,
198                    heading: &page.title,
199                    url: page.url.clone(),
200                    path: vec![page.title.clone()],
201                    depth: 1,
202                    order: 0,
203                    prose: &squeeze(&prose.join(" ")),
204                    code: &squeeze(&code.join(" ")),
205                    notes: &squeeze(&notes.join(" ")),
206                    meta: &front.meta,
207                });
208            }
209            PageKind::Page | PageKind::Chapter => {
210                let mut above: Vec<(u8, String)> = Vec::new();
211                for (order, section) in read.sections.iter().enumerate() {
212                    above.retain(|(level, _)| *level < section.level || section.level == 0);
213                    if section.level > 0 {
214                        above.push((section.level, section.heading.clone()));
215                    }
216                    let mut path: Vec<String> = above.iter().map(|(_, h)| h.clone()).collect();
217                    if path.first() != Some(&page.title) {
218                        path.insert(0, page.title.clone());
219                    }
220                    // As `render::doc` lays them out: with more than one
221                    // chapter, each one's ids carry its name, and the chapter
222                    // is an id itself.
223                    let anchor = match (&section.id, &unit.name) {
224                        (Some(id), Some(name)) => Some(format!("{name}--{id}")),
225                        (Some(id), None) => Some(id.clone()),
226                        (None, Some(name)) => Some(name.clone()),
227                        (None, None) => None,
228                    };
229                    add(Entry {
230                        page: &page,
231                        heading: &section.heading,
232                        url: match anchor {
233                            Some(anchor) => format!("{}#{anchor}", unit.address),
234                            None => unit.address.clone(),
235                        },
236                        path,
237                        depth: section.level,
238                        order,
239                        prose: &section.prose,
240                        code: &section.code,
241                        notes: "",
242                        meta: &front.meta,
243                    });
244                }
245            }
246        }
247        pages.insert(page.url.clone(), page);
248    }
249
250    pub(super) fn add_entry(&self, writer: &IndexWriter, entry: Entry) {
251        let fields = self.fields;
252        let schema = writer.index().schema();
253        let fast = |name: &str| schema.get_field(name).expect("a fast field of the schema");
254        let mut doc = TantivyDocument::default();
255        doc.add_text(fields.page, &entry.page.url);
256        doc.add_text(fields.url, &entry.url);
257        for label in &entry.path {
258            doc.add_text(fields.path, label);
259        }
260        for (ranked, words, text) in [
261            (
262                fields.title,
263                Some(fields.title_words),
264                entry.page.title.as_str(),
265            ),
266            (fields.heading, Some(fields.heading_words), entry.heading),
267            (fields.prose, Some(fields.prose_words), entry.prose),
268            (fields.notes, None, entry.notes),
269            (fields.meta, None, entry.meta),
270        ] {
271            doc.add_text(ranked, text);
272            if let Some(words) = words {
273                doc.add_text(words, text);
274            }
275        }
276        doc.add_text(fields.code, expand_code(entry.code));
277        doc.add_text(fields.code_text, entry.code);
278        for (field, text) in [
279            (fields.title_exact, entry.page.title.as_str()),
280            (fields.heading_exact, entry.heading),
281        ] {
282            let words = self.words(text, false);
283            let kept = kept(&words);
284            doc.add_text(field, joined(&kept, |word| &word.stem));
285            doc.add_text(field, joined(&kept, |word| &word.typed));
286        }
287        doc.add_u64(fast("depth"), u64::from(entry.depth));
288        doc.add_u64(fast("order"), entry.order as u64);
289        doc.add_u64(fast("nav"), entry.page.nav);
290        let _ = writer.add_document(doc);
291    }
292}