-
Notifications
You must be signed in to change notification settings - Fork 1
/
predicates.go
653 lines (531 loc) · 14.5 KB
/
predicates.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
/*
* Copyright (C) 2023 Intergral GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package parquetquery
import (
"bytes"
"fmt"
"regexp"
"strings"
"sync"
pq "github.com/segmentio/parquet-go"
)
// Predicate is a pushdown predicate that can be applied at
// the chunk, page, and value levels.
type Predicate interface {
fmt.Stringer
KeepColumnChunk(cc pq.ColumnChunk) bool
KeepPage(page pq.Page) bool
KeepValue(pq.Value) bool
}
// StringInPredicate checks for any of the given strings.
// Case sensitive exact byte matching
type StringInPredicate struct {
ss [][]byte
helper DictionaryPredicateHelper
}
var _ Predicate = (*StringInPredicate)(nil)
func NewStringInPredicate(ss []string) Predicate {
p := &StringInPredicate{
ss: make([][]byte, len(ss)),
}
for i := range ss {
p.ss[i] = []byte(ss[i])
}
return p
}
func (p *StringInPredicate) String() string {
var str string
for _, s := range p.ss {
str += fmt.Sprintf("%s, ", string(s))
}
return fmt.Sprintf("StringInPredicate{%s}", str)
}
func (p *StringInPredicate) KeepColumnChunk(cc pq.ColumnChunk) bool {
p.helper.setNewRowGroup()
if ci := cc.ColumnIndex(); ci != nil {
for _, subs := range p.ss {
for i := 0; i < ci.NumPages(); i++ {
ok := bytes.Compare(ci.MinValue(i).ByteArray(), subs) <= 0 && bytes.Compare(ci.MaxValue(i).ByteArray(), subs) >= 0
if ok {
// At least one page in this chunk matches
return true
}
}
}
return false
}
return true
}
func (p *StringInPredicate) KeepValue(v pq.Value) bool {
ba := v.ByteArray()
for _, ss := range p.ss {
if bytes.Equal(ba, ss) {
return true
}
}
return false
}
func (p *StringInPredicate) KeepPage(page pq.Page) bool {
//
// todo: check bounds
return p.helper.keepPage(page, p.KeepValue)
}
// RegexInPredicate checks for match against any of the given regexs.
// Memoized and resets on each row group.
type RegexNotInPredicate struct {
regs []*regexp.Regexp
matches map[string]bool
helper DictionaryPredicateHelper
}
var _ Predicate = (*RegexNotInPredicate)(nil)
func NewRegexNotInPredicate(regs []string) (*RegexNotInPredicate, error) {
p := &RegexNotInPredicate{
regs: make([]*regexp.Regexp, 0, len(regs)),
matches: make(map[string]bool),
}
for _, reg := range regs {
r, err := regexp.Compile(reg)
if err != nil {
return nil, err
}
p.regs = append(p.regs, r)
}
return p, nil
}
func (p *RegexNotInPredicate) String() string {
var str string
for _, s := range p.regs {
str += fmt.Sprintf("%s, ", s.String())
}
return fmt.Sprintf("RegexNotInPredicate{%s}", str)
}
func (p *RegexNotInPredicate) keep(v *pq.Value) bool {
if v.IsNull() {
// Null
return false
}
s := v.String()
if matched, ok := p.matches[s]; ok {
return matched
}
matched := false
for _, r := range p.regs {
if !r.MatchString(s) {
matched = true
break
}
}
p.matches[s] = matched
return matched
}
func (p *RegexNotInPredicate) KeepColumnChunk(pq.ColumnChunk) bool {
p.helper.setNewRowGroup()
// Reset match cache on each row group change
p.matches = make(map[string]bool, len(p.matches))
// Can we do any filtering here?
return true
}
func (p *RegexNotInPredicate) KeepValue(v pq.Value) bool {
return p.keep(&v)
}
func (p *RegexNotInPredicate) KeepPage(page pq.Page) bool {
return p.helper.keepPage(page, p.KeepValue)
}
// RegexInPredicate checks for match against any of the given regexs.
// Memoized and resets on each row group.
type RegexInPredicate struct {
regs []*regexp.Regexp
matches map[string]bool
helper DictionaryPredicateHelper
}
var _ Predicate = (*RegexInPredicate)(nil)
func NewRegexInPredicate(regs []string) (*RegexInPredicate, error) {
p := &RegexInPredicate{
regs: make([]*regexp.Regexp, 0, len(regs)),
matches: make(map[string]bool),
}
for _, reg := range regs {
r, err := regexp.Compile(reg)
if err != nil {
return nil, err
}
p.regs = append(p.regs, r)
}
return p, nil
}
func (p *RegexInPredicate) String() string {
var str string
for _, s := range p.regs {
str += fmt.Sprintf("%s, ", s.String())
}
return fmt.Sprintf("RegexInPredicate{%s}", str)
}
func (p *RegexInPredicate) keep(v *pq.Value) bool {
if v.IsNull() {
// Null
return false
}
s := v.String()
if matched, ok := p.matches[s]; ok {
return matched
}
matched := false
for _, r := range p.regs {
if r.MatchString(s) {
matched = true
break
}
}
p.matches[s] = matched
return matched
}
func (p *RegexInPredicate) KeepColumnChunk(pq.ColumnChunk) bool {
p.helper.setNewRowGroup()
// Reset match cache on each row group change
p.matches = make(map[string]bool, len(p.matches))
// Can we do any filtering here?
return true
}
func (p *RegexInPredicate) KeepValue(v pq.Value) bool {
return p.keep(&v)
}
func (p *RegexInPredicate) KeepPage(page pq.Page) bool {
return p.helper.keepPage(page, p.KeepValue)
}
type SubstringPredicate struct {
substring string
matches map[string]bool
helper DictionaryPredicateHelper
}
var _ Predicate = (*SubstringPredicate)(nil)
func NewSubstringPredicate(substring string) *SubstringPredicate {
return &SubstringPredicate{
substring: substring,
matches: map[string]bool{},
}
}
func (p *SubstringPredicate) String() string {
return fmt.Sprintf("SubstringPredicate{%s}", p.substring)
}
func (p *SubstringPredicate) KeepColumnChunk(pq.ColumnChunk) bool {
p.helper.setNewRowGroup()
// Reset match cache on each row group change
p.matches = make(map[string]bool, len(p.matches))
// Is there any filtering possible here?
// Column chunk contains a bloom filter and min/max bounds,
// but those can't be inspected for a substring match.
return true
}
func (p *SubstringPredicate) KeepValue(v pq.Value) bool {
vs := v.String()
if m, ok := p.matches[vs]; ok {
return m
}
m := strings.Contains(vs, p.substring)
p.matches[vs] = m
return m
}
func (p *SubstringPredicate) KeepPage(page pq.Page) bool {
return p.helper.keepPage(page, p.KeepValue)
}
// IntBetweenPredicate checks for int between the bounds [min,max] inclusive
type IntBetweenPredicate struct {
min, max int64
}
var _ Predicate = (*IntBetweenPredicate)(nil)
func NewIntBetweenPredicate(min, max int64) *IntBetweenPredicate {
return &IntBetweenPredicate{min, max}
}
func (p *IntBetweenPredicate) String() string {
return fmt.Sprintf("IntBetweenPredicate{%d,%d}", p.min, p.max)
}
func (p *IntBetweenPredicate) KeepColumnChunk(c pq.ColumnChunk) bool {
if ci := c.ColumnIndex(); ci != nil {
for i := 0; i < ci.NumPages(); i++ {
min := ci.MinValue(i).Int64()
max := ci.MaxValue(i).Int64()
if p.max >= min && p.min <= max {
return true
}
}
return false
}
return true
}
func (p *IntBetweenPredicate) KeepValue(v pq.Value) bool {
vv := v.Int64()
return p.min <= vv && vv <= p.max
}
func (p *IntBetweenPredicate) KeepPage(page pq.Page) bool {
if min, max, ok := page.Bounds(); ok {
return p.max >= min.Int64() && p.min <= max.Int64()
}
return true
}
// Generic predicate with callbacks to evalulate data of type T
// Fn evalulates a single data point and is required. Optionally,
// a RangeFn can evalulate a min/max range and is used to
// skip column chunks and pages when RangeFn is supplied and
// the column chunk or page also include bounds metadata.
type GenericPredicate[T any] struct {
Fn func(T) bool
RangeFn func(min, max T) bool
Extract func(pq.Value) T
helper DictionaryPredicateHelper
}
var _ Predicate = (*GenericPredicate[int64])(nil)
func NewGenericPredicate[T any](fn func(T) bool, rangeFn func(T, T) bool, extract func(pq.Value) T) *GenericPredicate[T] {
return &GenericPredicate[T]{Fn: fn, RangeFn: rangeFn, Extract: extract}
}
func (p *GenericPredicate[T]) String() string {
return "GenericPredicate{}"
}
func (p *GenericPredicate[T]) KeepColumnChunk(c pq.ColumnChunk) bool {
p.helper.setNewRowGroup()
if p.RangeFn == nil {
return true
}
if ci := c.ColumnIndex(); ci != nil {
for i := 0; i < ci.NumPages(); i++ {
min := p.Extract(ci.MinValue(i))
max := p.Extract(ci.MaxValue(i))
if p.RangeFn(min, max) {
return true
}
}
return false
}
return true
}
func (p *GenericPredicate[T]) KeepPage(page pq.Page) bool {
if p.RangeFn != nil {
if min, max, ok := page.Bounds(); ok {
return p.RangeFn(p.Extract(min), p.Extract(max))
}
}
return p.helper.keepPage(page, p.KeepValue)
}
func (p *GenericPredicate[T]) KeepValue(v pq.Value) bool {
return p.Fn(p.Extract(v))
}
func NewIntPredicate(fn func(int64) bool, rangeFn func(int64, int64) bool) *GenericPredicate[int64] {
return NewGenericPredicate(
fn, rangeFn,
func(v pq.Value) int64 { return v.Int64() },
)
}
func NewFloatPredicate(fn func(float64) bool, rangeFn func(float64, float64) bool) *GenericPredicate[float64] {
return NewGenericPredicate(
fn, rangeFn,
func(v pq.Value) float64 { return v.Double() },
)
}
func NewBoolPredicate(b bool) *GenericPredicate[bool] {
return NewGenericPredicate(
func(v bool) bool { return v == b },
nil,
func(v pq.Value) bool { return v.Boolean() },
)
}
type FloatBetweenPredicate struct {
min, max float64
}
var _ Predicate = (*FloatBetweenPredicate)(nil)
func NewFloatBetweenPredicate(min, max float64) *FloatBetweenPredicate {
return &FloatBetweenPredicate{min, max}
}
func (p *FloatBetweenPredicate) String() string {
return fmt.Sprintf("FloatBetweenPredicate{%f,%f}", p.min, p.max)
}
func (p *FloatBetweenPredicate) KeepColumnChunk(c pq.ColumnChunk) bool {
if ci := c.ColumnIndex(); ci != nil {
for i := 0; i < ci.NumPages(); i++ {
min := ci.MinValue(i).Double()
max := ci.MaxValue(i).Double()
if p.max >= min && p.min <= max {
return true
}
}
return false
}
return true
}
func (p *FloatBetweenPredicate) KeepValue(v pq.Value) bool {
vv := v.Double()
return p.min <= vv && vv <= p.max
}
func (p *FloatBetweenPredicate) KeepPage(page pq.Page) bool {
if min, max, ok := page.Bounds(); ok {
return p.max >= min.Double() && p.min <= max.Double()
}
return true
}
type OrPredicate struct {
preds []Predicate
}
var _ Predicate = (*OrPredicate)(nil)
func NewOrPredicate(preds ...Predicate) *OrPredicate {
return &OrPredicate{
preds: preds,
}
}
func (p *OrPredicate) String() string {
var preds string
for _, pred := range p.preds {
preds += pred.String() + ","
}
return fmt.Sprintf("OrPredicate{%s}", p.preds)
}
func (p *OrPredicate) KeepColumnChunk(c pq.ColumnChunk) bool {
ret := false
for _, p := range p.preds {
if p == nil {
// Nil means all values are returned
ret = ret || true
continue
}
if p.KeepColumnChunk(c) {
ret = ret || true
}
}
return ret
}
func (p *OrPredicate) KeepPage(page pq.Page) bool {
for _, p := range p.preds {
if p == nil {
// Nil means all values are returned
return true
}
if p.KeepPage(page) {
return true
}
}
return false
}
func (p *OrPredicate) KeepValue(v pq.Value) bool {
for _, p := range p.preds {
if p == nil {
// Nil means all values are returned
return true
}
if p.KeepValue(v) {
return true
}
}
return false
}
type InstrumentedPredicate struct {
pred Predicate // Optional, if missing then just keeps metrics with no filtering
InspectedColumnChunks int64
InspectedPages int64
InspectedValues int64
KeptColumnChunks int64
KeptPages int64
KeptValues int64
}
var _ Predicate = (*InstrumentedPredicate)(nil)
func (p *InstrumentedPredicate) String() string {
if p.pred == nil {
return fmt.Sprintf("InstrumentedPredicate{%d, nil}", p.InspectedValues)
}
return fmt.Sprintf("InstrumentedPredicate{%d, %s}", p.InspectedValues, p.pred)
}
func (p *InstrumentedPredicate) KeepColumnChunk(c pq.ColumnChunk) bool {
p.InspectedColumnChunks++
if p.pred == nil || p.pred.KeepColumnChunk(c) {
p.KeptColumnChunks++
return true
}
return false
}
func (p *InstrumentedPredicate) KeepPage(page pq.Page) bool {
p.InspectedPages++
if p.pred == nil || p.pred.KeepPage(page) {
p.KeptPages++
return true
}
return false
}
func (p *InstrumentedPredicate) KeepValue(v pq.Value) bool {
p.InspectedValues++
if p.pred == nil || p.pred.KeepValue(v) {
p.KeptValues++
return true
}
return false
}
// DictionaryPredicateHelper is a helper for a predicate that uses a dictionary
// for filtering.
//
// There is one dictionary per ColumnChunk/RowGroup, but it is not accessible in
// KeepColumnChunk. This helper saves the result of KeepPage and uses it for
// all pages in the row group. It also has a basic heuristic for choosing not
// to check the dictionary at all if the cardinality is too high.
type DictionaryPredicateHelper struct {
newRowGroup bool
keepPagesInRowGroup bool
// this helper can be accessed from multiple go routines at a time. Which causes race failures.
// temporarily add this lock until the whole parquet usage can be overhauled.
mu sync.Mutex
}
func (d *DictionaryPredicateHelper) setNewRowGroup() {
d.mu.Lock()
defer d.mu.Unlock()
d.newRowGroup = true
}
func (d *DictionaryPredicateHelper) keepPage(page pq.Page, keepValue func(pq.Value) bool) bool {
d.mu.Lock()
defer d.mu.Unlock()
if !d.newRowGroup {
return d.keepPagesInRowGroup
}
d.newRowGroup = false
d.keepPagesInRowGroup = true
// If a dictionary column then ensure at least one matching
// value exists in the dictionary
dict := page.Dictionary()
if dict == nil {
return d.keepPagesInRowGroup
}
l := dict.Len()
d.keepPagesInRowGroup = false
for i := 0; i < l; i++ {
dictionaryEntry := dict.Index(int32(i))
if keepValue(dictionaryEntry) {
d.keepPagesInRowGroup = true
break
}
}
return d.keepPagesInRowGroup
}
type SkipNilsPredicate struct{}
var _ Predicate = (*SkipNilsPredicate)(nil)
func NewSkipNilsPredicate() *SkipNilsPredicate {
return &SkipNilsPredicate{}
}
func (p *SkipNilsPredicate) String() string {
return "SkipNilsPredicate{}"
}
func (p *SkipNilsPredicate) KeepColumnChunk(pq.ColumnChunk) bool {
return true
}
func (p *SkipNilsPredicate) KeepPage(page pq.Page) bool {
return page.NumValues() > page.NumNulls()
}
func (p *SkipNilsPredicate) KeepValue(v pq.Value) bool {
return !v.IsNull()
}