-
Notifications
You must be signed in to change notification settings - Fork 126
/
query.go
1482 lines (1257 loc) · 36.2 KB
/
query.go
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
// Copyright (c) 2020 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bluge
import (
"fmt"
"math"
"strings"
"time"
"github.com/blugelabs/bluge/search/similarity"
"github.com/blugelabs/bluge/analysis"
"github.com/blugelabs/bluge/analysis/tokenizer"
"github.com/blugelabs/bluge/numeric"
"github.com/blugelabs/bluge/numeric/geo"
"github.com/blugelabs/bluge/search"
"github.com/blugelabs/bluge/search/searcher"
)
// A Query represents a description of the type
// and parameters for a query into the index.
type Query interface {
Searcher(i search.Reader,
options search.SearcherOptions) (search.Searcher, error)
}
type querySlice []Query
func (s querySlice) searchers(i search.Reader, options search.SearcherOptions) (rv []search.Searcher, err error) {
for _, q := range s {
var sr search.Searcher
sr, err = q.Searcher(i, options)
if err != nil {
// close all the already opened searchers
for _, rvs := range rv {
_ = rvs.Close()
}
return nil, err
}
rv = append(rv, sr)
}
return rv, nil
}
func (s querySlice) disjunction(i search.Reader, options search.SearcherOptions, min int) (search.Searcher, error) {
constituents, err := s.searchers(i, options)
if err != nil {
return nil, err
}
return searcher.NewDisjunctionSearcher(i, constituents, min, similarity.NewCompositeSumScorer(), options)
}
func (s querySlice) conjunction(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
constituents, err := s.searchers(i, options)
if err != nil {
return nil, err
}
return searcher.NewConjunctionSearcher(i, constituents, similarity.NewCompositeSumScorer(), options)
}
type validatableQuery interface {
Query
Validate() error
}
type boost float64
func (b *boost) Value() float64 {
if b == nil {
return 1
}
return float64(*b)
}
type BooleanQuery struct {
musts querySlice
shoulds querySlice
mustNots querySlice
boost *boost
scorer search.CompositeScorer
minShould int
}
// NewBooleanQuery creates a compound Query composed
// of several other Query objects.
// These other query objects are added using the
// AddMust() AddShould() and AddMustNot() methods.
// Result documents must satisfy ALL of the
// must Queries.
// Result documents must satisfy NONE of the must not
// Queries.
// Result documents that ALSO satisfy any of the should
// Queries will score higher.
func NewBooleanQuery() *BooleanQuery {
return &BooleanQuery{}
}
// SetMinShould requires that at least minShould of the
// should Queries must be satisfied.
func (q *BooleanQuery) SetMinShould(minShould int) *BooleanQuery {
q.minShould = minShould
return q
}
func (q *BooleanQuery) AddMust(m ...Query) *BooleanQuery {
q.musts = append(q.musts, m...)
return q
}
// Musts returns the queries that the documents must match
func (q *BooleanQuery) Musts() []Query {
return q.musts
}
func (q *BooleanQuery) AddShould(m ...Query) *BooleanQuery {
q.shoulds = append(q.shoulds, m...)
return q
}
// Shoulds returns queries that the documents may match
func (q *BooleanQuery) Shoulds() []Query {
return q.shoulds
}
func (q *BooleanQuery) AddMustNot(m ...Query) *BooleanQuery {
q.mustNots = append(q.mustNots, m...)
return q
}
// MustNots returns queries that the documents must not match
func (q *BooleanQuery) MustNots() []Query {
return q.mustNots
}
// MinShould returns the minimum number of should queries that need to match
func (q *BooleanQuery) MinShould() int {
return q.minShould
}
func (q *BooleanQuery) SetBoost(b float64) *BooleanQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *BooleanQuery) Boost() float64 {
return q.boost.Value()
}
func (q *BooleanQuery) initPrimarySearchers(i search.Reader, options search.SearcherOptions) (
mustSearcher, shouldSearcher, mustNotSearcher search.Searcher, err error) {
if len(q.mustNots) > 0 {
mustNotSearcher, err = q.mustNots.disjunction(i, options, 1)
if err != nil {
return nil, nil, nil, err
}
}
if len(q.musts) > 0 {
mustSearcher, err = q.musts.conjunction(i, options)
if err != nil {
if mustNotSearcher != nil {
_ = mustNotSearcher.Close()
}
return nil, nil, nil, err
}
}
if len(q.shoulds) > 0 {
shouldSearcher, err = q.shoulds.disjunction(i, options, q.minShould)
if err != nil {
if mustNotSearcher != nil {
_ = mustNotSearcher.Close()
}
if mustSearcher != nil {
_ = mustSearcher.Close()
}
return nil, nil, nil, err
}
}
return mustSearcher, shouldSearcher, mustNotSearcher, nil
}
func (q *BooleanQuery) Searcher(i search.Reader, options search.SearcherOptions) (rv search.Searcher, err error) {
mustSearcher, shouldSearcher, mustNotSearcher, err := q.initPrimarySearchers(i, options)
if err != nil {
return nil, err
}
mustSearcher = replaceMatchNoneWithNil(mustSearcher)
shouldSearcher = replaceMatchNoneWithNil(shouldSearcher)
mustNotSearcher = replaceMatchNoneWithNil(mustNotSearcher)
if mustSearcher == nil && shouldSearcher == nil && mustNotSearcher == nil {
// if all 3 are nil, return MatchNone
return searcher.NewMatchNoneSearcher(i, options)
// } else if mustSearcher == nil && shouldSearcher != nil && mustNotSearcher == nil {
// DISABLED optimization, if only should searcher, just return it instead
// While logically correct, returning the shouldSearcher looses the desired boost.
// return shouldSearcher, nil
} else if mustSearcher == nil && shouldSearcher == nil && mustNotSearcher != nil {
// if only mustNotSearcher, start with MatchAll
var err error
mustSearcher, err = searcher.NewMatchAllSearcher(i, 1, similarity.ConstantScorer(1), options)
if err != nil {
return nil, err
}
}
if q.scorer == nil {
q.scorer = similarity.NewCompositeSumScorerWithBoost(q.boost.Value())
}
return searcher.NewBooleanSearcher(mustSearcher, shouldSearcher, mustNotSearcher, q.scorer, options)
}
func replaceMatchNoneWithNil(s search.Searcher) search.Searcher {
if _, ok := s.(*searcher.MatchNoneSearcher); ok {
return nil
}
return s
}
func (q *BooleanQuery) Validate() error {
if len(q.musts) > 0 {
for _, mq := range q.musts {
if mq, ok := mq.(validatableQuery); ok {
err := mq.Validate()
if err != nil {
return err
}
}
}
}
if len(q.shoulds) > 0 {
for _, sq := range q.shoulds {
if sq, ok := sq.(validatableQuery); ok {
err := sq.Validate()
if err != nil {
return err
}
}
}
}
if len(q.mustNots) > 0 {
for _, mnq := range q.mustNots {
if mnq, ok := mnq.(validatableQuery); ok {
err := mnq.Validate()
if err != nil {
return err
}
}
}
}
if len(q.musts) == 0 && len(q.shoulds) == 0 && len(q.mustNots) == 0 {
return fmt.Errorf("boolean query must contain at least one must or should or not must clause")
}
return nil
}
type DateRangeQuery struct {
start time.Time
end time.Time
inclusiveStart bool
inclusiveEnd bool
field string
boost *boost
scorer search.Scorer
}
// NewDateRangeQuery creates a new Query for ranges
// of date values.
// Date strings are parsed using the DateTimeParser configured in the
// top-level config.QueryDateTimeParser
// Either, but not both endpoints can be nil.
func NewDateRangeQuery(start, end time.Time) *DateRangeQuery {
return NewDateRangeInclusiveQuery(start, end, true, false)
}
// NewDateRangeInclusiveQuery creates a new Query for ranges
// of date values.
// Date strings are parsed using the DateTimeParser configured in the
// top-level config.QueryDateTimeParser
// Either, but not both endpoints can be nil.
// startInclusive and endInclusive control inclusion of the endpoints.
func NewDateRangeInclusiveQuery(start, end time.Time, startInclusive, endInclusive bool) *DateRangeQuery {
return &DateRangeQuery{
start: start,
end: end,
inclusiveStart: startInclusive,
inclusiveEnd: endInclusive,
}
}
// Start returns the date range start and if the start is included in the query
func (q *DateRangeQuery) Start() (time.Time, bool) {
return q.start, q.inclusiveStart
}
// End returns the date range end and if the end is included in the query
func (q *DateRangeQuery) End() (time.Time, bool) {
return q.end, q.inclusiveEnd
}
func (q *DateRangeQuery) SetBoost(b float64) *DateRangeQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *DateRangeQuery) Boost() float64 {
return q.boost.Value()
}
func (q *DateRangeQuery) SetField(f string) *DateRangeQuery {
q.field = f
return q
}
func (q *DateRangeQuery) Field() string {
return q.field
}
func (q *DateRangeQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
min, max, err := q.parseEndpoints()
if err != nil {
return nil, err
}
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
if q.scorer == nil {
q.scorer = similarity.ConstantScorer(1)
}
return searcher.NewNumericRangeSearcher(i, min, max, q.inclusiveStart, q.inclusiveEnd, field,
q.boost.Value(), q.scorer, similarity.NewCompositeSumScorer(), options)
}
func (q *DateRangeQuery) parseEndpoints() (min, max float64, err error) {
min = math.Inf(-1)
max = math.Inf(1)
if !q.start.IsZero() {
if !isDatetimeCompatible(q.start) {
// overflow
return 0, 0, fmt.Errorf("invalid/unsupported date range, start: %v", q.start)
}
startInt64 := q.start.UnixNano()
min = numeric.Int64ToFloat64(startInt64)
}
if !q.end.IsZero() {
if !isDatetimeCompatible(q.end) {
// overflow
return 0, 0, fmt.Errorf("invalid/unsupported date range, end: %v", q.end)
}
endInt64 := q.end.UnixNano()
max = numeric.Int64ToFloat64(endInt64)
}
return min, max, nil
}
func (q *DateRangeQuery) Validate() error {
if q.start.IsZero() && q.end.IsZero() {
return fmt.Errorf("must specify start or end")
}
_, _, err := q.parseEndpoints()
if err != nil {
return err
}
return nil
}
func isDatetimeCompatible(t time.Time) bool {
if t.Before(time.Unix(0, math.MinInt64)) || t.After(time.Unix(0, math.MaxInt64)) {
return false
}
return true
}
type FuzzyQuery struct {
term string
prefix int
fuzziness int
field string
boost *boost
scorer search.Scorer
}
// NewFuzzyQuery creates a new Query which finds
// documents containing terms within a specific
// fuzziness of the specified term.
// The default fuzziness is 1.
//
// The current implementation uses Levenshtein edit
// distance as the fuzziness metric.
func NewFuzzyQuery(term string) *FuzzyQuery {
return &FuzzyQuery{
term: term,
fuzziness: 1,
}
}
// Term returns the term being queried
func (q *FuzzyQuery) Term() string {
return q.term
}
// PrefixLen returns the prefix match value
func (q *FuzzyQuery) Prefix() int {
return q.prefix
}
// Fuzziness returns the fuzziness of the query
func (q *FuzzyQuery) Fuzziness() int {
return q.fuzziness
}
func (q *FuzzyQuery) SetBoost(b float64) *FuzzyQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *FuzzyQuery) Boost() float64 {
return q.boost.Value()
}
func (q *FuzzyQuery) SetField(f string) *FuzzyQuery {
q.field = f
return q
}
func (q *FuzzyQuery) Field() string {
return q.field
}
func (q *FuzzyQuery) SetFuzziness(f int) *FuzzyQuery {
q.fuzziness = f
return q
}
func (q *FuzzyQuery) SetPrefix(p int) *FuzzyQuery {
q.prefix = p
return q
}
func (q *FuzzyQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
return searcher.NewFuzzySearcher(i, q.term, q.prefix, q.fuzziness, field, q.boost.Value(),
q.scorer, similarity.NewCompositeSumScorer(), options)
}
type GeoBoundingBoxQuery struct {
topLeft []float64
bottomRight []float64
field string
boost *boost
scorer search.Scorer
}
// NewGeoBoundingBoxQuery creates a new Query for performing geo bounding
// box searches. The arguments describe the position of the box and documents
// which have an indexed geo point inside the box will be returned.
func NewGeoBoundingBoxQuery(topLeftLon, topLeftLat, bottomRightLon, bottomRightLat float64) *GeoBoundingBoxQuery {
return &GeoBoundingBoxQuery{
topLeft: []float64{topLeftLon, topLeftLat},
bottomRight: []float64{bottomRightLon, bottomRightLat},
}
}
// TopLeft returns the start corner of the bounding box
func (q *GeoBoundingBoxQuery) TopLeft() []float64 {
return q.topLeft
}
// BottomRight returns the end cornder of the bounding box
func (q *GeoBoundingBoxQuery) BottomRight() []float64 {
return q.bottomRight
}
func (q *GeoBoundingBoxQuery) SetBoost(b float64) *GeoBoundingBoxQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *GeoBoundingBoxQuery) Boost() float64 {
return q.boost.Value()
}
func (q *GeoBoundingBoxQuery) SetField(f string) *GeoBoundingBoxQuery {
q.field = f
return q
}
func (q *GeoBoundingBoxQuery) Field() string {
return q.field
}
const (
minLon = -180
maxLon = 180
)
func (q *GeoBoundingBoxQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
if q.scorer == nil {
q.scorer = similarity.ConstantScorer(1)
}
if q.bottomRight[0] < q.topLeft[0] {
// cross date line, rewrite as two parts
leftSearcher, err := searcher.NewGeoBoundingBoxSearcher(i,
minLon, q.bottomRight[1], q.bottomRight[0], q.topLeft[1],
field, q.boost.Value(), q.scorer, similarity.NewCompositeSumScorer(),
options, true, geoPrecisionStep)
if err != nil {
return nil, err
}
rightSearcher, err := searcher.NewGeoBoundingBoxSearcher(i,
q.topLeft[0], q.bottomRight[1], maxLon, q.topLeft[1],
field, q.boost.Value(), q.scorer, similarity.NewCompositeSumScorer(),
options, true, geoPrecisionStep)
if err != nil {
_ = leftSearcher.Close()
return nil, err
}
return searcher.NewDisjunctionSearcher(i, []search.Searcher{leftSearcher, rightSearcher},
0, similarity.NewCompositeSumScorer(), options)
}
return searcher.NewGeoBoundingBoxSearcher(i, q.topLeft[0], q.bottomRight[1], q.bottomRight[0], q.topLeft[1],
field, q.boost.Value(), q.scorer, similarity.NewCompositeSumScorer(),
options, true, geoPrecisionStep)
}
func (q *GeoBoundingBoxQuery) Validate() error {
return nil
}
type GeoDistanceQuery struct {
location []float64
distance string
field string
boost *boost
scorer search.Scorer
}
// NewGeoDistanceQuery creates a new Query for performing geo distance
// searches. The arguments describe a position and a distance. Documents
// which have an indexed geo point which is less than or equal to the provided
// distance from the given position will be returned.
func NewGeoDistanceQuery(lon, lat float64, distance string) *GeoDistanceQuery {
return &GeoDistanceQuery{
location: []float64{lon, lat},
distance: distance,
}
}
// Location returns the location being queried
func (q *GeoDistanceQuery) Location() []float64 {
return q.location
}
// Distance returns the distance being queried
func (q *GeoDistanceQuery) Distance() string {
return q.distance
}
func (q *GeoDistanceQuery) SetBoost(b float64) *GeoDistanceQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *GeoDistanceQuery) Boost() float64 {
return q.boost.Value()
}
func (q *GeoDistanceQuery) SetField(f string) *GeoDistanceQuery {
q.field = f
return q
}
func (q *GeoDistanceQuery) Field() string {
return q.field
}
func (q *GeoDistanceQuery) Searcher(i search.Reader,
options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
dist, err := geo.ParseDistance(q.distance)
if err != nil {
return nil, err
}
return searcher.NewGeoPointDistanceSearcher(i, q.location[0], q.location[1], dist,
field, q.boost.Value(), q.scorer, similarity.NewCompositeSumScorer(), options, geoPrecisionStep)
}
func (q *GeoDistanceQuery) Validate() error {
return nil
}
type GeoBoundingPolygonQuery struct {
points []geo.Point
field string
boost *boost
scorer search.Scorer
}
// FIXME document like the others
func NewGeoBoundingPolygonQuery(points []geo.Point) *GeoBoundingPolygonQuery {
return &GeoBoundingPolygonQuery{
points: points}
}
// Points returns all the points being queried inside the bounding box
func (q *GeoBoundingPolygonQuery) Points() []geo.Point {
return q.points
}
func (q *GeoBoundingPolygonQuery) SetBoost(b float64) *GeoBoundingPolygonQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *GeoBoundingPolygonQuery) Boost() float64 {
return q.boost.Value()
}
func (q *GeoBoundingPolygonQuery) SetField(f string) *GeoBoundingPolygonQuery {
q.field = f
return q
}
func (q *GeoBoundingPolygonQuery) Field() string {
return q.field
}
func (q *GeoBoundingPolygonQuery) Searcher(i search.Reader,
options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
return searcher.NewGeoBoundedPolygonSearcher(i, q.points, field, q.boost.Value(),
q.scorer, similarity.NewCompositeSumScorer(), options, geoPrecisionStep)
}
func (q *GeoBoundingPolygonQuery) Validate() error {
return nil
}
type MatchAllQuery struct {
boost *boost
}
// NewMatchAllQuery creates a Query which will
// match all documents in the index.
func NewMatchAllQuery() *MatchAllQuery {
return &MatchAllQuery{}
}
func (q *MatchAllQuery) SetBoost(b float64) *MatchAllQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *MatchAllQuery) Boost() float64 {
return q.boost.Value()
}
func (q *MatchAllQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
return searcher.NewMatchAllSearcher(i, q.boost.Value(), similarity.ConstantScorer(1), options)
}
type MatchNoneQuery struct {
boost *boost
}
// NewMatchNoneQuery creates a Query which will not
// match any documents in the index.
func NewMatchNoneQuery() *MatchNoneQuery {
return &MatchNoneQuery{}
}
func (q *MatchNoneQuery) SetBoost(b float64) *MatchNoneQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *MatchNoneQuery) Boost() float64 {
return q.boost.Value()
}
func (q *MatchNoneQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
return searcher.NewMatchNoneSearcher(i, options)
}
type MatchPhraseQuery struct {
matchPhrase string
field string
analyzer *analysis.Analyzer
boost *boost
slop int
}
// NewMatchPhraseQuery creates a new Query object
// for matching phrases in the index.
// An Analyzer is chosen based on the field.
// Input text is analyzed using this analyzer.
// Token terms resulting from this analysis are
// used to build a search phrase. Result documents
// must match this phrase. Queried field must have been indexed with
// IncludeTermVectors set to true.
func NewMatchPhraseQuery(matchPhrase string) *MatchPhraseQuery {
return &MatchPhraseQuery{
matchPhrase: matchPhrase,
}
}
// Phrase returns the phrase being queried
func (q *MatchPhraseQuery) Phrase() string {
return q.matchPhrase
}
func (q *MatchPhraseQuery) SetBoost(b float64) *MatchPhraseQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *MatchPhraseQuery) Boost() float64 {
return q.boost.Value()
}
func (q *MatchPhraseQuery) SetField(f string) *MatchPhraseQuery {
q.field = f
return q
}
func (q *MatchPhraseQuery) Field() string {
return q.field
}
// Slop returns the acceptable distance between tokens
func (q *MatchPhraseQuery) Slop() int {
return q.slop
}
// SetSlop updates the sloppyness of the query
// the phrase terms can be as "dist" terms away from each other
func (q *MatchPhraseQuery) SetSlop(dist int) *MatchPhraseQuery {
q.slop = dist
return q
}
func (q *MatchPhraseQuery) SetAnalyzer(a *analysis.Analyzer) *MatchPhraseQuery {
q.analyzer = a
return q
}
func (q *MatchPhraseQuery) Analyzer() *analysis.Analyzer {
return q.analyzer
}
func (q *MatchPhraseQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
var tokens analysis.TokenStream
if q.analyzer != nil {
tokens = q.analyzer.Analyze([]byte(q.matchPhrase))
} else if options.DefaultAnalyzer != nil {
tokens = options.DefaultAnalyzer.Analyze([]byte(q.matchPhrase))
} else {
tokens = tokenizer.MakeTokenStream([]byte(q.matchPhrase))
}
if len(tokens) > 0 {
phrase := tokenStreamToPhrase(tokens)
phraseQuery := NewMultiPhraseQuery(phrase)
phraseQuery.SetField(field)
phraseQuery.SetBoost(q.boost.Value())
phraseQuery.SetSlop(q.slop)
return phraseQuery.Searcher(i, options)
}
noneQuery := NewMatchNoneQuery()
return noneQuery.Searcher(i, options)
}
func tokenStreamToPhrase(tokens analysis.TokenStream) [][]string {
firstPosition := int(^uint(0) >> 1)
lastPosition := 0
var currPosition int
for _, token := range tokens {
currPosition += token.PositionIncr
if currPosition < firstPosition {
firstPosition = currPosition
}
if currPosition > lastPosition {
lastPosition = currPosition
}
}
phraseLen := lastPosition - firstPosition + 1
if phraseLen > 0 {
rv := make([][]string, phraseLen)
currPosition = 0
for _, token := range tokens {
currPosition += token.PositionIncr
pos := currPosition - firstPosition
rv[pos] = append(rv[pos], string(token.Term))
}
return rv
}
return nil
}
type MatchQueryOperator int
const (
// Document must satisfy AT LEAST ONE of term searches.
MatchQueryOperatorOr = 0
// Document must satisfy ALL of term searches.
MatchQueryOperatorAnd = 1
)
type MatchQuery struct {
match string
field string
analyzer *analysis.Analyzer
boost *boost
prefix int
fuzziness int
operator MatchQueryOperator
}
// NewMatchQuery creates a Query for matching text.
// An Analyzer is chosen based on the field.
// Input text is analyzed using this analyzer.
// Token terms resulting from this analysis are
// used to perform term searches. Result documents
// must satisfy at least one of these term searches.
func NewMatchQuery(match string) *MatchQuery {
return &MatchQuery{
match: match,
operator: MatchQueryOperatorOr,
}
}
// Match returns the term being queried
func (q *MatchQuery) Match() string {
return q.match
}
func (q *MatchQuery) SetBoost(b float64) *MatchQuery {
boostVal := boost(b)
q.boost = &boostVal
return q
}
func (q *MatchQuery) Boost() float64 {
return q.boost.Value()
}
func (q *MatchQuery) SetField(f string) *MatchQuery {
q.field = f
return q
}
func (q *MatchQuery) Field() string {
return q.field
}
func (q *MatchQuery) SetFuzziness(f int) *MatchQuery {
q.fuzziness = f
return q
}
func (q *MatchQuery) Fuzziness() int {
return q.fuzziness
}
func (q *MatchQuery) SetPrefix(p int) *MatchQuery {
q.prefix = p
return q
}
func (q *MatchQuery) Prefix() int {
return q.prefix
}
func (q *MatchQuery) Analyzer() *analysis.Analyzer {
return q.analyzer
}
func (q *MatchQuery) SetAnalyzer(a *analysis.Analyzer) *MatchQuery {
q.analyzer = a
return q
}
func (q *MatchQuery) SetOperator(operator MatchQueryOperator) *MatchQuery {
q.operator = operator
return q
}
func (q *MatchQuery) Operator() MatchQueryOperator {
return q.operator
}
func (q *MatchQuery) Searcher(i search.Reader, options search.SearcherOptions) (search.Searcher, error) {
field := q.field
if q.field == "" {
field = options.DefaultSearchField
}
var tokens analysis.TokenStream
if q.analyzer != nil {
tokens = q.analyzer.Analyze([]byte(q.match))
} else if options.DefaultAnalyzer != nil {
tokens = options.DefaultAnalyzer.Analyze([]byte(q.match))
} else {
tokens = tokenizer.MakeTokenStream([]byte(q.match))
}
if len(tokens) > 0 {
tqs := make([]Query, len(tokens))
if q.fuzziness != 0 {
for i, token := range tokens {
query := NewFuzzyQuery(string(token.Term))
query.SetFuzziness(q.fuzziness)
query.SetPrefix(q.prefix)
query.SetField(field)
query.SetBoost(q.boost.Value())
tqs[i] = query
}
} else {
for i, token := range tokens {
tq := NewTermQuery(string(token.Term))
tq.SetField(field)
tq.SetBoost(q.boost.Value())
tqs[i] = tq
}
}
switch q.operator {
case MatchQueryOperatorOr:
booleanQuery := NewBooleanQuery()
booleanQuery.AddShould(tqs...)
booleanQuery.SetMinShould(1)
booleanQuery.SetBoost(q.boost.Value())
return booleanQuery.Searcher(i, options)
case MatchQueryOperatorAnd:
booleanQuery := NewBooleanQuery()
booleanQuery.AddMust(tqs...)
booleanQuery.SetBoost(q.boost.Value())
return booleanQuery.Searcher(i, options)
default:
return nil, fmt.Errorf("unhandled operator %d", q.operator)