Scan documents in chunks, calling `handler` for each chunk. Processes up to `total_limit` documents in chunks of `chunk_size`. The handler receives each chunk and can accumulate results without holding all documents in memory simultaneously. Returns the total number of documents processed.
(
&self,
tenant_id: u64,
collection: &str,
total_limit: usize,
chunk_size: usize,
mut handler: F,
)
| 54 | /// |
| 55 | /// Returns the total number of documents processed. |
| 56 | pub fn scan_documents_chunked<F>( |
| 57 | &self, |
| 58 | tenant_id: u64, |
| 59 | collection: &str, |
| 60 | total_limit: usize, |
| 61 | chunk_size: usize, |
| 62 | mut handler: F, |
| 63 | ) -> crate::Result<usize> |
| 64 | where |
| 65 | F: FnMut(&[(String, Vec<u8>)]), |
| 66 | { |
| 67 | let prefix = format!("{tenant_id}:{collection}:"); |
| 68 | let end = format!("{tenant_id}:{collection}:\u{ffff}"); |
| 69 | |
| 70 | let read_txn = self.db.begin_read().map_err(|e| redb_err("read txn", e))?; |
| 71 | let table = read_txn |
| 72 | .open_table(DOCUMENTS) |
| 73 | .map_err(|e| redb_err("open table", e))?; |
| 74 | |
| 75 | let range = table |
| 76 | .range(prefix.as_str()..end.as_str()) |
| 77 | .map_err(|e| redb_err("doc range", e))?; |
| 78 | |
| 79 | let mut chunk = Vec::with_capacity(chunk_size); |
| 80 | let mut total = 0usize; |
| 81 | |
| 82 | for entry in range { |
| 83 | if total >= total_limit { |
| 84 | break; |
| 85 | } |
| 86 | let entry = entry.map_err(|e| redb_err("doc entry", e))?; |
| 87 | let key = entry.0.value().to_string(); |
| 88 | let doc_id = key.strip_prefix(&prefix).unwrap_or(&key).to_string(); |
| 89 | let value = entry.1.value().to_vec(); |
| 90 | chunk.push((doc_id, value)); |
| 91 | total += 1; |
| 92 | |
| 93 | if chunk.len() >= chunk_size { |
| 94 | handler(&chunk); |
| 95 | chunk.clear(); |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // Process remaining partial chunk. |
| 100 | if !chunk.is_empty() { |
| 101 | handler(&chunk); |
| 102 | } |
| 103 | |
| 104 | debug!(collection, total, chunk_size, "chunked document scan"); |
| 105 | Ok(total) |
| 106 | } |
| 107 | |
| 108 | /// Scan index entries grouped by value for a field. |
| 109 | /// |