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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#[macro_use]
extern crate serde_derive;
#[cfg(test)]
#[macro_use]
extern crate maplit;
pub const ELASTICLUNR_VERSION: &str = "0.9.5";
pub mod config;
pub mod document_store;
pub mod inverted_index;
pub mod lang;
pub mod pipeline;
use std::collections::BTreeMap;
use document_store::DocumentStore;
use inverted_index::InvertedIndex;
use lang::English;
pub use lang::Language;
pub use pipeline::Pipeline;
type Tokenizer = Option<Box<dyn Fn(&str) -> Vec<String>>>;
pub struct IndexBuilder {
save: bool,
fields: Vec<String>,
field_tokenizers: Vec<Tokenizer>,
ref_field: String,
pipeline: Option<Pipeline>,
language: Box<dyn Language>,
}
impl Default for IndexBuilder {
fn default() -> Self {
IndexBuilder {
save: true,
fields: Vec::new(),
field_tokenizers: Vec::new(),
ref_field: "id".into(),
pipeline: None,
language: Box::new(English::new()),
}
}
}
impl IndexBuilder {
pub fn new() -> Self {
Default::default()
}
pub fn with_language(language: Box<dyn Language>) -> Self {
Self {
language,
..Default::default()
}
}
pub fn save_docs(mut self, save: bool) -> Self {
self.save = save;
self
}
pub fn add_field(mut self, field: &str) -> Self {
let field = field.into();
if self.fields.contains(&field) {
panic!("Duplicate fields in index: {}", field);
}
self.fields.push(field);
self.field_tokenizers.push(None);
self
}
pub fn add_field_with_tokenizer(
mut self,
field: &str,
tokenizer: Box<dyn Fn(&str) -> Vec<String>>,
) -> Self {
let field = field.into();
if self.fields.contains(&field) {
panic!("Duplicate fields in index: {}", field);
}
self.fields.push(field);
self.field_tokenizers.push(Some(tokenizer));
self
}
pub fn add_fields<I>(mut self, fields: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
for field in fields {
self = self.add_field(field.as_ref())
}
self
}
pub fn set_ref(mut self, ref_field: &str) -> Self {
self.ref_field = ref_field.into();
self
}
pub fn build(self) -> Index {
let IndexBuilder {
save,
fields,
field_tokenizers,
ref_field,
pipeline,
language,
} = self;
let index = fields
.iter()
.map(|f| (f.clone(), InvertedIndex::new()))
.collect();
let pipeline = pipeline.unwrap_or_else(|| language.make_pipeline());
Index {
index,
fields,
field_tokenizers,
ref_field,
document_store: DocumentStore::new(save),
pipeline,
version: crate::ELASTICLUNR_VERSION,
lang: language,
}
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Index {
fields: Vec<String>,
#[serde(skip)]
field_tokenizers: Vec<Tokenizer>,
pipeline: Pipeline,
#[serde(rename = "ref")]
ref_field: String,
version: &'static str,
index: BTreeMap<String, InvertedIndex>,
document_store: DocumentStore,
#[serde(with = "ser_lang")]
lang: Box<dyn Language>,
}
mod ser_lang {
use crate::Language;
use serde::de;
use serde::{Deserializer, Serializer};
use std::fmt;
pub fn serialize<S>(lang: &Box<dyn Language>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&lang.name())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Box<dyn Language>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(LanguageVisitor)
}
struct LanguageVisitor;
impl<'de> de::Visitor<'de> for LanguageVisitor {
type Value = Box<dyn Language>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a capitalized language name")
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: de::Error,
{
match crate::lang::from_name(v) {
Some(l) => Ok(l),
None => Err(E::custom(format!("Unknown language name: {}", v))),
}
}
}
}
impl Index {
pub fn new<I>(fields: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
IndexBuilder::new().add_fields(fields).build()
}
pub fn with_language<I>(lang: Box<dyn Language>, fields: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
IndexBuilder::with_language(lang).add_fields(fields).build()
}
pub fn add_doc<I>(&mut self, doc_ref: &str, data: I)
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut doc = BTreeMap::new();
doc.insert(self.ref_field.clone(), doc_ref.into());
let mut token_freq = BTreeMap::new();
for (i, value) in data.into_iter().enumerate() {
let field = &self.fields[i];
let tokenizer = self.field_tokenizers[i].as_ref();
doc.insert(field.clone(), value.as_ref().to_string());
if field == &self.ref_field {
continue;
}
let raw_tokens = if let Some(tokenizer) = tokenizer {
tokenizer(value.as_ref())
} else {
self.lang.tokenize(value.as_ref())
};
let tokens = self.pipeline.run(raw_tokens);
self.document_store
.add_field_length(doc_ref, field, tokens.len());
for token in tokens {
*token_freq.entry(token).or_insert(0u64) += 1;
}
for (token, count) in &token_freq {
let freq = (*count as f64).sqrt();
self.index
.get_mut(field)
.unwrap_or_else(|| panic!("InvertedIndex does not exist for field {}", field))
.add_token(doc_ref, token, freq);
}
}
self.document_store.add_doc(doc_ref, doc);
}
pub fn get_fields(&self) -> &[String] {
&self.fields
}
pub fn to_json_pretty(&self) -> String {
serde_json::to_string_pretty(&self).unwrap()
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_field_to_builder() {
let idx = IndexBuilder::new()
.add_fields(&["foo", "bar", "baz"])
.build();
let idx_fields = idx.get_fields();
for f in &["foo", "bar", "baz"] {
assert_eq!(idx_fields.iter().filter(|x| x == f).count(), 1);
}
}
#[test]
fn adding_document_to_index() {
let mut idx = Index::new(&["body"]);
idx.add_doc("1", &["this is a test"]);
assert_eq!(idx.document_store.len(), 1);
assert_eq!(
idx.document_store.get_doc("1").unwrap(),
btreemap! {
"id".into() => "1".into(),
"body".into() => "this is a test".into(),
}
);
}
#[test]
fn adding_document_with_empty_field() {
let mut idx = Index::new(&["title", "body"]);
idx.add_doc("1", &["", "test"]);
assert_eq!(idx.index["body"].get_doc_frequency("test"), 1);
assert_eq!(idx.index["body"].get_docs("test").unwrap()["1"], 1.);
}
#[test]
#[should_panic]
fn creating_index_with_identical_fields_panics() {
let _idx = Index::new(&["title", "body", "title"]);
}
}