ld-lucivy 0.26.1

BM25 search engine with cross-token fuzzy matching, substring search, regex, and highlights
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
//! Fastfields support efficient scanning for range queries.
//! We use this variant only if the fastfield exists, otherwise the default in `range_query` is
//! used, which uses the term dictionary + postings.

use std::net::Ipv6Addr;
use std::ops::{Bound, RangeInclusive};

use columnar::{
    Cardinality, Column, ColumnType, MonotonicallyMappableToU128, MonotonicallyMappableToU64,
    NumericalType, StrColumn,
};
use common::bounds::{BoundsRange, TransformBound};

use super::fast_field_range_doc_set::RangeDocSet;
use crate::query::{
    AllScorer, ConstScorer, EmptyScorer, EnableScoring, Explanation, Query, Scorer, Weight,
};
use crate::schema::{Type, ValueBytes};
use crate::{DocId, DocSet, Score, SegmentReader, LucivyError, Term};

#[derive(Clone, Debug)]
/// `FastFieldRangeQuery` is the same as [RangeQuery] but only uses the fast field
pub struct FastFieldRangeQuery {
    bounds: BoundsRange<Term>,
}
impl FastFieldRangeQuery {
    /// Create new `FastFieldRangeQuery`
    pub fn new(lower_bound: Bound<Term>, upper_bound: Bound<Term>) -> FastFieldRangeQuery {
        Self {
            bounds: BoundsRange::new(lower_bound, upper_bound),
        }
    }
}

impl Query for FastFieldRangeQuery {
    fn weight(&self, _enable_scoring: EnableScoring<'_>) -> crate::Result<Box<dyn Weight>> {
        Ok(Box::new(FastFieldRangeWeight::new(self.bounds.clone())))
    }
}

/// `FastFieldRangeWeight` uses the fast field to execute range queries.
#[derive(Clone, Debug)]
pub struct FastFieldRangeWeight {
    bounds: BoundsRange<Term>,
}

impl FastFieldRangeWeight {
    /// Create a new FastFieldRangeWeight
    pub fn new(bounds: BoundsRange<Term>) -> Self {
        Self { bounds }
    }
}

impl Weight for FastFieldRangeWeight {
    fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>> {
        // Check if both bounds are Bound::Unbounded
        if self.bounds.is_unbounded() {
            return Ok(Box::new(AllScorer::new(reader.max_doc())));
        }

        let term = self
            .bounds
            .get_inner()
            .expect("At least one bound must be set");
        let schema = reader.schema();
        let field_type = schema.get_field_entry(term.field()).field_type();
        assert_eq!(
            term.typ(),
            field_type.value_type(),
            "Field is of type {:?}, but got term of type {:?}",
            field_type,
            term.typ()
        );
        let field_name = term.get_full_path(reader.schema());

        let get_value_bytes = |term: &Term| term.value().value_bytes_payload();

        let term_value = term.value();
        if field_type.is_json() {
            let bounds = self
                .bounds
                .map_bound(|term| term.value().as_json_value_bytes().unwrap().to_owned());
            // Unlike with other field types JSON may have multiple columns of different types
            // under the same name
            //
            // In the JSON case the provided type in term may not exactly match the column type,
            // especially with the numeric type interpolation
            let json_value_bytes = term_value
                .as_json_value_bytes()
                .expect("expected json type in term");
            let typ = json_value_bytes.typ();

            match typ {
                Type::Str => {
                    let Some(str_dict_column): Option<StrColumn> =
                        reader.fast_fields().str(&field_name)?
                    else {
                        return Ok(Box::new(EmptyScorer));
                    };
                    let dict = str_dict_column.dictionary();

                    let bounds = self.bounds.map_bound(get_value_bytes);
                    // Get term ids for terms
                    let (lower_bound, upper_bound) =
                        dict.term_bounds_to_ord(bounds.lower_bound, bounds.upper_bound)?;
                    let fast_field_reader = reader.fast_fields();
                    let Some((column, _col_type)) = fast_field_reader
                        .u64_lenient_for_type(Some(&[ColumnType::Str]), &field_name)?
                    else {
                        return Ok(Box::new(EmptyScorer));
                    };
                    search_on_u64_ff(column, boost, BoundsRange::new(lower_bound, upper_bound))
                }
                Type::U64 | Type::I64 | Type::F64 => {
                    search_on_json_numerical_field(reader, &field_name, typ, bounds, boost)
                }
                Type::Date => {
                    let fast_field_reader = reader.fast_fields();
                    let Some((column, _col_type)) = fast_field_reader
                        .u64_lenient_for_type(Some(&[ColumnType::DateTime]), &field_name)?
                    else {
                        return Ok(Box::new(EmptyScorer));
                    };
                    let bounds = bounds.map_bound(|term| term.as_date().unwrap().to_u64());
                    search_on_u64_ff(
                        column,
                        boost,
                        BoundsRange::new(bounds.lower_bound, bounds.upper_bound),
                    )
                }
                Type::Bool | Type::Facet | Type::Bytes | Type::Json | Type::IpAddr => {
                    Err(crate::LucivyError::InvalidArgument(format!(
                        "unsupported value bytes type in json term value_bytes {:?}",
                        term_value.typ()
                    )))
                }
            }
        } else if field_type.is_ip_addr() {
            let parse_ip_from_bytes = |term: &Term| {
                term.value().as_ip_addr().ok_or_else(|| {
                    crate::LucivyError::InvalidArgument("Expected ip address".to_string())
                })
            };
            let bounds: BoundsRange<Ipv6Addr> = self.bounds.map_bound_res(parse_ip_from_bytes)?;

            let Some(ip_addr_column): Option<Column<Ipv6Addr>> =
                reader.fast_fields().column_opt(&field_name)?
            else {
                return Ok(Box::new(EmptyScorer));
            };
            let value_range = bound_range_inclusive_ip(
                &bounds.lower_bound,
                &bounds.upper_bound,
                ip_addr_column.min_value(),
                ip_addr_column.max_value(),
            );
            let docset = RangeDocSet::new(value_range, ip_addr_column);
            Ok(Box::new(ConstScorer::new(docset, boost)))
        } else if field_type.is_str() {
            let Some(str_dict_column): Option<StrColumn> = reader.fast_fields().str(&field_name)?
            else {
                return Ok(Box::new(EmptyScorer));
            };
            let dict = str_dict_column.dictionary();

            let bounds = self.bounds.map_bound(get_value_bytes);
            // Get term ids for terms
            let (lower_bound, upper_bound) =
                dict.term_bounds_to_ord(bounds.lower_bound, bounds.upper_bound)?;
            let fast_field_reader = reader.fast_fields();
            let Some((column, _col_type)) =
                fast_field_reader.u64_lenient_for_type(None, &field_name)?
            else {
                return Ok(Box::new(EmptyScorer));
            };
            search_on_u64_ff(column, boost, BoundsRange::new(lower_bound, upper_bound))
        } else {
            assert!(
                maps_to_u64_fastfield(field_type.value_type()),
                "{field_type:?}"
            );

            let bounds = self.bounds.map_bound_res(|term| {
                let value = term.value();
                let val = if let Some(val) = value.as_u64() {
                    val
                } else if let Some(val) = value.as_i64() {
                    val.to_u64()
                } else if let Some(val) = value.as_f64() {
                    val.to_u64()
                } else if let Some(val) = value.as_date() {
                    val.to_u64()
                } else {
                    return Err(LucivyError::InvalidArgument(format!(
                        "Expected term with u64, i64, f64 or date, but got {term:?}"
                    )));
                };
                Ok(val)
            })?;

            let fast_field_reader = reader.fast_fields();
            let Some((column, _col_type)) = fast_field_reader.u64_lenient_for_type(
                Some(&[
                    ColumnType::U64,
                    ColumnType::I64,
                    ColumnType::F64,
                    ColumnType::DateTime,
                ]),
                &field_name,
            )?
            else {
                return Ok(Box::new(EmptyScorer));
            };
            search_on_u64_ff(
                column,
                boost,
                BoundsRange::new(bounds.lower_bound, bounds.upper_bound),
            )
        }
    }

    fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation> {
        let mut scorer = self.scorer(reader, 1.0)?;
        if scorer.seek(doc) != doc {
            return Err(LucivyError::InvalidArgument(format!(
                "Document #({doc}) does not match"
            )));
        }
        let explanation = Explanation::new("Const", scorer.score());

        Ok(explanation)
    }
}

/// On numerical fields the column type may not match the user provided one.
///
/// Convert into fast field value space and search.
fn search_on_json_numerical_field(
    reader: &SegmentReader,
    field_name: &str,
    typ: Type,
    bounds: BoundsRange<ValueBytes<Vec<u8>>>,
    boost: Score,
) -> crate::Result<Box<dyn Scorer>> {
    // Since we don't know which type was interpolated for the internal column we
    // have to check for all numeric types (only one exists)
    let allowed_column_types: Option<&[ColumnType]> =
        Some(&[ColumnType::F64, ColumnType::I64, ColumnType::U64]);
    let fast_field_reader = reader.fast_fields();
    let Some((column, col_type)) =
        fast_field_reader.u64_lenient_for_type(allowed_column_types, field_name)?
    else {
        return Ok(Box::new(EmptyScorer));
    };
    let actual_column_type: NumericalType = col_type
        .numerical_type()
        .unwrap_or_else(|| panic!("internal error: couldn't cast to numerical_type: {col_type:?}"));

    let bounds = match typ.numerical_type().unwrap() {
        NumericalType::I64 => {
            let bounds = bounds.map_bound(|term| term.as_i64().unwrap());
            match actual_column_type {
                NumericalType::I64 => bounds.map_bound(|&term| term.to_u64()),
                NumericalType::U64 => {
                    bounds.transform_inner(
                        |&val| {
                            if val < 0 {
                                return TransformBound::NewBound(Bound::Unbounded);
                            }
                            TransformBound::Existing(val as u64)
                        },
                        |&val| {
                            if val < 0 {
                                // no hits case
                                return TransformBound::NewBound(Bound::Excluded(0));
                            }
                            TransformBound::Existing(val as u64)
                        },
                    )
                }
                NumericalType::F64 => bounds.map_bound(|&term| (term as f64).to_u64()),
            }
        }
        NumericalType::U64 => {
            let bounds = bounds.map_bound(|term| term.as_u64().unwrap());
            match actual_column_type {
                NumericalType::U64 => bounds.map_bound(|&term| term.to_u64()),
                NumericalType::I64 => {
                    bounds.transform_inner(
                        |&val| {
                            if val > i64::MAX as u64 {
                                // Actual no hits case
                                return TransformBound::NewBound(Bound::Excluded(i64::MAX as u64));
                            }
                            TransformBound::Existing((val as i64).to_u64())
                        },
                        |&val| {
                            if val > i64::MAX as u64 {
                                return TransformBound::NewBound(Bound::Unbounded);
                            }
                            TransformBound::Existing((val as i64).to_u64())
                        },
                    )
                }
                NumericalType::F64 => bounds.map_bound(|&term| (term as f64).to_u64()),
            }
        }
        NumericalType::F64 => {
            let bounds = bounds.map_bound(|term| term.as_f64().unwrap());
            match actual_column_type {
                NumericalType::U64 => transform_from_f64_bounds::<u64>(&bounds),
                NumericalType::I64 => transform_from_f64_bounds::<i64>(&bounds),
                NumericalType::F64 => bounds.map_bound(|&term| term.to_u64()),
            }
        }
    };
    search_on_u64_ff(
        column,
        boost,
        BoundsRange::new(bounds.lower_bound, bounds.upper_bound),
    )
}

trait IntType {
    fn min() -> Self;
    fn max() -> Self;
    fn to_f64(self) -> f64;
    fn from_f64(val: f64) -> Self;
}
impl IntType for i64 {
    fn min() -> Self {
        Self::MIN
    }
    fn max() -> Self {
        Self::MAX
    }
    fn to_f64(self) -> f64 {
        self as f64
    }
    fn from_f64(val: f64) -> Self {
        val as Self
    }
}
impl IntType for u64 {
    fn min() -> Self {
        Self::MIN
    }
    fn max() -> Self {
        Self::MAX
    }
    fn to_f64(self) -> f64 {
        self as f64
    }
    fn from_f64(val: f64) -> Self {
        val as Self
    }
}

fn transform_from_f64_bounds<T: IntType + MonotonicallyMappableToU64>(
    bounds: &BoundsRange<f64>,
) -> BoundsRange<u64> {
    bounds.transform_inner(
        |&lower_bound| {
            if lower_bound < T::min().to_f64() {
                return TransformBound::NewBound(Bound::Unbounded);
            }
            if lower_bound > T::max().to_f64() {
                // no hits case
                return TransformBound::NewBound(Bound::Excluded(u64::MAX));
            }

            if lower_bound.fract() == 0.0 {
                TransformBound::Existing(T::from_f64(lower_bound).to_u64())
            } else {
                TransformBound::NewBound(Bound::Included(T::from_f64(lower_bound.trunc()).to_u64()))
            }
        },
        |&upper_bound| {
            if upper_bound < T::min().to_f64() {
                return TransformBound::NewBound(Bound::Unbounded);
            }
            if upper_bound > T::max().to_f64() {
                // no hits case
                return TransformBound::NewBound(Bound::Included(u64::MAX));
            }
            if upper_bound.fract() == 0.0 {
                TransformBound::Existing(T::from_f64(upper_bound).to_u64())
            } else {
                TransformBound::NewBound(Bound::Included(T::from_f64(upper_bound.trunc()).to_u64()))
            }
        },
    )
}

fn search_on_u64_ff(
    column: Column<u64>,
    boost: Score,
    bounds: BoundsRange<u64>,
) -> crate::Result<Box<dyn Scorer>> {
    let col_min_value = column.min_value();
    let col_max_value = column.max_value();
    #[expect(clippy::reversed_empty_ranges)]
    let value_range = bound_to_value_range(
        &bounds.lower_bound,
        &bounds.upper_bound,
        column.min_value(),
        column.max_value(),
    )
    .unwrap_or(1..=0); // empty range
    if value_range.is_empty() {
        return Ok(Box::new(EmptyScorer));
    }
    if col_min_value >= *value_range.start() && col_max_value <= *value_range.end() {
        // all values in the column are within the range.
        if column.index.get_cardinality() == Cardinality::Full {
            if boost != 1.0f32 {
                return Ok(Box::new(ConstScorer::new(
                    AllScorer::new(column.num_docs()),
                    boost,
                )));
            } else {
                return Ok(Box::new(AllScorer::new(column.num_docs())));
            }
        } else {
            // TODO Make it a field presence request for that specific column
        }
    }

    let docset = RangeDocSet::new(value_range, column);
    Ok(Box::new(ConstScorer::new(docset, boost)))
}

/// Returns true if the type maps to a u64 fast field
pub(crate) fn maps_to_u64_fastfield(typ: Type) -> bool {
    match typ {
        Type::U64 | Type::I64 | Type::F64 | Type::Bool | Type::Date => true,
        Type::IpAddr => false,
        Type::Str | Type::Facet | Type::Bytes | Type::Json => false,
    }
}

fn bound_range_inclusive_ip(
    lower_bound: &Bound<Ipv6Addr>,
    upper_bound: &Bound<Ipv6Addr>,
    min_value: Ipv6Addr,
    max_value: Ipv6Addr,
) -> RangeInclusive<Ipv6Addr> {
    let start_value = match lower_bound {
        Bound::Included(ip_addr) => *ip_addr,
        Bound::Excluded(ip_addr) => Ipv6Addr::from(ip_addr.to_u128() + 1),
        Bound::Unbounded => min_value,
    };

    let end_value = match upper_bound {
        Bound::Included(ip_addr) => *ip_addr,
        Bound::Excluded(ip_addr) => Ipv6Addr::from(ip_addr.to_u128() - 1),
        Bound::Unbounded => max_value,
    };
    start_value..=end_value
}

// Returns None, if the range cannot be converted to a inclusive range (which equals to a empty
// range).
fn bound_to_value_range<T: MonotonicallyMappableToU64>(
    lower_bound: &Bound<T>,
    upper_bound: &Bound<T>,
    min_value: T,
    max_value: T,
) -> Option<RangeInclusive<T>> {
    let mut start_value = match lower_bound {
        Bound::Included(val) => *val,
        Bound::Excluded(val) => T::from_u64(val.to_u64().checked_add(1)?),
        Bound::Unbounded => min_value,
    };
    if start_value.partial_cmp(&min_value) == Some(std::cmp::Ordering::Less) {
        start_value = min_value;
    }
    let end_value = match upper_bound {
        Bound::Included(val) => *val,
        Bound::Excluded(val) => T::from_u64(val.to_u64().checked_sub(1)?),
        Bound::Unbounded => max_value,
    };
    Some(start_value..=end_value)
}

#[cfg(test)]
mod tests {
    use std::ops::{Bound, RangeInclusive};

    use common::bounds::BoundsRange;
    use common::DateTime;
    use proptest::prelude::*;
    use rand::rngs::StdRng;
    use rand::seq::SliceRandom;
    use rand::SeedableRng;
    use time::format_description::well_known::Rfc3339;
    use time::OffsetDateTime;

    use crate::collector::{Count, TopDocs};
    use crate::fastfield::FastValue;
    use crate::query::range_query::range_query_fastfield::FastFieldRangeWeight;
    use crate::query::{QueryParser, RangeQuery, Weight};
    use crate::schema::{
        DateOptions, Field, NumericOptions, Schema, SchemaBuilder, FAST, INDEXED, STORED, STRING,
        TEXT,
    };
    use crate::{Index, IndexWriter, LucivyDocument, Term, TERMINATED};

    #[test]
    fn test_text_field_ff_range_query() -> crate::Result<()> {
        let mut schema_builder = Schema::builder();
        schema_builder.add_text_field("title", TEXT | FAST);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema.clone());
        let mut index_writer = index.writer_for_tests()?;
        let title = schema.get_field("title").unwrap();
        index_writer.add_document(doc!(
          title => "bbb"
        ))?;
        index_writer.add_document(doc!(
          title => "ddd"
        ))?;
        index_writer.commit()?;
        let reader = index.reader()?;
        let searcher = reader.searcher();
        let query_parser = QueryParser::for_index(&index, vec![title]);

        let test_query = |query, num_hits| {
            let query = query_parser.parse_query(query).unwrap();
            let top_docs = searcher
                .search(&query, &TopDocs::with_limit(10).order_by_score())
                .unwrap();
            assert_eq!(top_docs.len(), num_hits);
        };

        test_query("title:[aaa TO ccc]", 1);
        test_query("title:[aaa TO bbb]", 1);
        test_query("title:[bbb TO bbb]", 1);
        test_query("title:[bbb TO ddd]", 2);
        test_query("title:[bbb TO eee]", 2);
        test_query("title:[bb TO eee]", 2);
        test_query("title:[ccc TO ccc]", 0);
        test_query("title:[ccc TO ddd]", 1);
        test_query("title:[ccc TO eee]", 1);

        test_query("title:[aaa TO *}", 2);
        test_query("title:[bbb TO *]", 2);
        test_query("title:[bb TO *]", 2);
        test_query("title:[ccc TO *]", 1);
        test_query("title:[ddd TO *]", 1);
        test_query("title:[dddd TO *]", 0);

        test_query("title:{aaa TO *}", 2);
        test_query("title:{bbb TO *]", 1);
        test_query("title:{bb TO *]", 2);
        test_query("title:{ccc TO *]", 1);
        test_query("title:{ddd TO *]", 0);
        test_query("title:{dddd TO *]", 0);

        test_query("title:[* TO bb]", 0);
        test_query("title:[* TO bbb]", 1);
        test_query("title:[* TO ccc]", 1);
        test_query("title:[* TO ddd]", 2);
        test_query("title:[* TO ddd}", 1);
        test_query("title:[* TO eee]", 2);

        Ok(())
    }

    #[test]
    fn test_date_range_query() {
        let mut schema_builder = Schema::builder();
        let options = DateOptions::default()
            .set_precision(common::DateTimePrecision::Microseconds)
            .set_fast();
        let date_field = schema_builder.add_date_field("date", options);
        let schema = schema_builder.build();

        let index = Index::create_in_ram(schema.clone());
        {
            let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();
            // This is added a string and creates a string column!
            index_writer
                .add_document(doc!(date_field => DateTime::from_utc(
                    OffsetDateTime::parse("2022-12-01T00:00:01Z", &Rfc3339).unwrap(),
                )))
                .unwrap();
            index_writer
                .add_document(doc!(date_field => DateTime::from_utc(
                    OffsetDateTime::parse("2023-12-01T00:00:01Z", &Rfc3339).unwrap(),
                )))
                .unwrap();
            index_writer
                .add_document(doc!(date_field => DateTime::from_utc(
                    OffsetDateTime::parse("2015-02-01T00:00:00.001Z", &Rfc3339).unwrap(),
                )))
                .unwrap();
            index_writer.commit().unwrap();
        }

        // Date field
        let dt1 =
            DateTime::from_utc(OffsetDateTime::parse("2022-12-01T00:00:01Z", &Rfc3339).unwrap());
        let dt2 =
            DateTime::from_utc(OffsetDateTime::parse("2023-12-01T00:00:01Z", &Rfc3339).unwrap());
        let dt3 = DateTime::from_utc(
            OffsetDateTime::parse("2015-02-01T00:00:00.001Z", &Rfc3339).unwrap(),
        );
        let dt4 = DateTime::from_utc(
            OffsetDateTime::parse("2015-02-01T00:00:00.002Z", &Rfc3339).unwrap(),
        );

        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let query_parser = QueryParser::for_index(&index, vec![date_field]);
        let test_query = |query, num_hits| {
            let query = query_parser.parse_query(query).unwrap();
            let top_docs = searcher
                .search(&query, &TopDocs::with_limit(10).order_by_score())
                .unwrap();
            assert_eq!(top_docs.len(), num_hits);
        };

        test_query(
            "date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.001Z]",
            1,
        );
        test_query(
            "date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z}",
            1,
        );
        test_query(
            "date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z]",
            1,
        );
        test_query(
            "date:{2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z]",
            0,
        );

        let count = |range_query: RangeQuery| searcher.search(&range_query, &Count).unwrap();
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(Term::from_field_date(date_field, dt3)),
                Bound::Excluded(Term::from_field_date(date_field, dt4)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(Term::from_field_date(date_field, dt3)),
                Bound::Included(Term::from_field_date(date_field, dt4)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(Term::from_field_date(date_field, dt1)),
                Bound::Included(Term::from_field_date(date_field, dt2)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(Term::from_field_date(date_field, dt1)),
                Bound::Excluded(Term::from_field_date(date_field, dt2)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Excluded(Term::from_field_date(date_field, dt1)),
                Bound::Excluded(Term::from_field_date(date_field, dt2)),
            )),
            0
        );
    }

    fn get_json_term<T: FastValue>(field: Field, path: &str, value: T) -> Term {
        let mut term = Term::from_field_json_path(field, path, true);
        term.append_type_and_fast_value(value);
        term
    }

    #[test]
    fn mixed_numerical_test() {
        let mut schema_builder = Schema::builder();
        schema_builder.add_i64_field("id_i64", STORED | FAST);
        schema_builder.add_u64_field("id_u64", STORED | FAST);
        schema_builder.add_f64_field("id_f64", STORED | FAST);
        let schema = schema_builder.build();

        fn get_json_term<T: FastValue>(schema: &Schema, path: &str, value: T) -> Term {
            let field = schema.get_field(path).unwrap();
            Term::from_fast_value(field, &value)
            // term.append_type_and_fast_value(value);
            // term
        }
        let index = Index::create_in_ram(schema.clone());
        {
            let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();

            let doc = json!({
                "id_u64": 0,
                "id_i64": 50,
            });
            let doc = LucivyDocument::parse_json(&schema, &serde_json::to_string(&doc).unwrap())
                .unwrap();
            index_writer.add_document(doc).unwrap();
            let doc = json!({
                "id_u64": 10,
                "id_i64": 1000,
            });
            let doc = LucivyDocument::parse_json(&schema, &serde_json::to_string(&doc).unwrap())
                .unwrap();
            index_writer.add_document(doc).unwrap();

            index_writer.commit().unwrap();
        }

        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let count = |range_query: RangeQuery| searcher.search(&range_query, &Count).unwrap();

        // u64 on u64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(&schema, "id_u64", 10u64)),
                Bound::Included(get_json_term(&schema, "id_u64", 10u64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(&schema, "id_u64", 9u64)),
                Bound::Excluded(get_json_term(&schema, "id_u64", 10u64)),
            )),
            0
        );

        // i64 on i64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(&schema, "id_i64", 50i64)),
                Bound::Included(get_json_term(&schema, "id_i64", 1000i64)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(&schema, "id_i64", 50i64)),
                Bound::Excluded(get_json_term(&schema, "id_i64", 1000i64)),
            )),
            1
        );
    }

    #[test]
    fn json_range_mixed_val() {
        let mut schema_builder = Schema::builder();
        let json_field = schema_builder.add_json_field("json", TEXT | STORED | FAST);
        let schema = schema_builder.build();

        let index = Index::create_in_ram(schema);
        {
            let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();
            let doc = json!({
                "mixed_val": 10000,
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            let doc = json!({
                "mixed_val": 20000,
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            let doc = json!({
                "mixed_val": "1000a",
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            let doc = json!({
                "mixed_val": "2000a",
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            index_writer.commit().unwrap();
        }
        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let count = |range_query: RangeQuery| searcher.search(&range_query, &Count).unwrap();

        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "mixed_val", 10000u64)),
                Bound::Included(get_json_term(json_field, "mixed_val", 20000u64)),
            )),
            2
        );
        fn get_json_term_str(field: Field, path: &str, value: &str) -> Term {
            let mut term = Term::from_field_json_path(field, path, true);
            term.append_type_and_str(value);
            term
        }
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term_str(json_field, "mixed_val", "1000a")),
                Bound::Included(get_json_term_str(json_field, "mixed_val", "2000b")),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term_str(json_field, "mixed_val", "1000")),
                Bound::Included(get_json_term_str(json_field, "mixed_val", "2000a")),
            )),
            2
        );
    }

    #[test]
    fn json_range_test() {
        let mut schema_builder = Schema::builder();
        let json_field = schema_builder.add_json_field("json", TEXT | STORED | FAST);
        let schema = schema_builder.build();

        let index = Index::create_in_ram(schema);
        let u64_val = u64::MAX - 1;
        {
            let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();
            let doc = json!({
                "id_u64": 0,
                "id_f64": 10.5,
                "id_i64": -100,
                "date": "2022-12-01T00:00:01Z"
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            let doc = json!({
                "id_u64": u64_val,
                "id_f64": 1000.5,
                "id_i64": 1000,
                "date": "2023-12-01T00:00:01Z"
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();
            let doc = json!({
                "date": "2015-02-01T00:00:00.001Z"
            });
            index_writer.add_document(doc!(json_field => doc)).unwrap();

            index_writer.commit().unwrap();
        }

        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let count = |range_query: RangeQuery| searcher.search(&range_query, &Count).unwrap();

        // u64 on u64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_u64", u64_val)),
                Bound::Included(get_json_term(json_field, "id_u64", u64_val)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_u64", u64_val)),
                Bound::Excluded(get_json_term(json_field, "id_u64", u64_val)),
            )),
            0
        );
        // f64 on u64 field
        assert_eq!(
            count(RangeQuery::new(
                // We need to subtract since there is some inaccuracy
                Bound::Included(get_json_term(
                    json_field,
                    "id_u64",
                    (u64_val - 10000) as f64
                )),
                Bound::Included(get_json_term(json_field, "id_u64", (u64_val) as f64)),
            )),
            1
        );
        // i64 on u64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_u64", 0_i64)),
                Bound::Included(get_json_term(json_field, "id_u64", 0_i64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_u64", 1_i64)),
                Bound::Included(get_json_term(json_field, "id_u64", 1_i64)),
            )),
            0
        );
        // u64 on f64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_f64", 10_u64)),
                Bound::Included(get_json_term(json_field, "id_f64", 11_u64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_f64", 10_u64)),
                Bound::Included(get_json_term(json_field, "id_f64", 2000_u64)),
            )),
            2
        );
        // i64 on f64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_f64", 10_i64)),
                Bound::Included(get_json_term(json_field, "id_f64", 2000_i64)),
            )),
            2
        );

        // i64 on i64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000i64)),
                Bound::Included(get_json_term(json_field, "id_i64", 1000i64)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", 1000i64)),
                Bound::Excluded(get_json_term(json_field, "id_i64", 1001i64)),
            )),
            1
        );

        // u64 on i64
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", 0_u64)),
                Bound::Included(get_json_term(json_field, "id_i64", 1000u64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", 0_u64)),
                Bound::Included(get_json_term(json_field, "id_i64", 999u64)),
            )),
            0
        );
        // f64 on i64 field
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000.0)),
                Bound::Included(get_json_term(json_field, "id_i64", 1000.0)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000.0f64)),
                Bound::Excluded(get_json_term(json_field, "id_i64", 1000.0f64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000.0f64)),
                Bound::Included(get_json_term(json_field, "id_i64", 1000.0f64)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000.0f64)),
                Bound::Excluded(get_json_term(json_field, "id_i64", 1000.01f64)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "id_i64", -1000.0f64)),
                Bound::Included(get_json_term(json_field, "id_i64", 999.99f64)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Excluded(get_json_term(json_field, "id_i64", 999.9)),
                Bound::Excluded(get_json_term(json_field, "id_i64", 1000.1)),
            )),
            1
        );

        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let query_parser = QueryParser::for_index(&index, vec![json_field]);
        let test_query = |query, num_hits| {
            let query = query_parser.parse_query(query).unwrap();
            let top_docs = searcher
                .search(&query, &TopDocs::with_limit(10).order_by_score())
                .unwrap();
            assert_eq!(top_docs.len(), num_hits);
        };

        test_query(
            "json.date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.001Z]",
            1,
        );
        test_query(
            "json.date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z}",
            1,
        );
        test_query(
            "json.date:[2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z]",
            1,
        );
        test_query(
            "json.date:{2015-02-01T00:00:00.001Z TO 2015-02-01T00:00:00.002Z]",
            0,
        );

        // Date field
        let dt1 =
            DateTime::from_utc(OffsetDateTime::parse("2022-12-01T00:00:01Z", &Rfc3339).unwrap());
        let dt2 =
            DateTime::from_utc(OffsetDateTime::parse("2023-12-01T00:00:01Z", &Rfc3339).unwrap());

        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "date", dt1)),
                Bound::Included(get_json_term(json_field, "date", dt2)),
            )),
            2
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Included(get_json_term(json_field, "date", dt1)),
                Bound::Excluded(get_json_term(json_field, "date", dt2)),
            )),
            1
        );
        assert_eq!(
            count(RangeQuery::new(
                Bound::Excluded(get_json_term(json_field, "date", dt1)),
                Bound::Excluded(get_json_term(json_field, "date", dt2)),
            )),
            0
        );
        // Date precision test. We don't want to truncate the precision
        let dt3 = DateTime::from_utc(
            OffsetDateTime::parse("2015-02-01T00:00:00.001Z", &Rfc3339).unwrap(),
        );
        let dt4 = DateTime::from_utc(
            OffsetDateTime::parse("2015-02-01T00:00:00.002Z", &Rfc3339).unwrap(),
        );
        let query = RangeQuery::new(
            Bound::Included(get_json_term(json_field, "date", dt3)),
            Bound::Excluded(get_json_term(json_field, "date", dt4)),
        );
        assert_eq!(count(query), 1);
    }

    #[derive(Clone, Debug)]
    pub struct Doc {
        pub id_name: String,
        pub id: u64,
    }

    fn operation_strategy() -> impl Strategy<Value = Doc> {
        prop_oneof![
            (0u64..10_000u64).prop_map(doc_from_id_1),
            (1u64..10_000u64).prop_map(doc_from_id_2),
        ]
    }

    fn doc_from_id_1(id: u64) -> Doc {
        let id = id * 1000;
        Doc {
            id_name: format!("id_name{id:010}"),
            id,
        }
    }
    fn doc_from_id_2(id: u64) -> Doc {
        let id = id * 1000;
        Doc {
            id_name: format!("id_name{:010}", id - 1),
            id,
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(10))]
        #[test]
        fn test_range_for_docs_prop(ops in proptest::collection::vec(operation_strategy(), 1..1000)) {
            assert!(test_id_range_for_docs(ops).is_ok());
        }
    }

    #[test]
    fn range_regression1_test() {
        let ops = vec![doc_from_id_1(0)];
        assert!(test_id_range_for_docs(ops).is_ok());
    }

    #[test]
    fn range_regression1_test_json() {
        let ops = vec![doc_from_id_1(0)];
        assert!(test_id_range_for_docs_json(ops).is_ok());
    }

    #[test]
    fn test_range_regression2() {
        let ops = vec![
            doc_from_id_1(52),
            doc_from_id_1(63),
            doc_from_id_1(12),
            doc_from_id_2(91),
            doc_from_id_2(33),
        ];
        assert!(test_id_range_for_docs(ops).is_ok());
    }

    #[test]
    fn test_range_regression3() {
        let ops = vec![doc_from_id_1(9), doc_from_id_1(0), doc_from_id_1(13)];
        assert!(test_id_range_for_docs(ops).is_ok());
    }

    #[test]
    fn test_range_regression_simplified() {
        let mut schema_builder = SchemaBuilder::new();
        let field = schema_builder.add_u64_field("test_field", FAST);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);
        let mut writer: IndexWriter = index.writer_for_tests().unwrap();
        writer.add_document(doc!(field=>52_000u64)).unwrap();
        writer.commit().unwrap();
        let searcher = index.reader().unwrap().searcher();
        let range_query = FastFieldRangeWeight::new(BoundsRange::new(
            Bound::Included(Term::from_field_u64(field, 50_000)),
            Bound::Included(Term::from_field_u64(field, 50_002)),
        ));
        let scorer = range_query
            .scorer(searcher.segment_reader(0), 1.0f32)
            .unwrap();
        assert_eq!(scorer.doc(), TERMINATED);
    }

    #[test]
    fn range_regression3_test() {
        let ops = vec![doc_from_id_1(1), doc_from_id_1(2), doc_from_id_1(3)];
        assert!(test_id_range_for_docs(ops).is_ok());
    }

    #[test]
    fn range_regression4_test() {
        let ops = vec![doc_from_id_2(100)];
        assert!(test_id_range_for_docs(ops).is_ok());
    }

    pub fn create_index_from_docs(docs: &[Doc], json_field: bool) -> Index {
        let mut schema_builder = Schema::builder();
        if json_field {
            let json_field = schema_builder.add_json_field("json", TEXT | STORED | FAST);
            let schema = schema_builder.build();

            let index = Index::create_in_ram(schema);

            {
                let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();
                for doc in docs.iter() {
                    let doc = json!({
                        "ids_i64": doc.id as i64,
                        "ids_i64": doc.id as i64,
                        "ids_f64": doc.id as f64,
                        "ids_f64": doc.id as f64,
                        "ids": doc.id,
                        "ids": doc.id,
                        "id": doc.id,
                        "id_f64": doc.id as f64,
                        "id_i64": doc.id as i64,
                        "id_name": doc.id_name.to_string(),
                        "id_name_fast": doc.id_name.to_string(),
                    });
                    index_writer.add_document(doc!(json_field => doc)).unwrap();
                }

                index_writer.commit().unwrap();
            }
            index
        } else {
            let id_u64_field = schema_builder.add_u64_field("id", INDEXED | STORED | FAST);
            let ids_u64_field = schema_builder
                .add_u64_field("ids", NumericOptions::default().set_fast().set_indexed());

            let id_f64_field = schema_builder.add_f64_field("id_f64", INDEXED | STORED | FAST);
            let ids_f64_field = schema_builder.add_f64_field(
                "ids_f64",
                NumericOptions::default().set_fast().set_indexed(),
            );

            let id_i64_field = schema_builder.add_i64_field("id_i64", INDEXED | STORED | FAST);
            let ids_i64_field = schema_builder.add_i64_field(
                "ids_i64",
                NumericOptions::default().set_fast().set_indexed(),
            );

            let text_field = schema_builder.add_text_field("id_name", STRING | STORED);
            let text_field2 = schema_builder.add_text_field("id_name_fast", STRING | STORED | FAST);
            let schema = schema_builder.build();

            let index = Index::create_in_ram(schema);

            {
                let mut index_writer = index.writer_with_num_threads(1, 50_000_000).unwrap();
                for doc in docs.iter() {
                    index_writer
                        .add_document(doc!(
                            ids_i64_field => doc.id as i64,
                            ids_i64_field => doc.id as i64,
                            ids_f64_field => doc.id as f64,
                            ids_f64_field => doc.id as f64,
                            ids_u64_field => doc.id,
                            ids_u64_field => doc.id,
                            id_u64_field => doc.id,
                            id_f64_field => doc.id as f64,
                            id_i64_field => doc.id as i64,
                            text_field => doc.id_name.to_string(),
                            text_field2 => doc.id_name.to_string(),
                        ))
                        .unwrap();
                }

                index_writer.commit().unwrap();
            }
            index
        }
    }

    fn test_id_range_for_docs(docs: Vec<Doc>) -> crate::Result<()> {
        test_id_range_for_docs_with_opt(docs, false)
    }
    fn test_id_range_for_docs_json(docs: Vec<Doc>) -> crate::Result<()> {
        test_id_range_for_docs_with_opt(docs, true)
    }

    fn test_id_range_for_docs_with_opt(docs: Vec<Doc>, json: bool) -> crate::Result<()> {
        let index = create_index_from_docs(&docs, json);
        let reader = index.reader().unwrap();
        let searcher = reader.searcher();

        let mut rng: StdRng = StdRng::from_seed([1u8; 32]);

        let get_num_hits = |query| searcher.search(&query, &Count).unwrap();
        let query_from_text = |text: &str| {
            QueryParser::for_index(&index, vec![])
                .parse_query(text)
                .unwrap()
        };

        let field_path = |field: &str| {
            if json {
                format!("json.{field}")
            } else {
                field.to_string()
            }
        };

        let gen_query_inclusive = |field: &str, range: RangeInclusive<u64>| {
            format!(
                "{}:[{} TO {}]",
                field_path(field),
                range.start(),
                range.end()
            )
        };
        let gen_query_exclusive = |field: &str, range: RangeInclusive<u64>| {
            format!(
                "{}:{{{} TO {}}}",
                field_path(field),
                range.start(),
                range.end()
            )
        };

        let test_sample = |sample_docs: Vec<Doc>| {
            let mut ids: Vec<u64> = sample_docs.iter().map(|doc| doc.id).collect();
            ids.sort();
            let expected_num_hits = docs
                .iter()
                .filter(|doc| (ids[0]..=ids[1]).contains(&doc.id))
                .count();

            let query = gen_query_inclusive("id", ids[0]..=ids[1]);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            let query = gen_query_inclusive("ids", ids[0]..=ids[1]);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            // Text query
            {
                let test_text_query = |field_name: &str| {
                    let mut id_names: Vec<&str> =
                        sample_docs.iter().map(|doc| doc.id_name.as_str()).collect();
                    id_names.sort();
                    let expected_num_hits = docs
                        .iter()
                        .filter(|doc| (id_names[0]..=id_names[1]).contains(&doc.id_name.as_str()))
                        .count();
                    let query = format!(
                        "{}:[{} TO {}]",
                        field_path(field_name),
                        id_names[0],
                        id_names[1]
                    );
                    assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
                };

                test_text_query("id_name");
                test_text_query("id_name_fast");
            }

            // Exclusive range
            let expected_num_hits = docs
                .iter()
                .filter(|doc| {
                    (ids[0].saturating_add(1)..=ids[1].saturating_sub(1)).contains(&doc.id)
                })
                .count();

            let query = gen_query_exclusive("id", ids[0]..=ids[1]);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            let query = gen_query_exclusive("ids", ids[0]..=ids[1]);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            // Intersection search
            let id_filter = sample_docs[0].id_name.to_string();
            let expected_num_hits = docs
                .iter()
                .filter(|doc| (ids[0]..=ids[1]).contains(&doc.id) && doc.id_name == id_filter)
                .count();
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("id", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("id_f64", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("id_i64", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            // Intersection search on multivalue id field
            let id_filter = sample_docs[0].id_name.to_string();
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("ids", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("ids_f64", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
            let query = format!(
                "{} AND {}:{}",
                gen_query_inclusive("ids_i64", ids[0]..=ids[1]),
                field_path("id_name"),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
        };

        test_sample(vec![docs[0].clone(), docs[0].clone()]);

        let samples: Vec<_> = docs.choose_multiple(&mut rng, 3).collect();

        if samples.len() > 1 {
            test_sample(vec![samples[0].clone(), samples[1].clone()]);
            test_sample(vec![samples[1].clone(), samples[1].clone()]);
        }
        if samples.len() > 2 {
            test_sample(vec![samples[1].clone(), samples[2].clone()]);
        }

        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod ip_range_tests {
    use proptest::prelude::ProptestConfig;
    use proptest::strategy::Strategy;
    use proptest::{prop_oneof, proptest};

    use super::*;
    use crate::collector::Count;
    use crate::query::QueryParser;
    use crate::schema::{Schema, FAST, INDEXED, STORED, STRING};
    use crate::{Index, IndexWriter};

    #[derive(Clone, Debug)]
    pub struct Doc {
        pub id: String,
        pub ip: Ipv6Addr,
    }

    fn operation_strategy() -> impl Strategy<Value = Doc> {
        prop_oneof![
            (0u64..10_000u64).prop_map(doc_from_id_1),
            (1u64..10_000u64).prop_map(doc_from_id_2),
        ]
    }

    pub fn doc_from_id_1(id: u64) -> Doc {
        let id = id * 1000;
        Doc {
            // ip != id
            id: id.to_string(),
            ip: Ipv6Addr::from_u128(id as u128),
        }
    }
    fn doc_from_id_2(id: u64) -> Doc {
        let id = id * 1000;
        Doc {
            // ip != id
            id: (id - 1).to_string(),
            ip: Ipv6Addr::from_u128(id as u128),
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(10))]
        #[test]
        fn test_ip_range_for_docs_prop(ops in proptest::collection::vec(operation_strategy(), 1..1000)) {
            assert!(test_ip_range_for_docs(&ops).is_ok());
        }
    }

    #[test]
    fn test_ip_range_regression1() {
        let ops = &[doc_from_id_1(0)];
        assert!(test_ip_range_for_docs(ops).is_ok());
    }

    #[test]
    fn test_ip_range_regression2() {
        let ops = &[
            doc_from_id_1(52),
            doc_from_id_1(63),
            doc_from_id_1(12),
            doc_from_id_2(91),
            doc_from_id_2(33),
        ];
        assert!(test_ip_range_for_docs(ops).is_ok());
    }

    #[test]
    fn test_ip_range_regression3() {
        let ops = &[doc_from_id_1(1), doc_from_id_1(2), doc_from_id_1(3)];
        assert!(test_ip_range_for_docs(ops).is_ok());
    }

    #[test]
    fn test_ip_range_regression3_simple() {
        let mut schema_builder = Schema::builder();
        let ips_field = schema_builder.add_ip_addr_field("ips", FAST | INDEXED);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);
        let mut writer: IndexWriter = index.writer_for_tests().unwrap();
        let ip_addrs: Vec<Ipv6Addr> = [1000, 2000, 3000]
            .into_iter()
            .map(Ipv6Addr::from_u128)
            .collect();
        for &ip_addr in &ip_addrs {
            writer
                .add_document(doc!(ips_field=>ip_addr, ips_field=>ip_addr))
                .unwrap();
        }
        writer.commit().unwrap();
        let searcher = index.reader().unwrap().searcher();
        let range_weight = FastFieldRangeWeight::new(BoundsRange::new(
            Bound::Included(Term::from_field_ip_addr(ips_field, ip_addrs[1])),
            Bound::Included(Term::from_field_ip_addr(ips_field, ip_addrs[2])),
        ));

        let count =
            crate::query::weight::Weight::count(&range_weight, searcher.segment_reader(0)).unwrap();
        assert_eq!(count, 2);
    }

    pub fn create_index_from_ip_docs(docs: &[Doc]) -> Index {
        let mut schema_builder = Schema::builder();
        let ip_field = schema_builder.add_ip_addr_field("ip", STORED | FAST);
        let ips_field = schema_builder.add_ip_addr_field("ips", FAST | INDEXED);
        let text_field = schema_builder.add_text_field("id", STRING | STORED);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);

        {
            let mut index_writer = index.writer_with_num_threads(2, 60_000_000).unwrap();
            for doc in docs.iter() {
                index_writer
                    .add_document(doc!(
                        ips_field => doc.ip,
                        ips_field => doc.ip,
                        ip_field => doc.ip,
                        text_field => doc.id.to_string(),
                    ))
                    .unwrap();
            }

            index_writer.commit().unwrap();
        }
        index
    }

    fn test_ip_range_for_docs(docs: &[Doc]) -> crate::Result<()> {
        let index = create_index_from_ip_docs(docs);
        let reader = index.reader().unwrap();
        let searcher = reader.searcher();

        let get_num_hits = |query| searcher.search(&query, &Count).unwrap();
        let query_from_text = |text: &str| {
            QueryParser::for_index(&index, vec![])
                .parse_query(text)
                .unwrap()
        };

        let gen_query_inclusive = |field: &str, ip_range: &RangeInclusive<Ipv6Addr>| {
            format!("{field}:[{} TO {}]", ip_range.start(), ip_range.end())
        };

        let test_sample = |sample_docs: &[Doc]| {
            let mut ips: Vec<Ipv6Addr> = sample_docs.iter().map(|doc| doc.ip).collect();
            ips.sort();
            let ip_range = ips[0]..=ips[1];
            let expected_num_hits = docs
                .iter()
                .filter(|doc| (ips[0]..=ips[1]).contains(&doc.ip))
                .count();

            let query = gen_query_inclusive("ip", &ip_range);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            let query = gen_query_inclusive("ips", &ip_range);
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            // Intersection search
            let id_filter = sample_docs[0].id.to_string();
            let expected_num_hits = docs
                .iter()
                .filter(|doc| ip_range.contains(&doc.ip) && doc.id == id_filter)
                .count();
            let query = format!(
                "{} AND id:{}",
                gen_query_inclusive("ip", &ip_range),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);

            // Intersection search on multivalue ip field
            let id_filter = sample_docs[0].id.to_string();
            let query = format!(
                "{} AND id:{}",
                gen_query_inclusive("ips", &ip_range),
                &id_filter
            );
            assert_eq!(get_num_hits(query_from_text(&query)), expected_num_hits);
        };

        test_sample(&[docs[0].clone(), docs[0].clone()]);
        if docs.len() > 1 {
            test_sample(&[docs[0].clone(), docs[1].clone()]);
            test_sample(&[docs[1].clone(), docs[1].clone()]);
        }
        if docs.len() > 2 {
            test_sample(&[docs[1].clone(), docs[2].clone()]);
        }

        Ok(())
    }
}