╭ search.zig ───────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 3 // an inverted index over any xitdb cursor: a sorted map from word to the 4 // sorted set of doc keys whose text holds it. a doc key is opaque bytes whose 5 // sort order is the order results come back in. 6 7 // the shortest word indexed or queried. a single character would expand to 8 // hundreds of words under prefix matching. 9 const min_word_len = 2; 10 // a longer word is truncated to this rather than skipped, so a prefix query 11 // still reaches it. 12 const max_word_len = 32; 13 // how many distinct words one document contributes. 14 const max_words_per_doc = 256; 15 // how much of a document is tokenized. 16 pub const max_indexed_bytes = 16 * 1024; 17 // how many indexed words one typed word expands to. 18 const max_expansions = 50; 19 // the largest doc key, so results are read into a buffer rather than allocated. 20 pub const max_doc_key_len = 64; 21 22 // index `text` under `doc_key`. 23 pub fn add( 24 comptime DB: type, 25 index: DB.SortedMap(.read_write), 26 allocator: std.mem.Allocator, 27 doc_key: []const u8, 28 text: []const u8, 29 ) !void { 30 var arena = std.heap.ArenaAllocator.init(allocator); 31 defer arena.deinit(); 32 for (try tokenize(arena.allocator(), text)) |word| { 33 const set = try DB.SortedSet(.read_write).init(try index.putCursor(word)); 34 try set.put(doc_key); 35 } 36 } 37 38 // drop `doc_key`'s postings. the caller supplies the text again, so no forward 39 // index is stored. 40 pub fn remove( 41 comptime DB: type, 42 index: DB.SortedMap(.read_write), 43 allocator: std.mem.Allocator, 44 doc_key: []const u8, 45 text: []const u8, 46 ) !void { 47 var arena = std.heap.ArenaAllocator.init(allocator); 48 defer arena.deinit(); 49 for (try tokenize(arena.allocator(), text)) |word| { 50 if (null == try index.getCursor(word)) continue; 51 const set = try DB.SortedSet(.read_write).init(try index.putCursor(word)); 52 _ = try set.remove(doc_key); 53 if (0 == try set.count()) _ = try index.remove(word); 54 } 55 } 56 57 // the doc keys holding every typed word, in key order. a stream, so callers 58 // stop at their page size. 59 pub fn Query(comptime DB: type) type { 60 return struct { 61 // one per typed word; empty when nothing can match 62 terms: []Term, 63 // the key the next result starts from, plus room for the one byte that 64 // steps past a returned key 65 pos: [max_doc_key_len + 1]u8 = undefined, 66 pos_len: usize = 0, 67 // whether `pos` holds a key that was already returned 68 returned: bool = false, 69 70 const Self = @This(); 71 72 // one typed word: the doc keys of every indexed word it expands to, 73 // merged into one ascending stream. 74 const Term = struct { 75 postings: []Posting, 76 77 // the smallest doc key at or after `key`, or null when the term is 78 // exhausted. 79 fn seek(self: *Term, key: []const u8) !?[]const u8 { 80 var best: ?[]const u8 = null; 81 for (self.postings) |*posting| { 82 try posting.advance(key); 83 if (posting.done) continue; 84 const current = posting.key[0..posting.key_len]; 85 if (best) |found| { 86 if (std.mem.order(u8, current, found) == .lt) best = current; 87 } else best = current; 88 } 89 return best; 90 } 91 }; 92 93 // one indexed word's doc keys, positioned at the current one. 94 const Posting = struct { 95 set: DB.SortedSet(.read_only), 96 iter: DB.Cursor(.read_only).Iter = undefined, 97 key: [max_doc_key_len]u8 = undefined, 98 key_len: usize = 0, 99 done: bool = false, 100 started: bool = false, 101 102 // move to the first key at or after `key`. one step reaches it in 103 // a dense posting, and a seek skips the rest of a sparse one. 104 fn advance(self: *Posting, key: []const u8) !void { 105 if (self.done) return; 106 if (self.started) { 107 if (std.mem.order(u8, self.key[0..self.key_len], key) != .lt) return; 108 try self.step(); 109 if (self.done or std.mem.order(u8, self.key[0..self.key_len], key) != .lt) return; 110 } 111 self.iter = try self.set.iteratorFrom(key); 112 self.started = true; 113 try self.step(); 114 } 115 116 fn step(self: *Posting) !void { 117 const cursor = (try self.iter.next()) orelse { 118 self.done = true; 119 return; 120 }; 121 const pair = try cursor.readKeyValuePair(); 122 self.key_len = (try pair.key_cursor.readBytes(&self.key)).len; 123 } 124 }; 125 126 pub fn init(index: DB.SortedMap(.read_only), aa: std.mem.Allocator, text: []const u8) !Self { 127 var terms: std.ArrayList(Term) = .empty; 128 for (try tokenize(aa, text)) |word| { 129 var postings: std.ArrayList(Posting) = .empty; 130 var iter = try index.iteratorFrom(word); 131 while (try iter.next()) |cursor| { 132 if (postings.items.len == max_expansions) break; 133 const pair = try cursor.readKeyValuePair(); 134 var buffer: [max_word_len]u8 = undefined; 135 const indexed = try pair.key_cursor.readBytes(&buffer); 136 if (!std.mem.startsWith(u8, indexed, word)) break; 137 try postings.append(aa, .{ .set = try DB.SortedSet(.read_only).init(pair.value_cursor) }); 138 } 139 // a word nothing starts with rules out every document 140 if (postings.items.len == 0) return .{ .terms = &.{} }; 141 try terms.append(aa, .{ .postings = postings.items }); 142 } 143 return .{ .terms = terms.items }; 144 } 145 146 // narrow the results to the doc keys in `set`. it is one more term, 147 // with that set as its only posting. a query nothing can match stays 148 // empty, since requiring a set would turn it into every doc key in it. 149 pub fn require(self: *Self, aa: std.mem.Allocator, set: DB.SortedSet(.read_only)) !void { 150 if (self.terms.len == 0) return; 151 var terms: std.ArrayList(Term) = .empty; 152 try terms.appendSlice(aa, self.terms); 153 const postings = try aa.alloc(Posting, 1); 154 postings[0] = .{ .set = set }; 155 try terms.append(aa, .{ .postings = postings }); 156 self.terms = terms.items; 157 } 158 159 // start the next result at `key` rather than the first one. 160 pub fn seek(self: *Self, key: []const u8) void { 161 @memcpy(self.pos[0..key.len], key); 162 self.pos_len = key.len; 163 self.returned = false; 164 } 165 166 pub fn next(self: *Self) !?[]const u8 { 167 if (self.terms.len == 0) return null; 168 if (self.returned) { 169 // doc keys are at most max_doc_key_len, so appending a byte 170 // lands strictly after the one just returned 171 self.pos[self.pos_len] = 0; 172 self.pos_len += 1; 173 self.returned = false; 174 } 175 // intersect by seeking: a term that lands past the candidate makes 176 // its key the new candidate and the others seek up to it. 177 var i: usize = 0; 178 while (i < self.terms.len) { 179 const key = (try self.terms[i].seek(self.pos[0..self.pos_len])) orelse return null; 180 if (std.mem.order(u8, key, self.pos[0..self.pos_len]) == .gt) { 181 @memcpy(self.pos[0..key.len], key); 182 self.pos_len = key.len; 183 i = 0; 184 continue; 185 } 186 i += 1; 187 } 188 self.returned = true; 189 return self.pos[0..self.pos_len]; 190 } 191 }; 192 } 193 194 // the unique lowercased words of `text`, in the order they first appear. 195 fn tokenize(aa: std.mem.Allocator, text: []const u8) ![]const []const u8 { 196 var words: std.StringArrayHashMapUnmanaged(void) = .empty; 197 const limit = @min(text.len, max_indexed_bytes); 198 var i: usize = 0; 199 while (i < limit) { 200 if (!isWordByte(text[i])) { 201 i += 1; 202 continue; 203 } 204 const start = i; 205 while (i < limit and isWordByte(text[i])) i += 1; 206 const word = text[start..@min(i, start + max_word_len)]; 207 if (word.len < min_word_len) continue; 208 const lowered = try aa.alloc(u8, word.len); 209 _ = std.ascii.lowerString(lowered, word); 210 try words.put(aa, lowered, {}); 211 if (words.count() == max_words_per_doc) break; 212 } 213 return words.keys(); 214 } 215 216 // a word is a run of ascii alphanumerics and non-ascii bytes. 217 fn isWordByte(byte: u8) bool { 218 return std.ascii.isAlphanumeric(byte) or byte >= 0x80; 219 } 220