lance 4.0.0

A columnar data format that is 100x faster than Parquet for random access.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! In-memory Full-Text Search (FTS) index.
//!
//! Provides inverted index for text search using crossbeam-skiplist.
//! Uses the same tokenization as Lance's InvertedIndex for consistency.
//!
//! ## Current Features
//! - BM25 scoring algorithm for relevance ranking
//! - Automatic result ordering by score (descending)
//! - Single-column term queries
//! - Phrase queries with slop support
//!
//! ## Pending Features (TODO)
//! - Multi-column search: Search across multiple columns simultaneously
//! - Boolean queries: MUST/SHOULD/MUST_NOT for complex query logic
//! - Fuzzy matching: Typo tolerance with configurable edit distance
//! - Boost queries: Positive/negative boosting for relevance tuning
//! - WAND factor: Performance/recall tradeoff control
//! - Per-term/column boost: Fine-grained relevance weighting
//!
//! **Note**: FTS index flush to persistent storage is NOT YET IMPLEMENTED.
//! The in-memory index works for real-time queries on MemTable data,
//! but is skipped during MemTable flush.

use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};

use arrow_array::RecordBatch;
use crossbeam_skiplist::SkipMap;
use datafusion::common::ScalarValue;
use lance_core::{Error, Result};
use lance_index::scalar::InvertedIndexParams;
use lance_index::scalar::inverted::tokenizer::lance_tokenizer::LanceTokenizer;
use tantivy::tokenizer::TokenStream;

use super::RowPosition;

/// Composite key for FTS index.
///
/// By combining (token, row_position), each entry is unique.
/// This follows the same pattern as IndexKey and IvfPqKey.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FtsKey {
    /// The indexed token (lowercase).
    pub token: String,
    /// Row position (makes the key unique for tokens appearing in multiple docs).
    pub row_position: RowPosition,
}

/// In-memory FTS (Full-Text Search) index entry (returned from search).
#[derive(Debug, Clone)]
pub struct FtsEntry {
    /// Row position in MemTable.
    pub row_position: RowPosition,
    /// BM25 score for this document.
    pub score: f32,
}

/// Full-text search query expression for composable queries.
///
/// Supports simple term matches, phrase queries, fuzzy matching, and Boolean
/// combinations with MUST/SHOULD/MUST_NOT logic.
#[derive(Debug, Clone)]
pub enum FtsQueryExpr {
    /// Simple term match query.
    Match {
        /// The search query string.
        query: String,
        /// Boost factor applied to the score (default 1.0).
        boost: f32,
    },
    /// Phrase query with optional slop.
    Phrase {
        /// The phrase to search for.
        query: String,
        /// Maximum allowed distance between consecutive tokens.
        slop: u32,
        /// Boost factor applied to the score (default 1.0).
        boost: f32,
    },
    /// Fuzzy match query with typo tolerance.
    Fuzzy {
        /// The search query string.
        query: String,
        /// Maximum edit distance (Levenshtein distance).
        /// None means auto-fuzziness based on token length.
        fuzziness: Option<u32>,
        /// Maximum number of terms to expand to (default 50).
        max_expansions: usize,
        /// Boost factor applied to the score (default 1.0).
        boost: f32,
    },
    /// Boolean combination of queries.
    Boolean {
        /// All MUST clauses must match for a document to be included.
        must: Vec<Self>,
        /// At least one SHOULD clause should match (adds to score).
        should: Vec<Self>,
        /// No MUST_NOT clause may match (excludes documents).
        must_not: Vec<Self>,
    },
    /// Boosting query with positive and optional negative components.
    ///
    /// Documents matching the positive query are returned.
    /// If a negative query is provided, documents matching both positive
    /// and negative have their scores reduced by `negative_boost`.
    Boost {
        /// The primary query (documents must match this).
        positive: Box<Self>,
        /// Optional query to demote matching documents.
        negative: Option<Box<Self>>,
        /// Boost factor for documents matching negative query (typically < 1.0).
        /// Score becomes: original_score * negative_boost for docs matching negative.
        negative_boost: f32,
    },
}

/// Default maximum number of fuzzy expansions.
pub const DEFAULT_MAX_EXPANSIONS: usize = 50;

/// Default WAND factor for full recall (no early termination).
pub const DEFAULT_WAND_FACTOR: f32 = 1.0;

/// Search options for controlling performance/recall tradeoffs.
///
/// The WAND (Weak AND) factor allows trading recall for performance:
/// - `wand_factor = 1.0`: Full recall (default), all matching documents returned
/// - `wand_factor < 1.0`: Faster but may miss some results. Documents with
///   scores below `top_k_score * wand_factor` are pruned.
///
/// # Example
/// ```ignore
/// let options = SearchOptions::default()
///     .with_limit(10)
///     .with_wand_factor(0.5);
/// let results = index.search_with_options(&query, options);
/// ```
#[derive(Debug, Clone)]
pub struct SearchOptions {
    /// WAND factor for early termination (0.0 to 1.0).
    /// 1.0 = full recall, <1.0 = faster but may miss low-scoring results.
    pub wand_factor: f32,
    /// Maximum number of results to return. None means unlimited.
    pub limit: Option<usize>,
}

impl Default for SearchOptions {
    fn default() -> Self {
        Self {
            wand_factor: DEFAULT_WAND_FACTOR,
            limit: None,
        }
    }
}

impl SearchOptions {
    /// Create new SearchOptions with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the WAND factor for early termination.
    ///
    /// - 1.0 = full recall (default)
    /// - 0.5 = prune documents scoring below 50% of the current k-th best score
    /// - 0.0 = only return the absolute best match
    pub fn with_wand_factor(mut self, wand_factor: f32) -> Self {
        self.wand_factor = wand_factor.clamp(0.0, 1.0);
        self
    }

    /// Set the maximum number of results to return.
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }
}

impl FtsQueryExpr {
    /// Create a simple match query.
    pub fn match_query(query: impl Into<String>) -> Self {
        Self::Match {
            query: query.into(),
            boost: 1.0,
        }
    }

    /// Create a phrase query with exact matching (slop=0).
    pub fn phrase(query: impl Into<String>) -> Self {
        Self::Phrase {
            query: query.into(),
            slop: 0,
            boost: 1.0,
        }
    }

    /// Create a phrase query with specified slop.
    pub fn phrase_with_slop(query: impl Into<String>, slop: u32) -> Self {
        Self::Phrase {
            query: query.into(),
            slop,
            boost: 1.0,
        }
    }

    /// Create a fuzzy match query with auto-fuzziness.
    ///
    /// Auto-fuzziness is calculated based on token length:
    /// - 0-2 chars: 0 (exact match)
    /// - 3-5 chars: 1
    /// - 6+ chars: 2
    pub fn fuzzy(query: impl Into<String>) -> Self {
        Self::Fuzzy {
            query: query.into(),
            fuzziness: None, // auto
            max_expansions: DEFAULT_MAX_EXPANSIONS,
            boost: 1.0,
        }
    }

    /// Create a fuzzy match query with specified edit distance.
    pub fn fuzzy_with_distance(query: impl Into<String>, fuzziness: u32) -> Self {
        Self::Fuzzy {
            query: query.into(),
            fuzziness: Some(fuzziness),
            max_expansions: DEFAULT_MAX_EXPANSIONS,
            boost: 1.0,
        }
    }

    /// Create a fuzzy match query with specified edit distance and max expansions.
    pub fn fuzzy_with_options(
        query: impl Into<String>,
        fuzziness: Option<u32>,
        max_expansions: usize,
    ) -> Self {
        Self::Fuzzy {
            query: query.into(),
            fuzziness,
            max_expansions,
            boost: 1.0,
        }
    }

    /// Create a Boolean query.
    pub fn boolean() -> BooleanQueryBuilder {
        BooleanQueryBuilder::new()
    }

    /// Create a boosting query with only a positive component.
    ///
    /// This is equivalent to just running the positive query.
    pub fn boosting(positive: Self) -> Self {
        Self::Boost {
            positive: Box::new(positive),
            negative: None,
            negative_boost: 1.0,
        }
    }

    /// Create a boosting query with positive and negative components.
    ///
    /// Documents matching the positive query are returned.
    /// Documents matching both positive and negative have their scores
    /// multiplied by `negative_boost` (typically < 1.0 to demote).
    ///
    /// # Arguments
    ///
    /// * `positive` - The primary query (documents must match this)
    /// * `negative` - Query to demote matching documents
    /// * `negative_boost` - Multiplier for documents matching negative (e.g., 0.5)
    pub fn boosting_with_negative(positive: Self, negative: Self, negative_boost: f32) -> Self {
        Self::Boost {
            positive: Box::new(positive),
            negative: Some(Box::new(negative)),
            negative_boost,
        }
    }

    /// Apply a boost factor to this query.
    pub fn with_boost(self, boost: f32) -> Self {
        match self {
            Self::Match { query, .. } => Self::Match { query, boost },
            Self::Phrase { query, slop, .. } => Self::Phrase { query, slop, boost },
            Self::Fuzzy {
                query,
                fuzziness,
                max_expansions,
                ..
            } => Self::Fuzzy {
                query,
                fuzziness,
                max_expansions,
                boost,
            },
            Self::Boolean {
                must,
                should,
                must_not,
            } => {
                // For Boolean queries, boost is not directly applied
                // (would need to apply to sub-queries)
                Self::Boolean {
                    must,
                    should,
                    must_not,
                }
            }
            Self::Boost {
                positive,
                negative,
                negative_boost,
            } => {
                // For Boost queries, we wrap the positive in a boosted match
                // This is a bit unusual - typically you'd boost individual sub-queries
                Self::Boost {
                    positive,
                    negative,
                    negative_boost,
                }
            }
        }
    }
}

/// Calculate auto-fuzziness based on token length.
///
/// This follows the same algorithm as Lance's existing InvertedIndex:
/// - 0-2 chars: 0 (exact match only)
/// - 3-5 chars: 1 edit allowed
/// - 6+ chars: 2 edits allowed
pub fn auto_fuzziness(token: &str) -> u32 {
    match token.chars().count() {
        0..=2 => 0,
        3..=5 => 1,
        _ => 2,
    }
}

/// Calculate Levenshtein distance between two strings.
///
/// Returns the minimum number of single-character edits (insertions,
/// deletions, or substitutions) required to transform one string into another.
pub fn levenshtein_distance(a: &str, b: &str) -> u32 {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let m = a_chars.len();
    let n = b_chars.len();

    // Handle edge cases
    if m == 0 {
        return n as u32;
    }
    if n == 0 {
        return m as u32;
    }

    // Use two rows instead of full matrix for space efficiency
    let mut prev_row: Vec<u32> = (0..=n as u32).collect();
    let mut curr_row: Vec<u32> = vec![0; n + 1];

    for (i, a_char) in a_chars.iter().enumerate() {
        curr_row[0] = (i + 1) as u32;

        for (j, b_char) in b_chars.iter().enumerate() {
            let cost = if a_char == b_char { 0 } else { 1 };

            curr_row[j + 1] = (prev_row[j + 1] + 1) // deletion
                .min(curr_row[j] + 1) // insertion
                .min(prev_row[j] + cost); // substitution
        }

        std::mem::swap(&mut prev_row, &mut curr_row);
    }

    prev_row[n]
}

/// Builder for constructing Boolean queries.
#[derive(Debug, Clone, Default)]
pub struct BooleanQueryBuilder {
    must: Vec<FtsQueryExpr>,
    should: Vec<FtsQueryExpr>,
    must_not: Vec<FtsQueryExpr>,
}

impl BooleanQueryBuilder {
    /// Create a new Boolean query builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a MUST clause (document must match).
    pub fn must(mut self, query: FtsQueryExpr) -> Self {
        self.must.push(query);
        self
    }

    /// Add a SHOULD clause (document should match, adds to score).
    pub fn should(mut self, query: FtsQueryExpr) -> Self {
        self.should.push(query);
        self
    }

    /// Add a MUST_NOT clause (document must not match).
    pub fn must_not(mut self, query: FtsQueryExpr) -> Self {
        self.must_not.push(query);
        self
    }

    /// Build the Boolean query.
    pub fn build(self) -> FtsQueryExpr {
        FtsQueryExpr::Boolean {
            must: self.must,
            should: self.should,
            must_not: self.must_not,
        }
    }
}

/// Posting value stored in the inverted index.
/// Contains term frequency and positions for phrase query support.
#[derive(Clone, Debug)]
pub struct PostingValue {
    /// Term frequency in the document.
    pub frequency: u32,
    /// Token positions within the document (0-indexed).
    /// Used for phrase matching.
    pub positions: Vec<u32>,
}

/// In-memory FTS index for full-text search.
pub struct FtsMemIndex {
    /// Field ID this index is built on.
    field_id: i32,
    /// Column name (for Arrow batch lookups).
    column_name: String,
    /// Inverted index: (token, row_position) -> (frequency, positions).
    postings: SkipMap<FtsKey, PostingValue>,
    /// Total document count.
    doc_count: AtomicUsize,
    /// Tokenizer for text processing (same as Lance's InvertedIndex).
    tokenizer: Mutex<Box<dyn LanceTokenizer>>,
    /// The parameters used to create the tokenizer (for flush).
    params: InvertedIndexParams,
    /// Document lengths: row_position -> token count (for BM25).
    doc_lengths: SkipMap<u64, u32>,
    /// Total token count across all documents (for computing avgdl).
    total_tokens: AtomicUsize,
    /// Document frequency: term -> number of documents containing the term.
    doc_freq: SkipMap<String, AtomicUsize>,
}

impl std::fmt::Debug for FtsMemIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FtsMemIndex")
            .field("field_id", &self.field_id)
            .field("column_name", &self.column_name)
            .field("doc_count", &self.doc_count)
            .field("params", &self.params)
            .finish()
    }
}

impl FtsMemIndex {
    /// Create a new FTS index for the given field with default parameters.
    pub fn new(field_id: i32, column_name: String) -> Self {
        Self::with_params(field_id, column_name, InvertedIndexParams::default())
    }

    /// Create a new FTS index with custom tokenizer parameters.
    pub fn with_params(field_id: i32, column_name: String, params: InvertedIndexParams) -> Self {
        let tokenizer = params.build().expect("Failed to build tokenizer");
        Self {
            field_id,
            column_name,
            postings: SkipMap::new(),
            doc_count: AtomicUsize::new(0),
            tokenizer: Mutex::new(tokenizer),
            params,
            doc_lengths: SkipMap::new(),
            total_tokens: AtomicUsize::new(0),
            doc_freq: SkipMap::new(),
        }
    }

    /// Get the field ID this index is built on.
    pub fn field_id(&self) -> i32 {
        self.field_id
    }

    /// Get the inverted index parameters.
    pub fn params(&self) -> &InvertedIndexParams {
        &self.params
    }

    /// Insert documents from a batch into the index.
    pub fn insert(&self, batch: &RecordBatch, row_offset: u64) -> Result<()> {
        let col_idx = batch
            .schema()
            .column_with_name(&self.column_name)
            .map(|(idx, _)| idx);

        if col_idx.is_none() {
            return Ok(());
        }

        let column = batch.column(col_idx.unwrap());

        for row_idx in 0..batch.num_rows() {
            let value = ScalarValue::try_from_array(column.as_ref(), row_idx)?;
            let row_position = row_offset + row_idx as u64;

            if let ScalarValue::Utf8(Some(text)) | ScalarValue::LargeUtf8(Some(text)) = value {
                // Use the tokenizer (same as InvertedIndex)
                // Track both frequency and positions for each term
                let mut term_data: HashMap<String, (u32, Vec<u32>)> = HashMap::new();
                {
                    let mut tokenizer = self.tokenizer.lock().unwrap();
                    let mut token_stream = tokenizer.token_stream_for_doc(&text);
                    let mut position: u32 = 0;
                    while let Some(token) = token_stream.next() {
                        let entry = term_data.entry(token.text.clone()).or_default();
                        entry.0 += 1; // frequency
                        entry.1.push(position); // position
                        position += 1;
                    }
                }

                // Calculate document length (total token count in this doc)
                let doc_length: u32 = term_data.values().map(|(freq, _)| freq).sum();
                self.doc_lengths.insert(row_position, doc_length);
                self.total_tokens
                    .fetch_add(doc_length as usize, Ordering::Relaxed);

                for (token, (freq, positions)) in term_data {
                    // Update document frequency for this term
                    if let Some(entry) = self.doc_freq.get(&token) {
                        entry.value().fetch_add(1, Ordering::Relaxed);
                    } else {
                        self.doc_freq.insert(token.clone(), AtomicUsize::new(1));
                    }

                    let key = FtsKey {
                        token,
                        row_position,
                    };
                    self.postings.insert(
                        key,
                        PostingValue {
                            frequency: freq,
                            positions,
                        },
                    );
                }
            }

            self.doc_count.fetch_add(1, Ordering::Relaxed);
        }

        Ok(())
    }

    /// Search for documents containing a term.
    ///
    /// The term is tokenized using the same tokenizer as the index.
    /// Returns all matching documents with their BM25 scores.
    pub fn search(&self, term: &str) -> Vec<FtsEntry> {
        // Tokenize the search term using token_stream_for_search
        let tokens: Vec<String> = {
            let mut tokenizer = self.tokenizer.lock().unwrap();
            let mut token_stream = tokenizer.token_stream_for_search(term);
            let mut tokens = Vec::new();
            while let Some(token) = token_stream.next() {
                tokens.push(token.text.clone());
            }
            tokens
        };

        // BM25 parameters
        const K1: f32 = 1.2;
        const B: f32 = 0.75;

        let n = self.doc_count.load(Ordering::Relaxed) as f32;
        let total_tokens = self.total_tokens.load(Ordering::Relaxed) as f32;
        let avgdl = if n > 0.0 { total_tokens / n } else { 1.0 };

        // Collect term frequencies per document for all query tokens
        // Map: row_position -> Vec<(term_freq, doc_freq_for_term)>
        let mut doc_term_info: HashMap<RowPosition, Vec<(u32, usize)>> = HashMap::new();

        for token in &tokens {
            // Get document frequency for this term
            let df = self
                .doc_freq
                .get(token)
                .map(|e| e.value().load(Ordering::Relaxed))
                .unwrap_or(0);

            if df == 0 {
                continue;
            }

            let start = FtsKey {
                token: token.clone(),
                row_position: 0,
            };
            let end = FtsKey {
                token: token.clone(),
                row_position: u64::MAX,
            };

            for entry in self.postings.range(start..=end) {
                doc_term_info
                    .entry(entry.key().row_position)
                    .or_default()
                    .push((entry.value().frequency, df));
            }
        }

        // Compute BM25 score for each document
        doc_term_info
            .into_iter()
            .map(|(row_position, term_infos)| {
                let dl = self
                    .doc_lengths
                    .get(&row_position)
                    .map(|e| *e.value() as f32)
                    .unwrap_or(1.0);

                let mut score: f32 = 0.0;
                for (tf, df) in term_infos {
                    // IDF = log((N - n + 0.5) / (n + 0.5) + 1)
                    let df_f = df as f32;
                    let idf = ((n - df_f + 0.5) / (df_f + 0.5) + 1.0).ln();

                    // BM25 term score = IDF * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (dl / avgdl)))
                    let tf_f = tf as f32;
                    let numerator = tf_f * (K1 + 1.0);
                    let denominator = tf_f + K1 * (1.0 - B + B * (dl / avgdl));
                    score += idf * (numerator / denominator);
                }

                FtsEntry {
                    row_position,
                    score,
                }
            })
            .collect()
    }

    /// Search for documents containing an exact phrase.
    ///
    /// The phrase is tokenized and documents must contain all tokens
    /// in the correct order (within the specified slop distance).
    ///
    /// # Arguments
    /// * `phrase` - The phrase to search for
    /// * `slop` - Maximum allowed distance between consecutive tokens.
    ///   0 means exact phrase match (tokens must be adjacent).
    ///   1 allows one intervening token, etc.
    ///
    /// Returns matching documents with BM25 scores.
    pub fn search_phrase(&self, phrase: &str, slop: u32) -> Vec<FtsEntry> {
        // Tokenize the phrase
        let tokens: Vec<String> = {
            let mut tokenizer = self.tokenizer.lock().unwrap();
            let mut token_stream = tokenizer.token_stream_for_search(phrase);
            let mut tokens = Vec::new();
            while let Some(token) = token_stream.next() {
                tokens.push(token.text.clone());
            }
            tokens
        };

        if tokens.is_empty() {
            return vec![];
        }

        // Single token phrase is just a regular search
        if tokens.len() == 1 {
            return self.search(phrase);
        }

        // BM25 parameters
        const K1: f32 = 1.2;
        const B: f32 = 0.75;

        let n = self.doc_count.load(Ordering::Relaxed) as f32;
        let total_tokens = self.total_tokens.load(Ordering::Relaxed) as f32;
        let avgdl = if n > 0.0 { total_tokens / n } else { 1.0 };

        // Collect posting lists for each token
        // Map: token_index -> Map<row_position, PostingValue>
        let mut token_postings: Vec<HashMap<RowPosition, PostingValue>> = Vec::new();

        for token in &tokens {
            let start = FtsKey {
                token: token.clone(),
                row_position: 0,
            };
            let end = FtsKey {
                token: token.clone(),
                row_position: u64::MAX,
            };

            let mut postings_for_token: HashMap<RowPosition, PostingValue> = HashMap::new();
            for entry in self.postings.range(start..=end) {
                postings_for_token.insert(entry.key().row_position, entry.value().clone());
            }
            token_postings.push(postings_for_token);
        }

        // Find documents that contain ALL tokens
        let first_token_docs: Vec<RowPosition> = token_postings[0].keys().copied().collect();

        let mut matching_docs: Vec<FtsEntry> = Vec::new();

        for row_position in first_token_docs {
            // Check if this document contains all tokens
            let all_tokens_present = token_postings
                .iter()
                .all(|tp| tp.contains_key(&row_position));
            if !all_tokens_present {
                continue;
            }

            // Check if the phrase matches (positions are in order within slop)
            if self.check_phrase_positions(&token_postings, row_position, slop) {
                // Calculate BM25 score
                let dl = self
                    .doc_lengths
                    .get(&row_position)
                    .map(|e| *e.value() as f32)
                    .unwrap_or(1.0);

                let mut score: f32 = 0.0;
                for (token_idx, token) in tokens.iter().enumerate() {
                    let df = self
                        .doc_freq
                        .get(token)
                        .map(|e| e.value().load(Ordering::Relaxed))
                        .unwrap_or(1) as f32;
                    let tf = token_postings[token_idx]
                        .get(&row_position)
                        .map(|p| p.frequency as f32)
                        .unwrap_or(1.0);

                    // IDF = log((N - n + 0.5) / (n + 0.5) + 1)
                    let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();

                    // BM25 term score
                    let numerator = tf * (K1 + 1.0);
                    let denominator = tf + K1 * (1.0 - B + B * (dl / avgdl));
                    score += idf * (numerator / denominator);
                }

                matching_docs.push(FtsEntry {
                    row_position,
                    score,
                });
            }
        }

        matching_docs
    }

    /// Check if phrase positions match within the given slop.
    ///
    /// Uses relative position algorithm: for each token, compute
    /// `relative_pos = doc_position - query_position`. If all tokens
    /// have the same relative position (within slop), the phrase matches.
    fn check_phrase_positions(
        &self,
        token_postings: &[HashMap<RowPosition, PostingValue>],
        row_position: RowPosition,
        slop: u32,
    ) -> bool {
        // Get positions for each token in this document
        let mut all_positions: Vec<&Vec<u32>> = Vec::new();
        for tp in token_postings {
            if let Some(posting) = tp.get(&row_position) {
                all_positions.push(&posting.positions);
            } else {
                return false;
            }
        }

        // For each position of the first token, check if we can form a phrase
        for &first_pos in all_positions[0] {
            if Self::check_phrase_from_position(&all_positions, first_pos, slop) {
                return true;
            }
        }

        false
    }

    /// Check if a phrase can be formed starting from a given position of the first token.
    fn check_phrase_from_position(all_positions: &[&Vec<u32>], first_pos: u32, slop: u32) -> bool {
        let mut expected_pos = first_pos;

        for positions in all_positions.iter().skip(1) {
            // Find a position for this token that's within slop of expected
            // For slop=0, next token must be at expected_pos+1 (adjacent)
            // For slop=1, next token can be at expected_pos+1 or expected_pos+2
            let min_pos = expected_pos.saturating_add(1);
            let max_pos = expected_pos.saturating_add(1 + slop);

            // Find the actual position used (smallest valid one)
            if let Some(&actual_pos) = positions
                .iter()
                .filter(|&&pos| pos >= min_pos && pos <= max_pos)
                .min()
            {
                expected_pos = actual_pos;
            } else {
                return false;
            }
        }

        true
    }

    /// Get the number of entries in the index.
    /// Note: This counts (token, row_position) pairs, not unique tokens.
    pub fn entry_count(&self) -> usize {
        self.postings.len()
    }

    /// Get the document count.
    pub fn doc_count(&self) -> usize {
        self.doc_count.load(Ordering::Relaxed)
    }

    /// Check if the index is empty.
    pub fn is_empty(&self) -> bool {
        self.doc_count.load(Ordering::Relaxed) == 0
    }

    /// Get the column name.
    pub fn column_name(&self) -> &str {
        &self.column_name
    }

    /// Expand a term to fuzzy matches within the specified edit distance.
    ///
    /// Returns a list of (matching_term, edit_distance) tuples, sorted by
    /// edit distance (closest matches first), limited to max_expansions.
    pub fn expand_fuzzy(
        &self,
        term: &str,
        max_distance: u32,
        max_expansions: usize,
    ) -> Vec<(String, u32)> {
        let mut matches: Vec<(String, u32)> = Vec::new();

        // If max_distance is 0, only exact matches
        if max_distance == 0 {
            if self.doc_freq.get(term).is_some() {
                matches.push((term.to_string(), 0));
            }
            return matches;
        }

        // Iterate through all tokens in doc_freq
        for entry in self.doc_freq.iter() {
            let indexed_term = entry.key();
            let distance = levenshtein_distance(term, indexed_term);

            if distance <= max_distance {
                matches.push((indexed_term.clone(), distance));
            }
        }

        // Sort by distance (prefer closer matches)
        matches.sort_by_key(|(_, d)| *d);

        // Limit to max_expansions
        matches.truncate(max_expansions);

        matches
    }

    /// Search for documents using fuzzy matching.
    ///
    /// Each query token is expanded to fuzzy matches within the edit distance,
    /// then searched. Results from all expansions are combined.
    pub fn search_fuzzy(
        &self,
        query: &str,
        fuzziness: Option<u32>,
        max_expansions: usize,
    ) -> Vec<FtsEntry> {
        // Tokenize the query
        let tokens: Vec<String> = {
            let mut tokenizer = self.tokenizer.lock().unwrap();
            let mut token_stream = tokenizer.token_stream_for_search(query);
            let mut tokens = Vec::new();
            while let Some(token) = token_stream.next() {
                tokens.push(token.text.clone());
            }
            tokens
        };

        if tokens.is_empty() {
            return vec![];
        }

        // BM25 parameters
        const K1: f32 = 1.2;
        const B: f32 = 0.75;

        let n = self.doc_count.load(Ordering::Relaxed) as f32;
        let total_tokens = self.total_tokens.load(Ordering::Relaxed) as f32;
        let avgdl = if n > 0.0 { total_tokens / n } else { 1.0 };

        // Collect term frequencies per document for all expanded tokens
        // Map: row_position -> Vec<(term_freq, doc_freq_for_term)>
        let mut doc_term_info: HashMap<RowPosition, Vec<(u32, usize)>> = HashMap::new();

        for token in &tokens {
            // Determine fuzziness for this token
            let max_distance = fuzziness.unwrap_or_else(|| auto_fuzziness(token));

            // Expand to fuzzy matches
            let expanded = self.expand_fuzzy(token, max_distance, max_expansions);

            for (matched_term, _distance) in expanded {
                // Get document frequency for this term
                let df = self
                    .doc_freq
                    .get(&matched_term)
                    .map(|e| e.value().load(Ordering::Relaxed))
                    .unwrap_or(0);

                if df == 0 {
                    continue;
                }

                let start = FtsKey {
                    token: matched_term.clone(),
                    row_position: 0,
                };
                let end = FtsKey {
                    token: matched_term,
                    row_position: u64::MAX,
                };

                for entry in self.postings.range(start..=end) {
                    doc_term_info
                        .entry(entry.key().row_position)
                        .or_default()
                        .push((entry.value().frequency, df));
                }
            }
        }

        // Compute BM25 score for each document
        doc_term_info
            .into_iter()
            .map(|(row_position, term_infos)| {
                let dl = self
                    .doc_lengths
                    .get(&row_position)
                    .map(|e| *e.value() as f32)
                    .unwrap_or(1.0);

                let mut score: f32 = 0.0;
                for (tf, df) in term_infos {
                    // IDF = log((N - n + 0.5) / (n + 0.5) + 1)
                    let df_f = df as f32;
                    let idf = ((n - df_f + 0.5) / (df_f + 0.5) + 1.0).ln();

                    // BM25 term score
                    let tf_f = tf as f32;
                    let numerator = tf_f * (K1 + 1.0);
                    let denominator = tf_f + K1 * (1.0 - B + B * (dl / avgdl));
                    score += idf * (numerator / denominator);
                }

                FtsEntry {
                    row_position,
                    score,
                }
            })
            .collect()
    }

    /// Execute a query expression and return matching documents with scores.
    ///
    /// This is the main entry point for executing complex queries including
    /// match, phrase, fuzzy, and Boolean queries.
    ///
    /// For performance optimization with limits, use `search_with_options()` instead.
    pub fn search_query(&self, query: &FtsQueryExpr) -> Vec<FtsEntry> {
        match query {
            FtsQueryExpr::Match { query, boost } => {
                let mut results = self.search(query);
                if *boost != 1.0 {
                    for entry in &mut results {
                        entry.score *= boost;
                    }
                }
                results
            }
            FtsQueryExpr::Phrase { query, slop, boost } => {
                let mut results = self.search_phrase(query, *slop);
                if *boost != 1.0 {
                    for entry in &mut results {
                        entry.score *= boost;
                    }
                }
                results
            }
            FtsQueryExpr::Fuzzy {
                query,
                fuzziness,
                max_expansions,
                boost,
            } => {
                let mut results = self.search_fuzzy(query, *fuzziness, *max_expansions);
                if *boost != 1.0 {
                    for entry in &mut results {
                        entry.score *= boost;
                    }
                }
                results
            }
            FtsQueryExpr::Boolean {
                must,
                should,
                must_not,
            } => self.search_boolean(must, should, must_not),
            FtsQueryExpr::Boost {
                positive,
                negative,
                negative_boost,
            } => self.search_boost(positive, negative.as_deref(), *negative_boost),
        }
    }

    /// Execute a query with options for performance/recall tradeoffs.
    ///
    /// This method extends `search_query()` with:
    /// - **WAND factor**: Early termination based on score threshold.
    ///   With `wand_factor < 1.0`, documents scoring below
    ///   `threshold = top_k_score * wand_factor` are pruned after scoring.
    /// - **Limit**: Maximum number of results to return (top-k by score).
    ///
    /// Results are always sorted by score in descending order.
    ///
    /// # Arguments
    /// * `query` - The query expression to execute
    /// * `options` - Search options including wand_factor and limit
    ///
    /// # Example
    /// ```ignore
    /// let options = SearchOptions::default()
    ///     .with_limit(10)
    ///     .with_wand_factor(0.8);
    /// let results = index.search_with_options(&query, options);
    /// ```
    pub fn search_with_options(
        &self,
        query: &FtsQueryExpr,
        options: SearchOptions,
    ) -> Vec<FtsEntry> {
        // Execute the query to get all results
        let mut results = self.search_query(query);

        // Sort by score descending
        results.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Apply WAND factor pruning if wand_factor < 1.0 and we have a limit
        if options.wand_factor < 1.0 {
            if let Some(limit) = options.limit {
                if results.len() > limit {
                    // Get the k-th best score (at position limit-1)
                    let top_k_score = results[limit - 1].score;
                    let threshold = top_k_score * options.wand_factor;

                    // Keep results scoring above the threshold, plus all results up to limit
                    // This ensures we don't accidentally prune results that would be in top-k
                    results.retain(|e| e.score >= threshold);
                }
            } else {
                // No limit but wand_factor < 1.0: prune relative to max score
                if let Some(max_entry) = results.first() {
                    let threshold = max_entry.score * options.wand_factor;
                    results.retain(|e| e.score >= threshold);
                }
            }
        }

        // Apply limit
        if let Some(limit) = options.limit {
            results.truncate(limit);
        }

        results
    }

    /// Execute a boosting query.
    ///
    /// Returns documents matching the positive query. Documents that also
    /// match the negative query have their scores multiplied by `negative_boost`.
    fn search_boost(
        &self,
        positive: &FtsQueryExpr,
        negative: Option<&FtsQueryExpr>,
        negative_boost: f32,
    ) -> Vec<FtsEntry> {
        // Execute positive query to get base results
        let mut results = self.search_query(positive);

        // If no negative query, just return positive results
        let Some(neg_query) = negative else {
            return results;
        };

        // Execute negative query
        let negative_results = self.search_query(neg_query);

        // Build a set of row positions that match the negative query
        let negative_positions: std::collections::HashSet<RowPosition> =
            negative_results.iter().map(|e| e.row_position).collect();

        // Apply negative boost to documents matching both queries
        for entry in &mut results {
            if negative_positions.contains(&entry.row_position) {
                entry.score *= negative_boost;
            }
        }

        results
    }

    /// Execute a Boolean query with MUST/SHOULD/MUST_NOT logic.
    ///
    /// - MUST: All clauses must match (intersection). Scores are summed.
    /// - SHOULD: At least one clause should match (union). Scores are added.
    /// - MUST_NOT: No clause may match (exclusion).
    ///
    /// If only SHOULD clauses are present, at least one must match.
    /// If MUST clauses are present, SHOULD clauses just add to the score.
    fn search_boolean(
        &self,
        must: &[FtsQueryExpr],
        should: &[FtsQueryExpr],
        must_not: &[FtsQueryExpr],
    ) -> Vec<FtsEntry> {
        // Collect MUST_NOT results for exclusion
        let excluded: std::collections::HashSet<RowPosition> = must_not
            .iter()
            .flat_map(|q| self.search_query(q))
            .map(|e| e.row_position)
            .collect();

        // Start with MUST clauses (intersection)
        let mut result_map: HashMap<RowPosition, f32> = if must.is_empty() {
            // No MUST clauses: start with all SHOULD results
            let mut map = HashMap::new();
            for q in should {
                for entry in self.search_query(q) {
                    *map.entry(entry.row_position).or_default() += entry.score;
                }
            }
            map
        } else {
            // Execute first MUST clause
            let first_results = self.search_query(&must[0]);
            let mut map: HashMap<RowPosition, f32> = first_results
                .into_iter()
                .map(|e| (e.row_position, e.score))
                .collect();

            // Intersect with remaining MUST clauses
            for q in must.iter().skip(1) {
                let results = self.search_query(q);
                let result_set: HashMap<RowPosition, f32> = results
                    .into_iter()
                    .map(|e| (e.row_position, e.score))
                    .collect();

                // Keep only documents in both sets, sum scores
                map = map
                    .into_iter()
                    .filter_map(|(pos, score)| result_set.get(&pos).map(|s| (pos, score + s)))
                    .collect();
            }

            // Add SHOULD clause scores (don't require match since MUST already filters)
            for q in should {
                for entry in self.search_query(q) {
                    if let Some(score) = map.get_mut(&entry.row_position) {
                        *score += entry.score;
                    }
                }
            }

            map
        };

        // Filter out MUST_NOT results
        for pos in &excluded {
            result_map.remove(pos);
        }

        // Convert to FtsEntry list
        result_map
            .into_iter()
            .map(|(row_position, score)| FtsEntry {
                row_position,
                score,
            })
            .collect()
    }

    /// Export the in-memory FTS index to an `InnerBuilder` for direct flush.
    ///
    /// This creates an `InnerBuilder` containing all the index data with
    /// reversed row positions for efficient LSM scan. The builder can then
    /// be written directly to disk without re-tokenizing the documents.
    ///
    /// # Arguments
    /// * `partition_id` - Partition ID for the index files
    /// * `total_rows` - Total number of rows in the MemTable (for position reversal)
    ///
    /// # Returns
    /// An `InnerBuilder` ready to be written to disk
    pub fn to_index_builder_reversed(
        &self,
        partition_id: u64,
        total_rows: usize,
    ) -> Result<lance_index::scalar::inverted::builder::InnerBuilder> {
        use lance_index::scalar::inverted::builder::{InnerBuilder, PositionRecorder};
        use lance_index::scalar::inverted::{DocSet, PostingListBuilder, TokenSet};

        if self.is_empty() {
            return Ok(InnerBuilder::new(
                partition_id,
                self.params.has_positions(),
                Default::default(),
            ));
        }

        let total_rows_u64 = total_rows as u64;
        let with_position = self.params.has_positions();

        // Step 1: Build DocSet with reversed row positions
        // Collect (original_pos, num_tokens) -> (reversed_pos, num_tokens)
        let mut doc_entries: Vec<(u64, u32)> = self
            .doc_lengths
            .iter()
            .map(|e| {
                let original_pos = *e.key();
                let reversed_pos = total_rows_u64 - original_pos - 1;
                (reversed_pos, *e.value())
            })
            .collect();

        // Sort by reversed position so doc_id assignment matches flushed data order
        doc_entries.sort_by_key(|(pos, _)| *pos);

        // Build DocSet and create mapping from reversed_pos -> doc_id
        let mut docs = DocSet::default();
        let mut reversed_pos_to_doc_id: HashMap<u64, u32> =
            HashMap::with_capacity(doc_entries.len());
        for (idx, (reversed_pos, num_tokens)) in doc_entries.into_iter().enumerate() {
            docs.append(reversed_pos, num_tokens);
            reversed_pos_to_doc_id.insert(reversed_pos, idx as u32);
        }

        // Step 2: Build TokenSet and group postings by token
        let mut tokens = TokenSet::default();
        let mut token_postings: HashMap<String, Vec<(u32, PostingValue)>> = HashMap::new();

        for entry in self.postings.iter() {
            let token = entry.key().token.clone();
            let original_pos = entry.key().row_position;
            let reversed_pos = total_rows_u64 - original_pos - 1;
            let doc_id = *reversed_pos_to_doc_id.get(&reversed_pos).ok_or_else(|| {
                Error::io(format!(
                    "FTS index internal error: doc_id not found for reversed position {} (original: {}, total_rows: {})",
                    reversed_pos, original_pos, total_rows
                ))
            })?;

            token_postings
                .entry(token)
                .or_default()
                .push((doc_id, entry.value().clone()));
        }

        // Assign token IDs in sorted order for FST format
        let mut sorted_tokens: Vec<_> = token_postings.keys().cloned().collect();
        sorted_tokens.sort();
        for token in &sorted_tokens {
            tokens.add(token.clone());
        }

        // Step 3: Build posting lists
        let mut posting_lists: Vec<PostingListBuilder> = (0..tokens.len())
            .map(|_| PostingListBuilder::new(with_position))
            .collect();

        for (token, mut postings) in token_postings {
            let token_id = tokens.get(&token).ok_or_else(|| {
                Error::io(format!(
                    "FTS index internal error: token '{}' not found in TokenSet",
                    token
                ))
            })? as usize;

            // Sort postings by doc_id for proper ordering
            postings.sort_by_key(|(doc_id, _)| *doc_id);

            for (doc_id, value) in postings {
                let position_recorder = if with_position {
                    PositionRecorder::Position(value.positions.into())
                } else {
                    PositionRecorder::Count(value.frequency)
                };
                posting_lists[token_id].add(doc_id, position_recorder);
            }
        }

        // Step 4: Create InnerBuilder with all the data
        let mut builder = InnerBuilder::new(partition_id, with_position, Default::default());
        builder.set_tokens(tokens);
        builder.set_docs(docs);
        builder.set_posting_lists(posting_lists);

        Ok(builder)
    }
}

/// Configuration for a Full-Text Search index.
#[derive(Debug, Clone)]
pub struct FtsIndexConfig {
    /// Index name.
    pub name: String,
    /// Field ID the index is built on.
    pub field_id: i32,
    /// Column name (for Arrow batch lookups).
    pub column: String,
    /// Tokenizer parameters (same as InvertedIndex).
    pub params: InvertedIndexParams,
}

impl FtsIndexConfig {
    /// Create a new FtsIndexConfig with default tokenizer parameters.
    pub fn new(name: String, field_id: i32, column: String) -> Self {
        Self {
            name,
            field_id,
            column,
            params: InvertedIndexParams::default(),
        }
    }

    /// Create a new FtsIndexConfig with custom tokenizer parameters.
    pub fn with_params(
        name: String,
        field_id: i32,
        column: String,
        params: InvertedIndexParams,
    ) -> Self {
        Self {
            name,
            field_id,
            column,
            params,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow_array::{Int32Array, StringArray};
    use arrow_schema::{DataType, Field, Schema as ArrowSchema};
    use std::sync::Arc;

    fn create_test_schema() -> Arc<ArrowSchema> {
        Arc::new(ArrowSchema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new("description", DataType::Utf8, true),
        ]))
    }

    fn create_test_batch(schema: &ArrowSchema) -> RecordBatch {
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2])),
                Arc::new(StringArray::from(vec![
                    "hello world",
                    "goodbye world",
                    "hello again",
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_fts_index_insert_and_search() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        assert_eq!(index.doc_count(), 3);

        // "hello" appears in docs 0 and 2
        let entries = index.search("hello");
        assert!(!entries.is_empty());
        assert_eq!(entries.len(), 2);

        // "world" appears in docs 0 and 1
        let entries = index.search("world");
        assert!(!entries.is_empty());
        assert_eq!(entries.len(), 2);

        // "goodbye" appears only in doc 1 (row position 1)
        let entries = index.search("goodbye");
        assert!(!entries.is_empty());
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].row_position, 1);

        // Non-existent term returns empty Vec
        let entries = index.search("nonexistent");
        assert!(entries.is_empty());
    }

    fn create_phrase_test_batch(schema: &ArrowSchema) -> RecordBatch {
        // Note: The tokenizer filters stop words (the, and, very, etc.) and lowercases.
        // Positions are assigned to non-filtered tokens only.
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
                Arc::new(StringArray::from(vec![
                    "alpha beta gamma",               // 0: alpha=0, beta=1, gamma=2
                    "beta alpha gamma",               // 1: beta=0, alpha=1, gamma=2
                    "alpha delta beta gamma",         // 2: alpha=0, delta=1, beta=2, gamma=3
                    "alpha gamma",                    // 3: alpha=0, gamma=1
                    "alpha delta epsilon beta gamma", // 4: alpha=0, delta=1, epsilon=2, beta=3, gamma=4
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_phrase_search_exact_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_phrase_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Exact phrase "alpha beta" with slop=0 should match only doc 0
        // Doc 0: "alpha beta gamma" - alpha=0, beta=1 (adjacent)
        // Doc 2: "alpha delta beta gamma" - alpha=0, beta=2 (NOT adjacent, slop needed)
        let entries = index.search_phrase("alpha beta", 0);
        assert_eq!(
            entries.len(),
            1,
            "Expected 1 match for 'alpha beta', got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
        assert_eq!(entries[0].row_position, 0);

        // "hello world" exact phrase
        let batch2 = create_test_batch(&schema);
        let index2 = FtsMemIndex::new(1, "description".to_string());
        index2.insert(&batch2, 0).unwrap();

        let entries = index2.search_phrase("hello world", 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].row_position, 0);

        // "goodbye world" exact phrase
        let entries = index2.search_phrase("goodbye world", 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].row_position, 1);
    }

    #[test]
    fn test_phrase_search_with_slop() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_phrase_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Positions after tokenization (no stop words filtered):
        // Doc 0: "alpha beta gamma" - alpha=0, beta=1, gamma=2
        // Doc 2: "alpha delta beta gamma" - alpha=0, delta=1, beta=2, gamma=3
        // Doc 4: "alpha delta epsilon beta gamma" - alpha=0, delta=1, epsilon=2, beta=3, gamma=4

        // "alpha beta" with slop=0 should match only doc 0
        // Doc 0: alpha=0, beta=1 (adjacent)
        let entries = index.search_phrase("alpha beta", 0);
        assert_eq!(
            entries.len(),
            1,
            "slop=0 matches: {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
        assert_eq!(entries[0].row_position, 0);

        // "alpha beta" with slop=1 should match docs 0 and 2
        // Doc 0: alpha=0, beta=1 (diff=1, within slop=1)
        // Doc 2: alpha=0, beta=2 (diff=2, slop=1 allows pos 1-2)
        // Doc 4: alpha=0, beta=3 (diff=3, slop=1 does NOT allow pos 3)
        let entries = index.search_phrase("alpha beta", 1);
        assert_eq!(
            entries.len(),
            2,
            "slop=1 matches: {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(positions.contains(&0));
        assert!(positions.contains(&2));

        // "alpha beta" with slop=2 should match docs 0, 2, and 4
        let entries = index.search_phrase("alpha beta", 2);
        assert_eq!(
            entries.len(),
            3,
            "slop=2 matches: {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        // "alpha gamma" with slop=0 should match docs 1 and 3 (adjacent)
        // Doc 1: "beta alpha gamma" - alpha=1, gamma=2 (adjacent)
        // Doc 3: "alpha gamma" - alpha=0, gamma=1 (adjacent)
        let entries = index.search_phrase("alpha gamma", 0);
        assert_eq!(
            entries.len(),
            2,
            "alpha gamma slop=0: {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        // "alpha gamma" with slop=1 should match docs 0, 1, 2, and 3
        // Doc 0: alpha=0, gamma=2 (diff=2, slop=1 allows pos 1-2)
        // Doc 1: alpha=1, gamma=2 (adjacent)
        // Doc 2: alpha=0, gamma=3 (diff=3, slop=1 allows pos 1-2, gamma at 3 NOT in range)
        // Doc 3: alpha=0, gamma=1 (adjacent)
        let entries = index.search_phrase("alpha gamma", 1);
        assert_eq!(
            entries.len(),
            3,
            "alpha gamma slop=1: {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_phrase_search_no_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_phrase_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // "beta alpha" with slop=0 should not match in most docs (wrong order)
        // Doc 1 has "beta alpha gamma" - beta=0, alpha=1, so "beta alpha" matches there!
        let entries = index.search_phrase("beta alpha", 0);
        assert_eq!(entries.len(), 1); // matches doc 1
        assert_eq!(entries[0].row_position, 1);

        // Non-existent phrase
        let entries = index.search_phrase("nonexistent phrase", 0);
        assert!(entries.is_empty());

        // Partial phrase not in any doc
        let entries = index.search_phrase("alpha hello", 0);
        assert!(entries.is_empty());

        // "gamma alpha" should not match (wrong order in all docs)
        let entries = index.search_phrase("gamma alpha", 0);
        assert!(entries.is_empty());
    }

    #[test]
    fn test_phrase_search_single_token() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_phrase_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Single token phrase should behave like regular search
        let phrase_entries = index.search_phrase("alpha", 0);
        let search_entries = index.search("alpha");

        assert_eq!(phrase_entries.len(), search_entries.len());
    }

    #[test]
    fn test_phrase_search_empty() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Empty phrase
        let entries = index.search_phrase("", 0);
        assert!(entries.is_empty());
    }

    // ====== Boolean Query Tests ======

    fn create_boolean_test_batch(schema: &ArrowSchema) -> RecordBatch {
        // Test documents for Boolean queries:
        // Doc 0: "rust programming language"
        // Doc 1: "python programming language"
        // Doc 2: "rust web server"
        // Doc 3: "python web framework"
        // Doc 4: "javascript programming"
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
                Arc::new(StringArray::from(vec![
                    "rust programming language",
                    "python programming language",
                    "rust web server",
                    "python web framework",
                    "javascript programming",
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_boolean_must_only() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: rust AND programming
        // Should match doc 0 only ("rust programming language")
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::match_query("rust"))
            .must(FtsQueryExpr::match_query("programming"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            1,
            "Expected 1 match for MUST(rust, programming), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
        assert_eq!(entries[0].row_position, 0);
    }

    #[test]
    fn test_boolean_should_only() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // SHOULD: rust OR python
        // Should match docs 0, 1, 2, 3 (all containing rust or python)
        let query = FtsQueryExpr::boolean()
            .should(FtsQueryExpr::match_query("rust"))
            .should(FtsQueryExpr::match_query("python"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            4,
            "Expected 4 matches for SHOULD(rust, python), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(positions.contains(&0));
        assert!(positions.contains(&1));
        assert!(positions.contains(&2));
        assert!(positions.contains(&3));
    }

    #[test]
    fn test_boolean_must_not_only() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST_NOT alone with no MUST or SHOULD returns empty
        // (nothing to include, only exclusions)
        let query = FtsQueryExpr::boolean()
            .must_not(FtsQueryExpr::match_query("rust"))
            .build();

        let entries = index.search_query(&query);
        assert!(
            entries.is_empty(),
            "MUST_NOT only should return empty, got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_boolean_must_with_should() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: programming, SHOULD: rust
        // Should match docs 0, 1, 4 (all with programming)
        // Doc 0 should have higher score (also matches rust)
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::match_query("programming"))
            .should(FtsQueryExpr::match_query("rust"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            3,
            "Expected 3 matches for MUST(programming) SHOULD(rust), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        // Find doc 0 and doc 1 scores
        let doc0 = entries.iter().find(|e| e.row_position == 0).unwrap();
        let doc1 = entries.iter().find(|e| e.row_position == 1).unwrap();

        // Doc 0 has both programming and rust, should score higher than doc 1 (only programming)
        assert!(
            doc0.score > doc1.score,
            "Doc 0 (rust+programming) should score higher than doc 1 (programming only). Doc0: {}, Doc1: {}",
            doc0.score,
            doc1.score
        );
    }

    #[test]
    fn test_boolean_must_with_must_not() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: programming, MUST_NOT: python
        // Should match docs 0 and 4 (programming but not python)
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::match_query("programming"))
            .must_not(FtsQueryExpr::match_query("python"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            2,
            "Expected 2 matches for MUST(programming) MUST_NOT(python), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(positions.contains(&0)); // rust programming language
        assert!(positions.contains(&4)); // javascript programming
        assert!(!positions.contains(&1)); // python programming language - excluded
    }

    #[test]
    fn test_boolean_combined() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: web, SHOULD: rust, MUST_NOT: framework
        // Docs with "web": 2 (rust web server), 3 (python web framework)
        // After MUST_NOT framework: only doc 2
        // Doc 2 also matches SHOULD(rust), so should have higher score
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::match_query("web"))
            .should(FtsQueryExpr::match_query("rust"))
            .must_not(FtsQueryExpr::match_query("framework"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            1,
            "Expected 1 match for MUST(web) SHOULD(rust) MUST_NOT(framework), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
        assert_eq!(entries[0].row_position, 2);
    }

    #[test]
    fn test_boolean_nested_phrase() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boolean_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: phrase("programming language")
        // Should match docs 0 and 1
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::phrase("programming language"))
            .build();

        let entries = index.search_query(&query);
        assert_eq!(
            entries.len(),
            2,
            "Expected 2 matches for MUST(phrase 'programming language'), got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );

        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(positions.contains(&0));
        assert!(positions.contains(&1));
    }

    #[test]
    fn test_search_query_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Test FtsQueryExpr::Match
        let query = FtsQueryExpr::match_query("hello");
        let entries = index.search_query(&query);
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn test_search_query_phrase() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Test FtsQueryExpr::Phrase
        let query = FtsQueryExpr::phrase("hello world");
        let entries = index.search_query(&query);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].row_position, 0);
    }

    #[test]
    fn test_search_query_with_boost() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Test boost
        let query_no_boost = FtsQueryExpr::match_query("hello");
        let query_with_boost = FtsQueryExpr::match_query("hello").with_boost(2.0);

        let entries_no_boost = index.search_query(&query_no_boost);
        let entries_with_boost = index.search_query(&query_with_boost);

        assert_eq!(entries_no_boost.len(), entries_with_boost.len());

        // Boosted scores should be 2x
        for (e1, e2) in entries_no_boost.iter().zip(entries_with_boost.iter()) {
            let expected = e1.score * 2.0;
            assert!(
                (e2.score - expected).abs() < 0.001,
                "Boosted score {} should be 2x original {}",
                e2.score,
                e1.score
            );
        }
    }

    // ====== Fuzzy Matching Tests ======

    #[test]
    fn test_levenshtein_distance() {
        // Identical strings
        assert_eq!(levenshtein_distance("hello", "hello"), 0);

        // Single character difference
        assert_eq!(levenshtein_distance("hello", "hallo"), 1); // substitution
        assert_eq!(levenshtein_distance("hello", "hell"), 1); // deletion
        assert_eq!(levenshtein_distance("hello", "helloo"), 1); // insertion

        // Two character differences
        assert_eq!(levenshtein_distance("hello", "hxllo"), 1);
        assert_eq!(levenshtein_distance("hello", "hxxlo"), 2);

        // Completely different strings
        assert_eq!(levenshtein_distance("abc", "xyz"), 3);

        // Empty strings
        assert_eq!(levenshtein_distance("", ""), 0);
        assert_eq!(levenshtein_distance("hello", ""), 5);
        assert_eq!(levenshtein_distance("", "hello"), 5);

        // Case sensitivity
        assert_eq!(levenshtein_distance("Hello", "hello"), 1);
    }

    #[test]
    fn test_auto_fuzziness() {
        // 0-2 chars: 0 fuzziness
        assert_eq!(auto_fuzziness(""), 0);
        assert_eq!(auto_fuzziness("a"), 0);
        assert_eq!(auto_fuzziness("ab"), 0);

        // 3-5 chars: 1 fuzziness
        assert_eq!(auto_fuzziness("abc"), 1);
        assert_eq!(auto_fuzziness("abcd"), 1);
        assert_eq!(auto_fuzziness("abcde"), 1);

        // 6+ chars: 2 fuzziness
        assert_eq!(auto_fuzziness("abcdef"), 2);
        assert_eq!(auto_fuzziness("programming"), 2);
    }

    fn create_fuzzy_test_batch(schema: &ArrowSchema) -> RecordBatch {
        // Test documents for fuzzy matching.
        // Note: The tokenizer stems words, so we use unstemmed single tokens
        // for predictable fuzzy matching tests.
        // Levenshtein distance examples:
        // - "alpha" to "alpho" = 1 (substitution: a -> o)
        // - "alpha" to "alphax" = 1 (insertion)
        // - "alpha" to "alph" = 1 (deletion)
        // Doc 0: "alpha beta gamma"
        // Doc 1: "alpho beta delta" (typo: 'alpho' instead of 'alpha', distance=1)
        // Doc 2: "alpha delta epsilon"
        // Doc 3: "omega zeta"
        // Doc 4: "alphax gamma" (typo: extra 'x', distance=1)
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
                Arc::new(StringArray::from(vec![
                    "alpha beta gamma",
                    "alpho beta delta",
                    "alpha delta epsilon",
                    "omega zeta",
                    "alphax gamma",
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_expand_fuzzy_exact_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Exact match with fuzziness=0: "alpha" exists in index
        let matches = index.expand_fuzzy("alpha", 0, 50);
        assert_eq!(
            matches.len(),
            1,
            "Expected 1 match for 'alpha', got {:?}",
            matches
        );
        assert_eq!(matches[0].0, "alpha");
        assert_eq!(matches[0].1, 0);

        // Non-existent term with fuzziness=0
        let matches = index.expand_fuzzy("nonexistent", 0, 50);
        assert!(matches.is_empty());
    }

    #[test]
    fn test_expand_fuzzy_single_edit() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // "alpho" (typo, substitution distance=1 from "alpha") should match "alpha"
        let matches = index.expand_fuzzy("alpho", 1, 50);
        assert!(
            matches
                .iter()
                .any(|(term, dist)| term == "alpha" && *dist == 1),
            "Expected 'alpha' with distance 1, got {:?}",
            matches
        );

        // Also matches itself since it's in the index
        assert!(
            matches.iter().any(|(term, _)| term == "alpho"),
            "Expected 'alpho' in matches, got {:?}",
            matches
        );
    }

    #[test]
    fn test_expand_fuzzy_max_expansions() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // With very high distance, should be limited by max_expansions
        let matches = index.expand_fuzzy("a", 10, 3);
        assert!(
            matches.len() <= 3,
            "Expected at most 3 matches, got {}",
            matches.len()
        );
    }

    #[test]
    fn test_search_fuzzy_basic() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Search with typo "alpho" should match documents with "alpha" or "alpho"
        let entries = index.search_fuzzy("alpho", Some(1), 50);
        assert!(!entries.is_empty(), "Expected matches for fuzzy 'alpho'");

        // Should match docs with alpha (0, 2) and alpho (1)
        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(
            positions.contains(&0) || positions.contains(&1) || positions.contains(&2),
            "Expected to match docs with alpha/alpho, got {:?}",
            positions
        );
    }

    #[test]
    fn test_search_fuzzy_auto_fuzziness() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // "alpho" (5 chars) should get auto-fuzziness of 1
        let entries = index.search_fuzzy("alpho", None, 50);
        assert!(!entries.is_empty(), "Expected matches with auto-fuzziness");
    }

    #[test]
    fn test_search_fuzzy_no_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Search for something completely different with low fuzziness
        let entries = index.search_fuzzy("xyz", Some(0), 50);
        assert!(entries.is_empty(), "Expected no matches for 'xyz'");

        // Even with fuzziness=1, "xyz" shouldn't match anything meaningful
        // (this may or may not be empty depending on what 3-letter words are in the index)
        let _ = index.search_fuzzy("xyz", Some(1), 50);
    }

    #[test]
    fn test_search_query_fuzzy() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Test FtsQueryExpr::Fuzzy via search_query
        let query = FtsQueryExpr::fuzzy("alpho");
        let entries = index.search_query(&query);
        assert!(
            !entries.is_empty(),
            "Expected matches for fuzzy query 'alpho'"
        );
    }

    #[test]
    fn test_search_query_fuzzy_with_distance() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Exact distance: "alpho" has distance 1 from "alpha"
        let query = FtsQueryExpr::fuzzy_with_distance("alpho", 1);
        let entries = index.search_query(&query);
        assert!(
            !entries.is_empty(),
            "Expected matches for fuzzy query with distance 1"
        );
    }

    #[test]
    fn test_search_query_fuzzy_with_boost() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        let query_no_boost = FtsQueryExpr::fuzzy("alpho");
        let query_with_boost = FtsQueryExpr::fuzzy("alpho").with_boost(2.0);

        let entries_no_boost = index.search_query(&query_no_boost);
        let entries_with_boost = index.search_query(&query_with_boost);

        assert_eq!(entries_no_boost.len(), entries_with_boost.len());

        // Boosted scores should be 2x
        for e1 in &entries_no_boost {
            let e2 = entries_with_boost
                .iter()
                .find(|e| e.row_position == e1.row_position)
                .unwrap();
            let expected = e1.score * 2.0;
            assert!(
                (e2.score - expected).abs() < 0.001,
                "Boosted score {} should be 2x original {}",
                e2.score,
                e1.score
            );
        }
    }

    #[test]
    fn test_boolean_with_fuzzy() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_fuzzy_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // MUST: fuzzy("alpho", distance=1), MUST_NOT: "delta"
        // "alpho" matches "alpha" (distance=1) and itself
        // Doc 0: "alpha beta gamma" - matches fuzzy alpho, no delta -> included
        // Doc 1: "alpho beta delta" - matches fuzzy alpho, has delta -> excluded
        // Doc 2: "alpha delta epsilon" - matches fuzzy alpho, has delta -> excluded
        // Doc 4: "alphax gamma" - matches fuzzy alpho via alphax (dist=1 to alpho), no delta -> included
        let query = FtsQueryExpr::boolean()
            .must(FtsQueryExpr::fuzzy_with_distance("alpho", 1))
            .must_not(FtsQueryExpr::match_query("delta"))
            .build();

        let entries = index.search_query(&query);

        // Should not contain docs 1 and 2 (have "delta")
        let positions: Vec<_> = entries.iter().map(|e| e.row_position).collect();
        assert!(
            !positions.contains(&1),
            "Doc 1 should be excluded due to MUST_NOT, got {:?}",
            positions
        );
        assert!(
            !positions.contains(&2),
            "Doc 2 should be excluded due to MUST_NOT, got {:?}",
            positions
        );
        // Doc 0 should be included
        assert!(
            positions.contains(&0),
            "Doc 0 should be included, got {:?}",
            positions
        );
    }

    // ====== Boost Query Tests ======

    fn create_boost_test_batch(schema: &ArrowSchema) -> RecordBatch {
        // Test documents for boost queries:
        // Doc 0: "rust programming language" - matches rust, programming, language
        // Doc 1: "python programming language" - matches python, programming, language
        // Doc 2: "rust web server" - matches rust, web, server
        // Doc 3: "python web framework" - matches python, web, framework
        // Doc 4: "javascript programming" - matches javascript, programming
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
                Arc::new(StringArray::from(vec![
                    "rust programming language",
                    "python programming language",
                    "rust web server",
                    "python web framework",
                    "javascript programming",
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_boost_query_positive_only() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boost_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Boosting query with only positive component (same as regular query)
        let query = FtsQueryExpr::boosting(FtsQueryExpr::match_query("programming"));
        let entries = index.search_query(&query);

        // Should match docs 0, 1, 4 (all with "programming")
        assert_eq!(
            entries.len(),
            3,
            "Expected 3 matches for 'programming', got {:?}",
            entries.iter().map(|e| e.row_position).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_boost_query_with_negative() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boost_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Boosting query: find "programming", demote docs with "python"
        let query = FtsQueryExpr::boosting_with_negative(
            FtsQueryExpr::match_query("programming"),
            FtsQueryExpr::match_query("python"),
            0.5, // Demote python docs by half
        );
        let entries = index.search_query(&query);

        // Should still match docs 0, 1, 4 (all with "programming")
        assert_eq!(entries.len(), 3);

        // Find scores for each doc
        let doc0 = entries.iter().find(|e| e.row_position == 0); // rust programming
        let doc1 = entries.iter().find(|e| e.row_position == 1); // python programming
        let doc4 = entries.iter().find(|e| e.row_position == 4); // javascript programming

        assert!(doc0.is_some() && doc1.is_some() && doc4.is_some());

        // Doc 1 (python) should have lower score than doc 0 (rust) due to negative boost
        // Doc 0 and doc 4 should have similar scores (neither match "python")
        let score0 = doc0.unwrap().score;
        let score1 = doc1.unwrap().score;
        let score4 = doc4.unwrap().score;

        // Doc 1 was demoted by 0.5, so it should have roughly half the score
        assert!(
            score1 < score0,
            "Doc 1 (python) should have lower score than doc 0 (rust). Doc0: {}, Doc1: {}",
            score0,
            score1
        );

        // Doc 0 and doc 4 should have similar scores (both not demoted)
        // They may differ slightly due to BM25 scoring differences, but doc 1 should be lower
        assert!(
            score1 < score4,
            "Doc 1 (python) should have lower score than doc 4 (javascript). Doc1: {}, Doc4: {}",
            score1,
            score4
        );
    }

    #[test]
    fn test_boost_query_negative_boost_factor() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boost_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Compare different negative boost factors
        let query_no_demote = FtsQueryExpr::boosting_with_negative(
            FtsQueryExpr::match_query("programming"),
            FtsQueryExpr::match_query("python"),
            1.0, // No demotion
        );

        let query_half_demote = FtsQueryExpr::boosting_with_negative(
            FtsQueryExpr::match_query("programming"),
            FtsQueryExpr::match_query("python"),
            0.5, // Half score for python
        );

        let query_zero_demote = FtsQueryExpr::boosting_with_negative(
            FtsQueryExpr::match_query("programming"),
            FtsQueryExpr::match_query("python"),
            0.0, // Zero score for python
        );

        let results_no_demote = index.search_query(&query_no_demote);
        let results_half_demote = index.search_query(&query_half_demote);
        let results_zero_demote = index.search_query(&query_zero_demote);

        // Get doc 1 (python programming) scores
        let score_no_demote = results_no_demote
            .iter()
            .find(|e| e.row_position == 1)
            .unwrap()
            .score;
        let score_half_demote = results_half_demote
            .iter()
            .find(|e| e.row_position == 1)
            .unwrap()
            .score;
        let score_zero_demote = results_zero_demote
            .iter()
            .find(|e| e.row_position == 1)
            .unwrap()
            .score;

        // Verify demotion factors are applied correctly
        assert!(
            (score_half_demote - score_no_demote * 0.5).abs() < 0.001,
            "Half demotion should give half score. Expected {}, got {}",
            score_no_demote * 0.5,
            score_half_demote
        );

        assert!(
            score_zero_demote.abs() < 0.001,
            "Zero demotion should give zero score, got {}",
            score_zero_demote
        );
    }

    #[test]
    fn test_boost_query_no_negative_match() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boost_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Boosting query where negative doesn't match any positive results
        let query = FtsQueryExpr::boosting_with_negative(
            FtsQueryExpr::match_query("rust"),   // Matches docs 0, 2
            FtsQueryExpr::match_query("python"), // Matches docs 1, 3 (no overlap!)
            0.1,
        );

        let entries = index.search_query(&query);

        // Should match docs 0, 2 (rust docs)
        assert_eq!(entries.len(), 2);

        // Scores should not be demoted (no overlap with python)
        let query_baseline = FtsQueryExpr::match_query("rust");
        let baseline_entries = index.search_query(&query_baseline);

        for entry in &entries {
            let baseline = baseline_entries
                .iter()
                .find(|e| e.row_position == entry.row_position)
                .unwrap();
            assert!(
                (entry.score - baseline.score).abs() < 0.001,
                "Scores should match when no negative overlap. Got {} vs {}",
                entry.score,
                baseline.score
            );
        }
    }

    #[test]
    fn test_boost_query_nested() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_boost_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Nested boost: positive is a Boolean query
        let positive_query = FtsQueryExpr::boolean()
            .should(FtsQueryExpr::match_query("programming"))
            .should(FtsQueryExpr::match_query("web"))
            .build();

        let query = FtsQueryExpr::boosting_with_negative(
            positive_query,
            FtsQueryExpr::match_query("python"),
            0.5,
        );

        let entries = index.search_query(&query);

        // Should match docs 0, 1, 2, 3, 4 (programming or web)
        assert!(entries.len() >= 4, "Should match multiple docs");

        // Python docs (1, 3) should be demoted
        let python_docs: Vec<_> = entries
            .iter()
            .filter(|e| e.row_position == 1 || e.row_position == 3)
            .collect();

        let non_python_docs: Vec<_> = entries
            .iter()
            .filter(|e| e.row_position != 1 && e.row_position != 3)
            .collect();

        // At least some python docs should have lower scores
        if !python_docs.is_empty() && !non_python_docs.is_empty() {
            let max_python_score = python_docs.iter().map(|e| e.score).fold(0.0f32, f32::max);
            let max_non_python_score = non_python_docs
                .iter()
                .map(|e| e.score)
                .fold(0.0f32, f32::max);

            // This is a soft check - depends on BM25 scoring details
            // Just verify the demotion is happening
            assert!(
                python_docs.iter().any(|e| e.score < max_non_python_score)
                    || max_python_score <= max_non_python_score,
                "Python docs should generally have lower scores"
            );
        }
    }

    // ====== WAND Factor / Search Options Tests ======

    #[test]
    fn test_search_options_default() {
        let options = SearchOptions::default();
        assert_eq!(options.wand_factor, 1.0);
        assert!(options.limit.is_none());
    }

    #[test]
    fn test_search_options_builder() {
        let options = SearchOptions::new().with_wand_factor(0.5).with_limit(10);

        assert_eq!(options.wand_factor, 0.5);
        assert_eq!(options.limit, Some(10));
    }

    #[test]
    fn test_search_options_wand_factor_clamped() {
        // wand_factor should be clamped to [0.0, 1.0]
        let options = SearchOptions::new().with_wand_factor(2.0);
        assert_eq!(options.wand_factor, 1.0);

        let options = SearchOptions::new().with_wand_factor(-0.5);
        assert_eq!(options.wand_factor, 0.0);
    }

    fn create_wand_test_batch(schema: &ArrowSchema) -> RecordBatch {
        // Test documents with varying relevance:
        // Doc 0: "alpha alpha alpha beta" - high relevance for "alpha" (3 occurrences)
        // Doc 1: "alpha beta gamma" - medium relevance for "alpha" (1 occurrence)
        // Doc 2: "beta gamma delta" - no relevance for "alpha"
        // Doc 3: "alpha alpha" - medium-high relevance for "alpha" (2 occurrences, shorter doc)
        // Doc 4: "alpha" - some relevance for "alpha" (1 occurrence, very short doc)
        RecordBatch::try_new(
            Arc::new(schema.clone()),
            vec![
                Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
                Arc::new(StringArray::from(vec![
                    "alpha alpha alpha beta",
                    "alpha beta gamma",
                    "beta gamma delta",
                    "alpha alpha",
                    "alpha",
                ])),
            ],
        )
        .unwrap()
    }

    #[test]
    fn test_search_with_options_full_recall() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        let query = FtsQueryExpr::match_query("alpha");

        // Full recall (wand_factor = 1.0)
        let options = SearchOptions::default();
        let results = index.search_with_options(&query, options);

        // Should return all docs containing "alpha" (docs 0, 1, 3, 4)
        assert_eq!(results.len(), 4, "Expected 4 matches with full recall");

        // Results should be sorted by score descending
        for i in 1..results.len() {
            assert!(
                results[i - 1].score >= results[i].score,
                "Results should be sorted by score descending"
            );
        }
    }

    #[test]
    fn test_search_with_options_with_limit() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        let query = FtsQueryExpr::match_query("alpha");

        // Limit to top 2 results
        let options = SearchOptions::new().with_limit(2);
        let results = index.search_with_options(&query, options);

        assert_eq!(results.len(), 2, "Expected 2 matches with limit=2");

        // Should be the top 2 by score
        let full_results = index.search_query(&query);
        let mut full_sorted = full_results;
        full_sorted.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());

        assert_eq!(
            results[0].row_position, full_sorted[0].row_position,
            "First result should be highest scorer"
        );
        assert_eq!(
            results[1].row_position, full_sorted[1].row_position,
            "Second result should be second highest scorer"
        );
    }

    #[test]
    fn test_search_with_options_wand_factor_pruning() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        let query = FtsQueryExpr::match_query("alpha");

        // Get full results first to understand the score distribution
        let full_results = index.search_query(&query);
        let mut full_sorted = full_results.clone();
        full_sorted.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());

        // With wand_factor = 0.0, should only keep results at or above threshold (max_score * 0.0 = 0)
        // Actually with wand_factor = 0.0, threshold = max_score * 0.0 = 0, so all positive scores pass
        // The real test is to use a higher wand_factor like 0.5
        let options = SearchOptions::new().with_wand_factor(0.5);
        let results = index.search_with_options(&query, options);

        // Results should be pruned based on threshold
        if !results.is_empty() {
            let max_score = full_sorted[0].score;
            let threshold = max_score * 0.5;

            for result in &results {
                assert!(
                    result.score >= threshold - 0.001, // small epsilon for float comparison
                    "With wand_factor=0.5, all results should score >= {} but got {}",
                    threshold,
                    result.score
                );
            }

            // Should have fewer or equal results compared to full results
            assert!(
                results.len() <= full_results.len(),
                "Pruned results should not exceed full results"
            );
        }
    }

    #[test]
    fn test_search_with_options_wand_factor_with_limit() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        let query = FtsQueryExpr::match_query("alpha");

        // Get full results to understand score distribution
        let full_results = index.search_query(&query);
        assert!(
            full_results.len() >= 3,
            "Need at least 3 results for this test"
        );

        // With limit=2 and wand_factor=0.5, prune docs scoring below 50% of 2nd best
        let options = SearchOptions::new().with_limit(2).with_wand_factor(0.5);
        let results = index.search_with_options(&query, options);

        // Should have at most 2 results (the limit)
        assert!(results.len() <= 2, "Should not exceed limit");

        // Results should be sorted by score
        if results.len() > 1 {
            assert!(results[0].score >= results[1].score);
        }
    }

    #[test]
    fn test_search_with_options_empty_results() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Query for something that doesn't exist
        let query = FtsQueryExpr::match_query("nonexistent");
        let options = SearchOptions::new().with_limit(10).with_wand_factor(0.5);
        let results = index.search_with_options(&query, options);

        assert!(
            results.is_empty(),
            "Should return empty for non-matching query"
        );
    }

    #[test]
    fn test_search_with_options_boolean_query() {
        let schema = create_test_schema();
        let index = FtsMemIndex::new(1, "description".to_string());

        let batch = create_wand_test_batch(&schema);
        index.insert(&batch, 0).unwrap();

        // Boolean query: alpha SHOULD beta
        let query = FtsQueryExpr::boolean()
            .should(FtsQueryExpr::match_query("alpha"))
            .should(FtsQueryExpr::match_query("beta"))
            .build();

        let options = SearchOptions::new().with_limit(3);
        let results = index.search_with_options(&query, options);

        assert!(results.len() <= 3, "Should not exceed limit");
        // Results should be sorted by score descending
        for i in 1..results.len() {
            assert!(results[i - 1].score >= results[i].score);
        }
    }
}