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
//! Phrase Search for TextFTSIndex
//!
//! Implements exact phrase matching using positional indexes:
//! - "machine learning" β find docs where "machine" immediately precedes "learning"
//! - Uses inverted index positions for fast matching
//! - O(n) complexity where n = docs containing first term
use crate::{Result, StorageError};
use crate::index::text_types::{DocId, Position, PostingList};
use std::collections::HashMap;
/// Phrase search executor
pub struct PhraseSearcher;
impl PhraseSearcher {
/// Search for exact phrase in a TextFTSIndex
///
/// High-level API that works with TextFTSIndex
pub fn search_phrase_in_index(
index: &crate::index::TextFTSIndex,
phrase: &str,
) -> Result<Vec<(DocId, u32)>> {
use crate::index::text_types::Tokenizer;
// Tokenize phrase
let tokenizer = index.get_tokenizer();
let tokens = tokenizer.tokenize(phrase);
if tokens.is_empty() {
return Ok(vec![]);
}
// Get posting lists for each term
let mut term_postings = Vec::new();
for token in &tokens {
if let Some(posting) = index.get_posting_list(&token.text)? {
term_postings.push(posting);
} else {
// Term not found, no matches
return Ok(vec![]);
}
}
// Convert to references for search
let posting_refs: Vec<&PostingList> = term_postings.iter().collect();
Self::search(&posting_refs)
}
/// Search with proximity in a TextFTSIndex
pub fn search_proximity_in_index(
index: &crate::index::TextFTSIndex,
terms: &str,
max_distance: u32,
) -> Result<Vec<(DocId, u32)>> {
use crate::index::text_types::Tokenizer;
// Tokenize terms
let tokenizer = index.get_tokenizer();
let tokens = tokenizer.tokenize(terms);
if tokens.is_empty() {
return Ok(vec![]);
}
// Get posting lists for each term
let mut term_postings = Vec::new();
for token in &tokens {
if let Some(posting) = index.get_posting_list(&token.text)? {
term_postings.push(posting);
} else {
return Ok(vec![]);
}
}
// Convert to references for search
let posting_refs: Vec<&PostingList> = term_postings.iter().collect();
Self::search_with_proximity(&posting_refs, max_distance)
}
/// Search for exact phrase in posting lists
///
/// Algorithm:
/// 1. Find docs containing all terms
/// 2. For each doc, verify positions are consecutive
///
/// # Arguments
/// * `term_postings` - Posting lists for each term in phrase (in order)
///
/// # Returns
/// Vec of (doc_id, match_count) pairs
///
/// # Example
/// ```ignore
/// // Search "machine learning"
/// let postings = vec![machine_postings, learning_postings];
/// let results = PhraseSearcher::search(&postings)?;
/// ```
pub fn search(term_postings: &[&PostingList]) -> Result<Vec<(DocId, u32)>> {
if term_postings.is_empty() {
return Ok(vec![]);
}
if term_postings.len() == 1 {
// Single term: return all docs
return Ok(term_postings[0]
.doc_ids()
.iter()
.map(|&doc_id| (doc_id, 1))
.collect());
}
// Find candidate docs (intersection of all term doc_ids)
let candidate_docs = Self::find_candidate_docs(term_postings)?;
// Verify phrase matches in each candidate doc
// π P1 δΌεοΌι’ει
ειζζ‘£ζ°ι
let mut results = Vec::with_capacity(candidate_docs.len());
for doc_id in candidate_docs {
if let Some(count) = Self::verify_phrase_in_doc(doc_id, term_postings)? {
results.push((doc_id, count));
}
}
Ok(results)
}
/// Find docs containing all terms (intersection)
fn find_candidate_docs(term_postings: &[&PostingList]) -> Result<Vec<DocId>> {
let mut candidate_docs: Vec<DocId> = term_postings[0]
.doc_ids()
.iter()
.copied()
.collect();
// Intersect with remaining terms
for posting in &term_postings[1..] {
let doc_set: std::collections::HashSet<DocId> =
posting.doc_ids().iter().copied().collect();
candidate_docs.retain(|doc_id| doc_set.contains(doc_id));
if candidate_docs.is_empty() {
break; // Early exit
}
}
Ok(candidate_docs)
}
/// Verify phrase exists in document by checking consecutive positions
///
/// Returns: Some(match_count) if phrase found, None otherwise
fn verify_phrase_in_doc(
doc_id: DocId,
term_postings: &[&PostingList],
) -> Result<Option<u32>> {
// Get positions for each term in this doc
let mut positions_per_term: Vec<Vec<Position>> = Vec::new();
for posting in term_postings {
match posting.get_positions(doc_id) {
Some(positions) => positions_per_term.push(positions.to_vec()),
None => {
// Position index disabled or doc not found
return Err(StorageError::InvalidData(
"β PHRASE_SEARCH requires position indexing to be enabled.\n\
π‘ Solution: Re-create the TEXT index with:\n\
\n\
DROP INDEX <index_name>;\n\
CREATE TEXT INDEX <index_name> ON <table>(<column>) WITH POSITIONS;\n\
\n\
Note: Position indexing adds ~40% memory overhead but enables phrase/proximity search.".to_string()
).into());
}
}
}
// Find consecutive matches
let match_count = Self::count_consecutive_matches(&positions_per_term);
if match_count > 0 {
Ok(Some(match_count))
} else {
Ok(None)
}
}
/// Count consecutive position matches
///
/// Example:
/// - term[0] positions: [5, 10, 20]
/// - term[1] positions: [6, 21]
/// β Matches at (5,6) and (20,21) β count = 2
fn count_consecutive_matches(positions_per_term: &[Vec<Position>]) -> u32 {
if positions_per_term.is_empty() {
return 0;
}
let mut match_count = 0;
// For each position of first term, try to find consecutive chain
for &first_pos in &positions_per_term[0] {
let mut current_pos = first_pos;
let mut matched = true;
// Check if subsequent terms appear at consecutive positions
for term_idx in 1..positions_per_term.len() {
let expected_pos = current_pos + 1;
if positions_per_term[term_idx].contains(&expected_pos) {
current_pos = expected_pos;
} else {
matched = false;
break;
}
}
if matched {
match_count += 1;
}
}
match_count
}
/// Search with proximity: terms within N positions of each other
///
/// Example: "machine learning"~5 β terms within 5 words
pub fn search_with_proximity(
term_postings: &[&PostingList],
max_distance: u32,
) -> Result<Vec<(DocId, u32)>> {
if term_postings.is_empty() {
return Ok(vec![]);
}
let candidate_docs = Self::find_candidate_docs(term_postings)?;
// π P1 δΌεοΌι’ει
ειζζ‘£ζ°ι
let mut results = Vec::with_capacity(candidate_docs.len());
for doc_id in candidate_docs {
if let Some(count) = Self::verify_proximity_in_doc(doc_id, term_postings, max_distance)? {
results.push((doc_id, count));
}
}
Ok(results)
}
/// Verify terms appear within max_distance of each other
fn verify_proximity_in_doc(
doc_id: DocId,
term_postings: &[&PostingList],
max_distance: u32,
) -> Result<Option<u32>> {
let mut positions_per_term: Vec<Vec<Position>> = Vec::new();
for posting in term_postings {
match posting.get_positions(doc_id) {
Some(positions) => positions_per_term.push(positions.to_vec()),
None => return Ok(None),
}
}
let match_count = Self::count_proximity_matches(&positions_per_term, max_distance);
if match_count > 0 {
Ok(Some(match_count))
} else {
Ok(None)
}
}
/// Count matches within proximity distance
fn count_proximity_matches(positions_per_term: &[Vec<Position>], max_distance: u32) -> u32 {
if positions_per_term.is_empty() {
return 0;
}
let mut match_count = 0;
// For each position of first term
for &first_pos in &positions_per_term[0] {
let mut all_within_range = true;
// Check if all other terms appear within max_distance
for term_idx in 1..positions_per_term.len() {
let within_range = positions_per_term[term_idx].iter().any(|&pos| {
let distance = if pos > first_pos {
pos - first_pos
} else {
first_pos - pos
};
distance <= max_distance
});
if !within_range {
all_within_range = false;
break;
}
}
if all_within_range {
match_count += 1;
}
}
match_count
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::index::text_types::PostingList;
#[test]
fn test_consecutive_matches() {
let positions = vec![
vec![5, 10, 20], // "machine"
vec![6, 21], // "learning"
];
let count = PhraseSearcher::count_consecutive_matches(&positions);
assert_eq!(count, 2); // (5,6) and (20,21)
}
#[test]
fn test_no_consecutive_matches() {
let positions = vec![
vec![5, 10], // "machine"
vec![7, 21], // "learning" (not consecutive)
];
let count = PhraseSearcher::count_consecutive_matches(&positions);
assert_eq!(count, 0);
}
#[test]
fn test_proximity_matches() {
let positions = vec![
vec![5, 20], // "machine"
vec![8, 22], // "learning" (distance 3 and 2)
];
let count = PhraseSearcher::count_proximity_matches(&positions, 5);
assert_eq!(count, 2); // Both within distance 5
let count = PhraseSearcher::count_proximity_matches(&positions, 2);
assert_eq!(count, 1); // Only (20,22) within distance 2
}
}