-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
index.rs
284 lines (247 loc) · 10.9 KB
/
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
284
use super::*;
use std::collections::HashMap;
use std::fs::read_dir;
use std::iter::Iterator;
use std::path::PathBuf;
use serde_json::Value as JValue;
use tantivy::collector::TopCollector;
use tantivy::query::{AllQuery, QueryParser};
use tantivy::schema::*;
use tantivy::Index;
use handle::IndexHandle;
use query::{summary_schema, AggregateQuery, SumCollector};
use results::*;
use settings::Settings;
#[derive(Deserialize, Debug)]
pub struct Search {
pub query: Queries,
#[serde(default = "Settings::default_result_limit")]
pub limit: usize,
}
impl Search {
pub fn all() -> Self {
Search {
query: Queries::AllDocs,
limit: Settings::default_result_limit(),
}
}
}
#[derive(Deserialize, Clone, PartialEq, Debug)]
#[serde(untagged)]
pub enum Queries {
TermSearch { term: HashMap<String, JValue> },
TermsSearch { terms: HashMap<String, Vec<String>> },
RangeSearch { range: HashMap<String, HashMap<String, i64>> },
RawSearch { raw: String },
SumAgg { field: String },
AllDocs,
}
pub struct IndexCatalog {
pub settings: Settings,
base_path: PathBuf,
collection: HashMap<String, IndexHandle>,
}
impl IndexCatalog {
pub fn with_path(base_path: PathBuf) -> Result<Self> {
IndexCatalog::new(base_path, Settings::default())
}
pub fn new(base_path: PathBuf, settings: Settings) -> Result<Self> {
let mut index_cat = IndexCatalog {
settings,
base_path,
collection: HashMap::new(),
};
index_cat.refresh_catalog()?;
info!("Indexes: {:?}", index_cat.collection.keys());
Ok(index_cat)
}
pub fn base_path(&self) -> &PathBuf {
&self.base_path
}
#[doc(hidden)]
#[allow(dead_code)]
pub fn with_index(name: String, index: Index) -> Result<Self> {
let mut map = HashMap::new();
let new_index = IndexHandle::new(index, Settings::default(), &name)
.unwrap_or_else(|_| panic!("Unable to open index: {} because it's locked", name));
map.insert(name, new_index);
Ok(IndexCatalog {
settings: Settings::default(),
base_path: PathBuf::new(),
collection: map,
})
}
pub fn load_index(path: &str) -> Result<Index> {
let p = PathBuf::from(path);
if p.exists() {
Index::open_in_dir(p)
.map_err(|_| Error::UnknownIndex(path.to_string()))
.and_then(Ok)
} else {
Err(Error::UnknownIndex(path.to_string()))
}
}
pub fn add_index(&mut self, name: String, index: Index) {
let handle = IndexHandle::new(index, self.settings.clone(), &name)
.unwrap_or_else(|_| panic!("Unable to open index: {} because it's locked", name));
self.collection.entry(name).or_insert(handle);
}
#[allow(dead_code)]
pub fn get_collection(&self) -> &HashMap<String, IndexHandle> {
&self.collection
}
pub fn get_mut_collection(&mut self) -> &mut HashMap<String, IndexHandle> {
&mut self.collection
}
pub fn exists(&self, index: &str) -> bool {
self.get_collection().contains_key(index)
}
pub fn get_mut_index(&mut self, name: &str) -> Result<&mut IndexHandle> {
self.collection.get_mut(name).ok_or_else(|| Error::UnknownIndex(name.to_string()))
}
pub fn get_index(&self, name: &str) -> Result<&IndexHandle> {
self.collection.get(name).ok_or_else(|| Error::UnknownIndex(name.to_string()))
}
pub fn refresh_catalog(&mut self) -> Result<()> {
self.collection.clear();
for dir in read_dir(self.base_path.clone())? {
let entry = dir?.path();
if let Some(entry_str) = entry.to_str() {
if !entry_str.ends_with(".node_id") {
let pth: String = entry_str.rsplit('/').take(1).collect();
let idx = IndexCatalog::load_index(entry_str)?;
self.add_index(pth.clone(), idx);
}
} else {
return Err(Error::IOError(format!("Path {} is not a valid unicode path", entry.display())));
}
}
Ok(())
}
pub fn search_index(&self, index: &str, search: &Search) -> Result<SearchResults> {
match self.get_index(index) {
Ok(hand) => {
let idx = hand.get_index();
idx.load_searchers()?;
let searcher = idx.searcher();
let schema = idx.schema();
let fields: Vec<Field> = schema.fields().iter().filter_map(|e| schema.get_field(e.name())).collect();
let mut collector = TopCollector::with_limit(search.limit);
let mut query_parser = QueryParser::for_index(idx, fields);
query_parser.set_conjunction_by_default();
match &search.query {
Queries::TermSearch { term } => {
let terms = term.iter().map(|(t, v)| format!("{}:{}", t, v)).collect::<Vec<String>>().join(" ");
let query = query_parser.parse_query(&terms)?;
info!("{}", terms);
info!("{:#?}", query);
searcher.search(&*query, &mut collector)?;
}
Queries::RangeSearch { range } => {
info!("{:#?}", range);
let terms = range
.iter()
.map(|(field, value)| {
let mut term_query = format!("{}:", field);
let upper_inclusive = value.contains_key("lte");
let lower_inclusive = value.contains_key("gte");
if lower_inclusive {
term_query += "[";
if let Some(v) = value.get("gte") {
term_query += &v.to_string();
}
} else {
term_query += "{";
if let Some(v) = value.get("gt") {
term_query += &v.to_string();
}
}
term_query += " TO ";
if upper_inclusive {
if let Some(v) = value.get("lte") {
term_query += &v.to_string();
}
term_query += "]";
} else {
if let Some(v) = value.get("lt") {
term_query += &v.to_string();
}
term_query += "}";
}
term_query
}).collect::<Vec<String>>()
.join(" ");
let query = query_parser.parse_query(&terms)?;
info!("{}", terms);
info!("{:#?}", query);
searcher.search(&*query, &mut collector)?;
}
Queries::RawSearch { raw } => {
let query = query_parser.parse_query(&raw)?;
info!("{:#?}", query);
searcher.search(&*query, &mut collector)?;
}
Queries::SumAgg { field } => {
// This can no doubt be simplified...
let mut agg_collector = TopCollector::with_limit(searcher.num_docs() as usize);
searcher.search(&AllQuery, &mut agg_collector)?;
let f = match schema.get_field(&field) {
Some(f) => f,
None => return Err(Error::QueryError(format!("Field {} does not exist", field))),
};
let sum_agg = SumCollector::new(f, &searcher, agg_collector);
let doc = sum_agg.result().into();
let agg_schema = summary_schema();
let named_doc = ScoredDoc::new(None, agg_schema.to_named_doc(&doc));
return Ok(SearchResults::new(vec![named_doc]));
}
Queries::AllDocs => searcher.search(&AllQuery, &mut collector)?,
_ => unimplemented!(),
};
let scored_docs: Vec<ScoredDoc> = collector
.top_docs()
.into_iter()
.map(|(score, doc)| {
let d = searcher.doc(doc).expect("Doc not found in segment");
ScoredDoc::new(Some(score), schema.to_named_doc(&d))
}).collect();
Ok(SearchResults::new(scored_docs))
}
Err(e) => Err(e),
}
}
pub fn clear(&mut self) {
self.collection.clear();
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use gotham::test::{TestClient, TestServer};
use std::sync::{Arc, RwLock};
use tantivy::doc;
pub fn create_test_index() -> Index {
let mut builder = SchemaBuilder::new();
let test_text = builder.add_text_field("test_text", STORED | TEXT);
let test_int = builder.add_i64_field("test_i64", INT_STORED | INT_INDEXED);
let test_unsign = builder.add_u64_field("test_u64", INT_STORED | INT_INDEXED);
let test_unindexed = builder.add_text_field("test_unindex", STORED);
let schema = builder.build();
let idx = Index::create_in_ram(schema);
let mut writer = idx.writer(30_000_000).unwrap();
writer.add_document(doc!{ test_text => "Test Document 1", test_int => 2014i64, test_unsign => 10u64, test_unindexed => "no" });
writer.add_document(doc!{ test_text => "Test Dockument 2", test_int => -2015i64, test_unsign => 11u64, test_unindexed => "yes" });
writer.add_document(doc!{ test_text => "Test Duckiment 3", test_int => 2016i64, test_unsign => 12u64, test_unindexed => "noo" });
writer.add_document(doc!{ test_text => "Test Document 4", test_int => -2017i64, test_unsign => 13u64, test_unindexed => "yess" });
writer.add_document(doc!{ test_text => "Test Document 5", test_int => 2018i64, test_unsign => 14u64, test_unindexed => "nooo" });
writer.commit().unwrap();
idx
}
pub fn create_test_client(catalog: &Arc<RwLock<IndexCatalog>>) -> TestClient {
let server = create_test_server(catalog);
server.client()
}
pub fn create_test_server(catalog: &Arc<RwLock<IndexCatalog>>) -> TestServer {
TestServer::new(router::router_with_catalog(catalog)).unwrap()
}
}