forked from dgraph-io/dgraph
/
groupby.go
331 lines (307 loc) · 7.78 KB
/
groupby.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
/*
* Copyright (C) 2017 Dgraph Labs, Inc. and Contributors
*
* 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 <http://www.gnu.org/licenses/>.
*/
package query
import (
"fmt"
"sort"
"strconv"
"github.com/dgraph-io/dgraph/algo"
"github.com/dgraph-io/dgraph/protos/intern"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/x"
)
type groupPair struct {
key types.Val
attr string
alias string
}
type groupResult struct {
keys []groupPair
aggregates []groupPair
uids []uint64
}
func (grp *groupResult) aggregateChild(child *SubGraph) error {
fieldName := child.Params.Alias
if child.Params.DoCount {
if child.Attr != "uid" {
return x.Errorf("Only uid predicate is allowed in count within groupby")
}
if fieldName == "" {
fieldName = "count"
}
grp.aggregates = append(grp.aggregates, groupPair{
attr: fieldName,
key: types.Val{
Tid: types.IntID,
Value: int64(len(grp.uids)),
},
})
return nil
}
if child.SrcFunc != nil && isAggregatorFn(child.SrcFunc.Name) {
if fieldName == "" {
fieldName = fmt.Sprintf("%s(%s)", child.SrcFunc.Name, child.Attr)
}
finalVal, err := aggregateGroup(grp, child)
if err != nil {
return err
}
grp.aggregates = append(grp.aggregates, groupPair{
attr: fieldName,
key: finalVal,
})
}
return nil
}
type groupResults struct {
group []*groupResult
}
type groupElements struct {
entities *intern.List
key types.Val
}
type uniq struct {
elements map[string]groupElements
attr string
}
type dedup struct {
groups []*uniq
}
func (d *dedup) getGroup(attr string) *uniq {
var res *uniq
// Looping last to first is better in this case.
for i := len(d.groups) - 1; i >= 0; i-- {
it := d.groups[i]
if attr == it.attr {
res = it
break
}
}
if res == nil {
// Create a new entry.
res = &uniq{
attr: attr,
elements: make(map[string]groupElements),
}
d.groups = append(d.groups, res)
}
return res
}
func (d *dedup) addValue(attr string, value types.Val, uid uint64) {
cur := d.getGroup(attr)
// Create the string key.
var strKey string
if value.Tid == types.UidID {
strKey = strconv.FormatUint(value.Value.(uint64), 10)
} else {
valC := types.Val{types.StringID, ""}
err := types.Marshal(value, &valC)
if err != nil {
return
}
strKey = valC.Value.(string)
}
if _, ok := cur.elements[strKey]; !ok {
// If this is the first element of the group.
cur.elements[strKey] = groupElements{
key: value,
entities: &intern.List{make([]uint64, 0)},
}
}
curEntity := cur.elements[strKey].entities
curEntity.Uids = append(curEntity.Uids, uid)
}
func aggregateGroup(grp *groupResult, child *SubGraph) (types.Val, error) {
ag := aggregator{
name: child.SrcFunc.Name,
}
for _, uid := range grp.uids {
idx := sort.Search(len(child.SrcUIDs.Uids), func(i int) bool {
return child.SrcUIDs.Uids[i] >= uid
})
if idx == len(child.SrcUIDs.Uids) || child.SrcUIDs.Uids[idx] != uid {
continue
}
v := child.valueMatrix[idx].Values[0]
val, err := convertWithBestEffort(v, child.Attr)
if err != nil {
continue
}
ag.Apply(val)
}
return ag.Value()
}
// formGroup creates all possible groups with the list of uids that belong to that
// group.
func (res *groupResults) formGroups(dedupMap dedup, cur *intern.List, groupVal []groupPair) {
l := len(groupVal)
if len(dedupMap.groups) == 0 || (l != 0 && len(cur.Uids) == 0) {
// This group is already empty or no group can be formed. So stop.
return
}
if l == len(dedupMap.groups) {
a := make([]uint64, len(cur.Uids))
b := make([]groupPair, len(groupVal))
copy(a, cur.Uids)
copy(b, groupVal)
res.group = append(res.group, &groupResult{
uids: a,
keys: b,
})
return
}
for _, v := range dedupMap.groups[l].elements {
temp := new(intern.List)
groupVal = append(groupVal, groupPair{
key: v.key,
attr: dedupMap.groups[l].attr,
})
if l != 0 {
algo.IntersectWith(cur, v.entities, temp)
} else {
temp.Uids = make([]uint64, len(v.entities.Uids))
copy(temp.Uids, v.entities.Uids)
}
res.formGroups(dedupMap, temp, groupVal)
groupVal = groupVal[:len(groupVal)-1]
}
}
func (sg *SubGraph) processGroupBy(doneVars map[string]varValue, path []*SubGraph) error {
var dedupMap dedup
var pathNode *SubGraph
for _, child := range sg.Children {
// Find a better name for ignoreResult.
// Aggregation children would be skipped because of this condition.
if !child.Params.ignoreResult {
continue
}
attr := child.Params.Alias
if attr == "" {
attr = child.Attr
}
if len(child.DestUIDs.Uids) != 0 {
// It's a UID node.
for i := 0; i < len(child.uidMatrix); i++ {
srcUid := child.SrcUIDs.Uids[i]
ul := child.uidMatrix[i]
for _, uid := range ul.Uids {
dedupMap.addValue(attr, types.Val{Tid: types.UidID, Value: uid}, srcUid)
}
}
pathNode = child
} else {
// It's a value node.
for i, v := range child.valueMatrix {
srcUid := child.SrcUIDs.Uids[i]
val, err := convertTo(v.Values[0])
if err != nil {
continue
}
dedupMap.addValue(attr, val, srcUid)
}
}
}
// Create all the groups here.
res := new(groupResults)
res.formGroups(dedupMap, &intern.List{}, []groupPair{})
// Go over the groups and aggregate the values.
for _, child := range sg.Children {
if child.Params.ignoreResult {
continue
}
// This is a aggregation node.
for _, grp := range res.group {
err := grp.aggregateChild(child)
if err != nil && err != ErrEmptyVal {
return err
}
}
chVar := child.Params.Var
if chVar != "" {
tempMap := make(map[uint64]types.Val)
for _, grp := range res.group {
if len(grp.keys) == 0 {
continue
}
if len(grp.keys) > 1 {
return x.Errorf("Expected one UID for var in groupby but got: %d", len(grp.keys))
}
uidVal := grp.keys[0].key.Value
uid, ok := uidVal.(uint64)
if !ok {
return x.Errorf("Vars can be assigned only when grouped by UID attribute")
}
// grp.aggregates could be empty if schema conversion failed during aggregation
if len(grp.aggregates) > 0 {
tempMap[uid] = grp.aggregates[len(grp.aggregates)-1].key
}
}
doneVars[chVar] = varValue{
Vals: tempMap,
path: append(path, pathNode),
}
}
child.Params.ignoreResult = true
}
// Sort to order the groups for determinism.
sort.Slice(res.group, func(i, j int) bool {
return groupLess(res.group[i], res.group[j])
})
sg.GroupbyRes = res
return nil
}
func groupLess(a, b *groupResult) bool {
if len(a.uids) < len(b.uids) {
return true
} else if len(a.uids) != len(b.uids) {
return false
}
if len(a.keys) < len(b.keys) {
return true
} else if len(a.keys) != len(b.keys) {
return false
}
if len(a.aggregates) < len(b.aggregates) {
return true
} else if len(a.aggregates) != len(b.aggregates) {
return false
}
for i := range a.keys {
l, err := types.Less(a.keys[i].key, b.keys[i].key)
if err == nil {
if l {
return l
}
l, _ = types.Less(b.keys[i].key, a.keys[i].key)
if l {
return !l
}
}
}
for i := range a.aggregates {
if l, err := types.Less(a.aggregates[i].key, b.aggregates[i].key); err == nil {
if l {
return l
}
l, _ = types.Less(b.aggregates[i].key, a.aggregates[i].key)
if l {
return !l
}
}
}
return false
}