seekstorm 3.2.2

Vector & lexical search engine library & multi-tenancy server
Documentation
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
use ahash::{AHashMap, AHashSet};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};
use tokio::sync::RwLock;
use utoipa::ToSchema;

#[cfg(feature = "vb")]
use crate::vector::ResultSource;
use crate::{
    add_result::{PostingListObjectSingle, add_result_singleterm_multifield},
    index::{Index, IndexArc, NgramType, Shard},
    min_heap::Result,
    search::{FilterSparse, ResultObject, ResultSort, ResultType, SearchResult, SortOrder},
};

/// Iterator result
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
pub struct IteratorResultItem {
    /// document ID
    pub doc_id: u64,
    /// document
    pub doc: Option<IndexMap<String, Value>>,
}

/// Iterator
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
pub struct IteratorResult {
    /// number of actually skipped documents
    pub skip: usize,
    /// document IDs, and optionally the documents themselves
    pub results: Vec<IteratorResultItem>,
}

/// Document iterator
/// The document iterator allows to iterate over all document IDs and documents in the entire index, forward or backward.
/// It enables efficient sequential access to every document, even in very large indexes, without running a search.
/// Paging through the index works without collecting document IDs to Min-heap in size-limited RAM first.
/// The iterator guarantees that only valid document IDs are returned, even though document IDs are not strictly continuous.
/// Document IDs can also be fetched in batches, reducing round trips and significantly improving performance, especially when using the REST API.
/// Typical use cases include index export, conversion, analytics, audits, and inspection.
/// Explanation of "eventually continuous" docid:
/// In SeekStorm, document IDs become continuous over time. In a multi-sharded index, each shard maintains its own document ID space.
/// Because documents are distributed across shards in a non-deterministic, load-dependent way, shard-local document IDs advance at different rates.
/// When these are mapped to global document IDs, temporary gaps can appear.
/// As a result, simply iterating from 0 to the total document count may encounter invalid IDs near the end.
/// The Document Iterator abstracts this complexity and reliably returns only valid document IDs.
/// - docid=None, take>0: **skip first s document IDs**, then **take next t document IDs** of an index.
/// - docid=None, take<0: **skip last s document IDs**, then **take previous t document IDs** of an index.
/// - docid=Some, take>0: **skip next s document IDs**, then **take next t document IDs** of an index, relative to a given document ID, with end-of-index indicator.
/// - docid=Some, take<0: **skip previous s document IDs**, then **take previous t document IDs**, relative to a given document ID, with start-of-index indicator.
/// - take=0: does not make sense, that defies the purpose of get_iterator.
/// - The sign of take indicates the direction of iteration: positive take for forward iteration, negative take for backward iteration.
/// - The skip parameter is always positive, indicating the number of document IDs to skip before taking document IDs. The skip direction is determined by the sign of take too.
///
/// Next page:     take last  docid from previous result set, skip=1, take=+page_size
/// Previous page: take first docid from previous result set, skip=1, take=-page_size
/// Returns a tuple of (number of actually skipped document IDs, vec of taken document IDs, sorted ascending).
/// Detect end/begin of index during iteration: if returned vec.len() < requested take || if returned skip <requested skip
#[allow(async_fn_in_trait)]
pub trait GetIterator {
    /// Document iterator
    /// The document iterator allows to iterate over all document IDs and documents in the entire index, forward or backward.
    /// It enables efficient sequential access to every document, even in very large indexes, without running a search.
    /// Paging through the index works without collecting document IDs to Min-heap in size-limited RAM first.
    /// The iterator guarantees that only valid document IDs are returned, even though document IDs are not strictly continuous.
    /// Document IDs can also be fetched in batches, reducing round trips and significantly improving performance, especially when using the REST API.
    /// Typical use cases include index export, conversion, analytics, audits, and inspection.
    /// Explanation of "eventually continuous" docid:
    /// In SeekStorm, document IDs become continuous over time. In a multi-sharded index, each shard maintains its own document ID space.
    /// Because documents are distributed across shards in a non-deterministic, load-dependent way, shard-local document IDs advance at different rates.
    /// When these are mapped to global document IDs, temporary gaps can appear.
    /// As a result, simply iterating from 0 to the total document count may encounter invalid IDs near the end.
    /// The Document Iterator abstracts this complexity and reliably returns only valid document IDs.
    /// - docid=None, take>0: **skip first s document IDs**, then **take next t document IDs** of an index.
    /// - docid=None, take<0: **skip last s document IDs**, then **take previous t document IDs** of an index.
    /// - docid=Some, take>0: **skip next s document IDs**, then **take next t document IDs** of an index, relative to a given document ID, with end-of-index indicator.
    /// - docid=Some, take<0: **skip previous s document IDs**, then **take previous t document IDs**, relative to a given document ID, with start-of-index indicator.
    /// - take=0: does not make sense, that defies the purpose of get_iterator.
    /// - The sign of take indicates the direction of iteration: positive take for forward iteration, negative take for backward iteration.
    /// - The skip parameter is always positive, indicating the number of document IDs to skip before taking document IDs. The skip direction is determined by the sign of take too.
    ///
    /// Next page:     take last  docid from previous result set, skip=1, take=+page_size
    /// Previous page: take first docid from previous result set, skip=1, take=-page_size
    /// Returns a tuple of (number of actually skipped document IDs, vec of taken document IDs, sorted ascending).
    /// Detect end/begin of index during iteration: if returned vec.len() < requested take || if returned skip <requested skip
    async fn get_iterator(
        &self,
        docid: Option<u64>,
        skip: usize,
        take: isize,
        include_deleted: bool,
        include_document: bool,
        fields: Vec<String>,
    ) -> IteratorResult;
}

impl GetIterator for IndexArc {
    async fn get_iterator(
        &self,
        docid: Option<u64>,
        skip: usize,
        take: isize,
        include_deleted: bool,
        include_document: bool,
        fields: Vec<String>,
    ) -> IteratorResult {
        if take == 0 {
            return IteratorResult {
                skip,
                results: Vec::new(),
            };
        }

        let fields_hashset: std::collections::HashSet<String> =
            std::collections::HashSet::from_iter(fields);

        let mut min_docid: Option<u64> = None;
        let mut max_docid: Option<u64> = None;
        let shard_number = self.read().await.shard_number as u64;
        for (shard_id, shard) in self.read().await.shard_vec.iter().enumerate() {
            let shard_ref = shard.read().await;
            let shard_indexed_doc_count = shard_ref.indexed_doc_count as u64;

            if shard_indexed_doc_count == 0 {
                continue;
            }

            if shard_indexed_doc_count > 0 {
                let shard_max_docid =
                    shard_id as u64 + ((shard_indexed_doc_count - 1) * shard_number);

                if min_docid.is_none() {
                    min_docid = Some(shard_id as u64);
                }

                if max_docid.is_none() || shard_max_docid > max_docid.unwrap() {
                    max_docid = Some(shard_max_docid);
                }
            }
        }

        if min_docid.is_none() || max_docid.is_none() {
            return IteratorResult {
                skip,
                results: Vec::new(),
            };
        }

        let mut results: Vec<IteratorResultItem> = Vec::new();
        let mut skip_count = 0;

        if take > 0 {
            let mut docid = if let Some(docid_value) = docid {
                if docid_value < min_docid.unwrap() || docid_value > max_docid.unwrap() {
                    return IteratorResult {
                        skip,
                        results: Vec::new(),
                    };
                }
                docid_value
            } else {
                min_docid.unwrap()
            };

            while results.len() < take.unsigned_abs() {
                let shard_id = docid % shard_number;
                let docid_shard = docid / shard_number;

                let shard_ref = &self.read().await.shard_vec[shard_id as usize];
                let docid_shard_max = shard_ref.read().await.indexed_doc_count as u64;
                if docid_shard_max == 0
                    || docid_shard >= docid_shard_max
                    || (!include_deleted
                        && shard_ref
                            .read()
                            .await
                            .delete_hashset
                            .contains(&(docid_shard as usize)))
                {
                    if docid >= max_docid.unwrap() {
                        break;
                    }
                    docid += 1;
                    continue;
                }

                if skip_count < skip {
                    if docid >= max_docid.unwrap() {
                        break;
                    }
                    docid += 1;
                    skip_count += 1;
                    continue;
                }

                let result = if include_document {
                    IteratorResultItem {
                        doc_id: docid,
                        doc: self
                            .read()
                            .await
                            .get_document(
                                docid as usize,
                                false,
                                &None,
                                &fields_hashset,
                                &Vec::new(),
                            )
                            .await
                            .ok(),
                    }
                } else {
                    IteratorResultItem {
                        doc_id: docid,
                        doc: None,
                    }
                };
                results.push(result);
                if docid >= max_docid.unwrap() {
                    break;
                }
                docid += 1;
            }
            IteratorResult {
                skip: skip_count,
                results,
            }
        } else {
            let mut docid = if let Some(docid_value) = docid {
                if docid_value < min_docid.unwrap() || docid_value > max_docid.unwrap() {
                    return IteratorResult {
                        skip,
                        results: Vec::new(),
                    };
                }
                docid_value
            } else {
                max_docid.unwrap()
            };

            while results.len() < take.unsigned_abs() {
                let shard_id = docid % shard_number;
                let docid_shard = docid / shard_number;

                let shard_ref = &self.read().await.shard_vec[shard_id as usize];
                let docid_shard_max = shard_ref.read().await.indexed_doc_count as u64;
                if docid_shard_max == 0
                    || docid_shard >= docid_shard_max
                    || (!include_deleted
                        && shard_ref
                            .read()
                            .await
                            .delete_hashset
                            .contains(&(docid_shard as usize)))
                {
                    if docid <= min_docid.unwrap() {
                        break;
                    }
                    docid -= 1;

                    continue;
                }

                if skip_count < skip {
                    if docid <= min_docid.unwrap() {
                        break;
                    }
                    docid -= 1;
                    skip_count += 1;
                    continue;
                }

                let result = if include_document {
                    IteratorResultItem {
                        doc_id: docid,
                        doc: self
                            .read()
                            .await
                            .get_document(
                                docid as usize,
                                false,
                                &None,
                                &std::collections::HashSet::new(),
                                &Vec::new(),
                            )
                            .await
                            .ok(),
                    }
                } else {
                    IteratorResultItem {
                        doc_id: docid,
                        doc: None,
                    }
                };
                results.push(result);
                if docid <= min_docid.unwrap() {
                    break;
                }
                docid -= 1;
            }

            IteratorResult {
                skip: skip_count,
                results,
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) async fn search_iterator_shard(
    shard: &Shard,
    result_type: ResultType,
    _include_uncommitted: bool,
    result_count_arc: &Arc<AtomicUsize>,
    search_result: &mut SearchResult<'_>,
    top_k: usize,
    facet_filter: &[FilterSparse],
) {
    let mut result_count_local = 0i32;

    let plo_single = PostingListObjectSingle {
        rank_position_pointer_range: 0,
        pointer_pivot_p_docid: 0,
        byte_array: &[],
        p_docid: 0,
        idf: 0.0,
        idf_ngram1: 0.0,
        idf_ngram2: 0.0,
        idf_ngram3: 0.0,
        ngram_type: NgramType::SingleTerm,
    };

    let mut not_query_list = Vec::new();

    for docid in 0..shard.indexed_doc_count {
        add_result_singleterm_multifield(
            shard,
            docid,
            &mut result_count_local,
            search_result,
            top_k,
            &result_type,
            &AHashSet::new(),
            facet_filter,
            &plo_single,
            &mut not_query_list,
            0.0,
        );
    }

    result_count_arc.fetch_add(result_count_local as usize, Ordering::Relaxed);
}

pub(crate) async fn search_iterator_index(
    index_arc: &Arc<RwLock<Index>>,
    offset: usize,
    length: usize,
    result_type: ResultType,
    _include_uncommitted: bool,
    result_sort: Vec<ResultSort>,
) -> ResultObject {
    let mut result_object = ResultObject {
        original_query: "".to_string(),
        query: "".to_string(),
        query_terms: Vec::new(),
        result_count: 0,
        result_count_total: 0,
        observed_vector_count: 0,
        observed_cluster_count: 0,
        results: Vec::new(),
        facets: AHashMap::new(),
        suggestions: Vec::new(),
    };

    let indexed_doc_count = index_arc.read().await.indexed_doc_count().await;

    if result_type != ResultType::Count {
        let iterator = if result_sort.len() == 1
            && !result_sort.is_empty()
            && result_sort.first().unwrap().order == SortOrder::Ascending
        {
            index_arc
                .get_iterator(None, offset, length as isize, false, false, vec![])
                .await
        } else {
            index_arc
                .get_iterator(None, offset, -(length as isize), false, false, vec![])
                .await
        };

        for result in iterator.results.iter() {
            result_object.results.push(Result {
                doc_id: result.doc_id as usize,
                score: 0.0,

                #[cfg(feature = "vb")]
                source: ResultSource::Lexical,
                ..Default::default()
            });
        }

        result_object.result_count = result_object.results.len();
    }
    result_object.result_count_total = indexed_doc_count;

    result_object
}