forked from karlseguin/nabu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
344 lines (310 loc) · 7.94 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
package nabu
import (
"github.com/karlseguin/nabu/conditions"
"github.com/karlseguin/nabu/indexes"
"github.com/karlseguin/nabu/key"
"sort"
)
type Query interface {
NoCache() Query
Union(name string, values ...string) Query
Set(name, value string) Query
Where(condition Condition) Query
Desc() Query
Limit(limit int) Query
Offset(offset int) Query
IncludeTotal() Query
Execute() Result
}
// Build and executes a query against the database
type NormalQuery struct {
upto int
limit int
desc bool
offset int
cache bool
db *Database
sortLength int
conditionCount int
includeTotal bool
sortCondition RankedCondition
sort indexes.Ranked
dynamicSort []uint
ranged bool
conditions Conditions
}
// Queries are statically created upfront and reused
func newQuery(db *Database) Query {
q := &NormalQuery{
db: db,
cache: true,
conditions: make(Conditions, db.maxConditionsPerQuery),
}
q.reset()
return q
}
// Filter on a set.
func (q *NormalQuery) Set(indexName, value string) Query {
q.addCondition(conditions.NewSet(indexName, value))
return q
}
// Filter on an a union of set values (tag1 || tag2 || tag3).
func (q *NormalQuery) Union(indexName string, values ...string) Query {
if len(values) == 1 {
return q.Set(indexName, values[0])
}
q.addCondition(conditions.NewUnion(indexName, values))
return q
}
// Filter results for the query and value. Where can be called multiple
// times. Each must have an even number of parameters (indexName, value):
//
// Where(nabu.GT("age", 10))
//
func (q *NormalQuery) Where(condition Condition) Query {
if q.sort != nil && condition.IndexName() == q.sort.Name() {
if ranked, ok := condition.(RankedCondition); ok {
q.sortCondition = ranked
}
} else {
q.addCondition(condition)
}
return q
}
func (q *NormalQuery) addCondition(condition Condition) bool {
if q.conditionCount == q.db.maxConditionsPerQuery {
return false
}
q.conditions[q.conditionCount] = condition
q.conditionCount++
return true
}
// Don't cache the result or use the cache to generate the result
// Caches are incrementally updated as changes come in, so this should
// only be used for one-off queries
func (q *NormalQuery) NoCache() Query {
q.cache = false
return q
}
// Limit the number of documents returned
func (q *NormalQuery) Limit(limit int) Query {
q.limit = limit
if q.limit > q.db.maxLimit {
q.limit = q.db.maxLimit
}
if q.includeTotal == false {
q.upto = q.limit + 1
}
return q
}
// Paging offset to start at
func (q *NormalQuery) Offset(offset int) Query {
q.offset = offset
return q
}
// Sort the documents by descending order
func (q *NormalQuery) Desc() Query {
q.desc = true
return q
}
// By default, a total count of matching document won't be returned.
// Instead, only the results HasMore will be set. Including the total
// count is less efficient (and unecessary for infinite scrolling or
// for requests beyond the first page). The total will be capped at the
// configured MaxTotal
func (q *NormalQuery) IncludeTotal() Query {
q.includeTotal = true
q.upto = q.db.maxTotal
return q
}
// Executes the query, returning a result. The result must be closed
// once you are done with it
func (q *NormalQuery) Execute() Result {
defer q.reset()
conditionCount := q.conditionCount
if q.dynamicSort != nil {
q.prepareConditions()
defer q.conditions[:conditionCount].RUnlock()
return q.findFromDynamicSort()
}
q.sort.RLock()
if q.sortCondition != nil {
q.sortCondition.On(q.sort)
q.sortLength = q.sortCondition.Len()
} else {
q.sortLength = q.sort.Len()
}
q.sort.RUnlock()
if conditionCount == 0 {
return q.findWithNoIndexes()
}
q.prepareConditions()
defer q.conditions[:conditionCount].RUnlock()
return q.execute()
}
// Loads the indexes used by the query
func (q *NormalQuery) prepareConditions() {
conditionCount := q.conditionCount
q.db.LoadIndexes(q.conditions[:conditionCount])
q.conditions[:conditionCount].RLock()
if conditionCount > 1 {
sort.Sort(q.conditions[:conditionCount])
}
}
// Determines wether an index-based query will be used or a sort-based query.
// The choice is based on the type of sort index (whether it can rank documents),
// whether the smallest index fits within the configured maximum unsorted size and,
// whether the smallest index is sufficiently small compared to the sort index.
func (q *NormalQuery) execute() Result {
first := q.conditions[0]
firstLength := first.Len()
if firstLength == 0 {
return EmptyResult
}
if q.sortLength > firstLength*5 && firstLength <= q.db.maxUnsortedSize && first.CanIterate() {
return q.findByIndex()
}
return q.findBySort()
}
// An optimized code path for when no index is provided (just walking through
// a sort index)
func (q *NormalQuery) findWithNoIndexes() Result {
limit := q.limit
result := <-q.db.sortedResults
result.total = -1
var iterator indexes.Iterator
if q.desc {
iterator = q.sort.Backwards()
} else {
iterator = q.sort.Forwards()
}
if q.sortCondition != nil {
iterator.Range(q.sortCondition.Range())
}
iterator.Offset(q.offset)
id := iterator.Current()
for ; id != key.NULL; id = iterator.Next() {
if result.add(id) == limit {
break
}
}
result.hasMore = id != key.NULL && iterator.Next() != key.NULL
iterator.Close()
if q.includeTotal {
result.total = q.sortLength
if result.total > q.upto {
result.total = q.upto
}
}
return result
}
func (q *NormalQuery) findFromDynamicSort() Result {
found := 0
limit := q.limit
conditionCount := q.conditionCount
result := <-q.db.sortedResults
for _, id := range q.dynamicSort {
keyd := key.Type(id)
for j := 0; j < conditionCount; j++ {
if q.conditions[j].Contains(keyd) == false {
goto nomatchdesc
}
}
result.total++
if result.total > q.offset {
if found < limit {
result.add(keyd)
found++
} else if result.total >= q.upto {
break
}
}
nomatchdesc:
}
result.hasMore = result.total > (q.offset + q.limit)
if q.includeTotal == false {
result.total = -1
}
return result
}
// Walk the sort index and filter out results
func (q *NormalQuery) findBySort() Result {
found := 0
limit := q.limit
conditionCount := q.conditionCount
var iterator indexes.Iterator
result := <-q.db.sortedResults
if q.desc {
iterator = q.sort.Backwards()
} else {
iterator = q.sort.Forwards()
}
if q.sortCondition != nil {
iterator.Range(q.sortCondition.Range()).Offset(0)
}
for id := iterator.Current(); id != key.NULL; id = iterator.Next() {
for j := 0; j < conditionCount; j++ {
if q.conditions[j].Contains(id) == false {
goto nomatchdesc
}
}
result.total++
if result.total > q.offset {
if found < limit {
result.add(id)
found++
} else if result.total >= q.upto {
break
}
}
nomatchdesc:
}
iterator.Close()
result.hasMore = result.total > (q.offset + q.limit)
if q.includeTotal == false {
result.total = -1
}
return result
}
// Filter by indexes, then sort. Ideal when the smallest index is quite a bit
// smaller than the sort index
func (q *NormalQuery) findByIndex() Result {
conditionCount := q.conditionCount
result := <-q.db.unsortedResults
var sort RankedContainer
if q.sortCondition != nil {
q.sortCondition.On(q.sort)
sort = q.sortCondition
} else {
sort = q.sort
}
iterator := q.conditions[0].Iterator()
defer iterator.Close()
for id := iterator.Current(); id != key.NULL; id = iterator.Next() {
for j := 1; j < conditionCount; j++ {
if q.conditions[j].Contains(id) == false {
goto nomatch
}
}
if score, exists := sort.Score(id); exists {
result.add(id, score)
}
nomatch:
}
return result.finalize(q)
}
// Reset the query and release it back into the pool
func (q *NormalQuery) reset() {
q.sort = nil
q.offset = 0
q.cache = true
q.desc = false
q.ranged = false
q.dynamicSort = nil
q.conditionCount = 0
q.sortCondition = nil
q.includeTotal = false
q.limit = q.db.defaultLimit
q.upto = q.db.defaultLimit + 1
q.db.queryPool <- q
}