/
query.go
357 lines (271 loc) · 6.73 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
package updog
import (
"fmt"
"math/bits"
"sort"
"strings"
"time"
"github.com/RoaringBitmap/roaring"
)
// Query describes a count query to execute on an index. updog allows you to run
// the equivalent of SQL queries like `SELECT x, y, z, COUNT(*) WHERE ... GROUP BY x, y, z`.
type Query struct {
// Expr is the expression you want to limit your query on. You can use the types ExprEqual, ExprNot,
// ExprAnd and ExprOr to construct your expression.
Expr Expression
// GroupBy is a list of column names you want to group by. The result will then contain the
// results for all available values of all the listed columns for which a non-zero count result
// was determined.
GroupBy []string
groupByFields []groupBy
}
// Execute runs the provided query on the index and returns the query result.
func (idx *Index) Execute(q *Query) (*Result, error) {
if idx.metrics.ExecuteDuration != nil {
defer func(t0 time.Time) {
idx.metrics.ExecuteDuration.Observe(time.Since(t0).Seconds())
}(time.Now())
}
idx.mtx.RLock()
defer idx.mtx.RUnlock()
if err := q.populateGroupBy(q.GroupBy, idx.schema); err != nil {
return nil, err
}
result, err := q.Expr.eval(idx)
if err != nil {
return nil, err
}
return &Result{
Count: result.GetCardinality(),
Groups: q.groupBy(result, idx),
}, nil
}
// Result contains the query result.
type Result struct {
// Count is the total count of rows that matched the query expression.
Count uint64
// Groups contains a list of grouped results. If no GroupBy list was provided
// in the query, this list will be empty.
Groups []ResultGroup
}
// ResultGroup contains a single grouped result.
type ResultGroup struct {
// Fields contains a list of result fields for that group, each field consisting of the
// column name and value.
Fields []ResultField
// Count contains the determined count for the list of result fields.
Count uint64
}
// ResultField contains a single column name and value. It is used in ResultGroup objects.
type ResultField struct {
Column string
Value string
}
type Expression interface {
eval(idx *Index) (*roaring.Bitmap, error)
String() string
cacheKey() uint64
}
func (q *Query) populateGroupBy(columns []string, sch *schema) error {
for _, colName := range columns {
col, ok := sch.Columns[colName]
if !ok {
return fmt.Errorf("column %q not found", colName)
}
gb := groupBy{Column: colName}
for v, valueIdx := range col.Values {
gb.Values = append(gb.Values, groupByValue{
Value: v,
Idx: valueIdx,
})
}
sort.Slice(gb.Values, func(i, j int) bool {
return gb.Values[i].Value < gb.Values[j].Value
})
q.groupByFields = append(q.groupByFields, gb)
}
return nil
}
type resultGroup struct {
fields []ResultField
result *roaring.Bitmap
}
func (q *Query) groupBy(result *roaring.Bitmap, idx *Index) (finalResult []ResultGroup) {
if len(q.groupByFields) == 0 {
return nil
}
resultGroups := []resultGroup{
{result: result},
}
for _, gbf := range q.groupByFields {
var newResultGroups []resultGroup
for _, rg := range resultGroups {
for _, v := range gbf.Values {
vbm, err := idx.values.GetCol(v.Idx)
if err != nil {
continue
}
result := roaring.And(rg.result, vbm)
if result.GetCardinality() == 0 {
continue
}
newResultGroups = append(newResultGroups, resultGroup{
fields: append(rg.fields, ResultField{Column: gbf.Column, Value: v.Value}),
result: result,
})
}
}
resultGroups = newResultGroups
}
for _, rg := range resultGroups {
finalResult = append(finalResult, ResultGroup{
Fields: rg.fields,
Count: rg.result.GetCardinality(),
})
}
return finalResult
}
type groupBy struct {
Column string
Values []groupByValue
}
type groupByValue struct {
Value string
Idx uint64
}
type ExprEqual struct {
Column string
Value string
}
func (e *ExprEqual) eval(idx *Index) (*roaring.Bitmap, error) {
_, ok := idx.schema.Columns[e.Column]
if !ok {
return nil, fmt.Errorf("column %q not found in schema", e.Column)
}
valueIdx := getValueIndex(e.Column, e.Value)
cacheKey := e.cacheKey()
bm, ok := idx.cache.Get(cacheKey)
if ok {
return bm, nil
}
bm, err := idx.values.GetCol(valueIdx)
if err != nil || bm == nil {
bm = roaring.New()
}
idx.cache.Put(cacheKey, bm)
return bm, nil
}
func (e *ExprEqual) String() string {
return fmt.Sprintf("(EQUAL %s %q)", e.Column, e.Value)
}
func (e *ExprEqual) cacheKey() uint64 {
return getValueIndex(e.Column, e.Value)
}
type ExprNot struct {
Expr Expression
}
func (e *ExprNot) eval(idx *Index) (*roaring.Bitmap, error) {
cacheKey := e.cacheKey()
bm, ok := idx.cache.Get(cacheKey)
if ok {
return bm, nil
}
bm, err := e.Expr.eval(idx)
if err != nil {
return nil, err
}
bm = roaring.Flip(bm, 0, uint64(idx.nextRowID))
idx.cache.Put(cacheKey, bm)
return bm, nil
}
func (e *ExprNot) String() string {
return fmt.Sprintf("(NOT %s)", e.Expr.String())
}
const (
maskNot = 0x87A9CD14CAEB50EB
maskAnd = 0xF9F1F5ADCB67A077
maskOr = 0xBFB85A99B03E78E7
)
func (e *ExprNot) cacheKey() uint64 {
return bits.RotateLeft64(e.Expr.cacheKey(), 1) ^ maskNot
}
type ExprAnd struct {
Exprs []Expression
}
func (e *ExprAnd) eval(idx *Index) (*roaring.Bitmap, error) {
var elems []*roaring.Bitmap
cacheKey := e.cacheKey()
bm, ok := idx.cache.Get(cacheKey)
if ok {
return bm, nil
}
for _, e := range e.Exprs {
elem, err := e.eval(idx)
if err != nil {
return nil, err
}
elems = append(elems, elem)
}
bm = roaring.FastAnd(elems...)
idx.cache.Put(cacheKey, bm)
return bm, nil
}
func (e *ExprAnd) String() string {
var buf strings.Builder
buf.WriteString("(AND ")
for idx, expr := range e.Exprs {
if idx > 0 {
buf.WriteString(" ")
}
buf.WriteString(expr.String())
}
buf.WriteString(")")
return buf.String()
}
func (e *ExprAnd) cacheKey() uint64 {
key := uint64(maskAnd)
for _, e := range e.Exprs {
key = key ^ bits.RotateLeft64(e.cacheKey(), 1)
}
return key
}
type ExprOr struct {
Exprs []Expression
}
func (e *ExprOr) eval(idx *Index) (*roaring.Bitmap, error) {
var elems []*roaring.Bitmap
cacheKey := e.cacheKey()
bm, ok := idx.cache.Get(cacheKey)
if ok {
return bm, nil
}
for _, e := range e.Exprs {
elem, err := e.eval(idx)
if err != nil {
return nil, err
}
elems = append(elems, elem)
}
bm = roaring.FastOr(elems...)
idx.cache.Put(cacheKey, bm)
return bm, nil
}
func (e *ExprOr) String() string {
var buf strings.Builder
buf.WriteString("(OR ")
for idx, expr := range e.Exprs {
if idx > 0 {
buf.WriteString(" ")
}
buf.WriteString(expr.String())
}
buf.WriteString(")")
return buf.String()
}
func (e *ExprOr) cacheKey() uint64 {
key := uint64(maskOr)
for _, e := range e.Exprs {
key = key ^ bits.RotateLeft64(e.cacheKey(), 1)
}
return key
}