|
| 1 | +use tantivy::collector::TopDocs; |
| 2 | +use tantivy::query::QueryParser; |
1 | 3 | use tantivy::schema::*;
|
| 4 | +use tantivy::DocAddress; |
| 5 | +use tantivy::IndexReader; |
2 | 6 | use tantivy::IndexWriter;
|
3 | 7 | use tantivy::ReloadPolicy;
|
4 |
| -use tantivy::Searcher; |
| 8 | +use tantivy::Result; |
5 | 9 |
|
6 |
| -pub struct Registry { |
| 10 | +pub struct Index { |
| 11 | + index: tantivy::Index, |
| 12 | + schema: Schema, |
| 13 | + fields: Vec<Field>, |
7 | 14 | writer: IndexWriter,
|
8 |
| - searcher: Searcher, |
| 15 | + reader: IndexReader, |
9 | 16 | }
|
10 | 17 |
|
11 |
| -pub fn create() -> tantivy::Result<Registry> { |
| 18 | +pub fn create() -> Result<Index> { |
12 | 19 | let schema_builder = Schema::builder();
|
13 | 20 |
|
14 |
| - // TODO: add schema |
| 21 | + // @TODO: create schema |
| 22 | + // @TODO: create fields from schema input |
15 | 23 |
|
| 24 | + let fields = vec![]; |
16 | 25 | let schema = schema_builder.build();
|
17 | 26 | let index = tantivy::Index::create_in_ram(schema.clone());
|
18 |
| - |
19 |
| - // index writer |
20 | 27 | let writer = index.writer(50_000_000)?;
|
21 |
| - |
22 |
| - // index reader |
23 | 28 | let reader = index
|
24 | 29 | .reader_builder()
|
25 | 30 | .reload_policy(ReloadPolicy::OnCommit)
|
26 | 31 | .try_into()?;
|
27 |
| - let searcher = reader.searcher(); |
28 | 32 |
|
29 |
| - Ok(Registry { writer, searcher }) |
| 33 | + Ok(Index { |
| 34 | + index, |
| 35 | + schema, |
| 36 | + fields, |
| 37 | + writer, |
| 38 | + reader, |
| 39 | + }) |
| 40 | +} |
| 41 | + |
| 42 | +pub fn add(index: Index, docs: Vec<Document>) -> Result<Index> { |
| 43 | + docs.iter() |
| 44 | + .map(|doc| { |
| 45 | + index.writer.add_document(doc.clone())?; |
| 46 | + Ok(()) |
| 47 | + }) |
| 48 | + .collect::<Result<()>>()?; |
| 49 | + |
| 50 | + Ok(index) |
| 51 | +} |
| 52 | + |
| 53 | +pub fn commit(mut index: Index) -> Result<Index> { |
| 54 | + index.writer.commit()?; |
| 55 | + index.reader.reload()?; |
| 56 | + |
| 57 | + Ok(index) |
30 | 58 | }
|
31 | 59 |
|
32 |
| -pub fn add() {} |
| 60 | +pub fn remove(mut index: Index, field: Field, text: &str) -> Result<Index> { |
| 61 | + let term = Term::from_field_text(field, text); |
| 62 | + |
| 63 | + index.writer.delete_term(term); |
33 | 64 |
|
34 |
| -pub fn remove() {} |
| 65 | + Ok(index) |
| 66 | +} |
| 67 | + |
| 68 | +pub fn search( |
| 69 | + index: Index, |
| 70 | + query: &str, |
| 71 | + limit: Option<usize>, |
| 72 | +) -> tantivy::Result<Vec<(f32, DocAddress)>> { |
| 73 | + let limit = limit.unwrap_or(10); |
| 74 | + let parser = QueryParser::for_index(&index.index, index.fields); |
| 75 | + let query = parser.parse_query(query)?; |
| 76 | + let searcher = index.reader.searcher(); |
| 77 | + let result = searcher.search(&query, &TopDocs::with_limit(limit))?; |
35 | 78 |
|
36 |
| -pub fn search() {} |
| 79 | + Ok(result) |
| 80 | +} |
0 commit comments