/
graph.go
879 lines (799 loc) · 24.2 KB
/
graph.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
package elastic
import (
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/bmeg/grip/engine/core"
"github.com/bmeg/grip/gdbi"
"github.com/bmeg/grip/gripql"
"github.com/bmeg/grip/log"
"github.com/bmeg/grip/timestamp"
"github.com/bmeg/grip/util"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/encoding/protojson"
elastic "gopkg.in/olivere/elastic.v5"
)
var excludeData = elastic.NewFetchSourceContext(true).Exclude("data")
// Graph is a graph database backended by elastic search
type Graph struct {
ts *timestamp.Timestamp
client *elastic.Client
graph string
vertexIndex string
edgeIndex string
// Used to batch queries from incoming channels
batchSize int
// Not recommended for production. Refresh the relevant primary and replica shards (not the
// whole index) immediately after the operation occurs, so that the updated
// document appears in search results immediately.
synchronous bool
pageSize int
}
// Compiler returns a query compiler that will use elastic search as a backend
func (es *Graph) Compiler() gdbi.Compiler {
return core.NewCompiler(es, core.IndexStartOptimize) //TODO: probably a better optimizer for vertex label search
}
// GetTimestamp returns the change timestamp of the current graph
func (es *Graph) GetTimestamp() string {
return es.ts.Get(es.graph)
}
// AddEdge adds an edge to the graph, if the id is not "" and in already exists
// in the graph, it is replaced
func (es *Graph) AddEdge(edges []*gdbi.Edge) error {
ctx := context.Background()
bulkRequest := es.client.Bulk()
if es.synchronous {
bulkRequest = bulkRequest.Refresh("true")
}
for _, e := range edges {
if e.ID == "" {
return fmt.Errorf("edge gid cannot be an empty string")
}
pe := PackEdge(e)
script := elastic.NewScript(`ctx._source.gid = params.gid;
ctx._source.label = params.label;
ctx._source.from = params.from;
ctx._source.to = params.to;
ctx._source.data = params.data;`).Params(pe)
req := elastic.NewBulkUpdateRequest().
Index(es.edgeIndex).
Type("edge").
Id(e.ID).
Script(script).
Upsert(pe)
bulkRequest = bulkRequest.Add(req)
}
_, err := bulkRequest.Do(ctx)
if err != nil {
return fmt.Errorf("failed to add edge: %s", err)
}
es.ts.Touch(es.graph)
return nil
}
// AddVertex adds an edge to the graph, if the id is not "" and in already exists
// in the graph, it is replaced
func (es *Graph) AddVertex(vertices []*gdbi.Vertex) error {
ctx := context.Background()
bulkRequest := es.client.Bulk()
if es.synchronous {
bulkRequest = bulkRequest.Refresh("true")
}
for _, v := range vertices {
if v.ID == "" {
return fmt.Errorf("vertex gid cannot be an empty string")
}
pv := PackVertex(v)
script := elastic.NewScript(`ctx._source.gid = params.gid;
ctx._source.label = params.label;
ctx._source.data = params.data;`).Params(pv)
req := elastic.NewBulkUpdateRequest().
Index(es.vertexIndex).
Type("vertex").
Id(v.ID).
Script(script).
Upsert(pv)
bulkRequest = bulkRequest.Add(req)
}
_, err := bulkRequest.Do(ctx)
if err != nil {
return fmt.Errorf("failed to add vertex: %s", err)
}
es.ts.Touch(es.graph)
return nil
}
func (es *Graph) BulkAdd(stream <-chan *gdbi.GraphElement) error {
return util.StreamBatch(stream, 50, es.graph, es.AddVertex, es.AddEdge)
}
// DelEdge deletes edge `eid`
func (es *Graph) DelEdge(eid string) error {
ctx := context.Background()
op := es.client.Delete()
if es.synchronous {
op = op.Refresh("true")
}
_, err := op.Index(es.edgeIndex).Type("edge").Id(eid).Do(ctx)
if err != nil {
return fmt.Errorf("failed to delete edge %s: %s", eid, err)
}
es.ts.Touch(es.graph)
return nil
}
// deleteConnectedEdges deletes edges where `from` or `to` equal `vid`
func (es *Graph) deleteConnectedEdges(vid string) error {
ctx := context.Background()
op := es.client.DeleteByQuery()
if es.synchronous {
op = op.Refresh("true")
}
op = op.Index(es.edgeIndex).Type("edge").Query(
elastic.NewBoolQuery().Should(elastic.NewTermQuery("from", vid), elastic.NewTermQuery("to", vid)),
)
_, err := op.Do(ctx)
if err != nil {
return fmt.Errorf("failed to delete edge(s): %s", err)
}
es.ts.Touch(es.graph)
return nil
}
// DelVertex deletes vertex `vid` and all adjacent edges
func (es *Graph) DelVertex(vid string) error {
ctx := context.Background()
op := es.client.Delete()
if es.synchronous {
op = op.Refresh("true")
}
_, err := op.Index(es.vertexIndex).Type("vertex").Id(vid).Do(ctx)
if err != nil {
return fmt.Errorf("failed to delete vertex %s: %s", vid, err)
}
es.ts.Touch(es.graph)
err = es.deleteConnectedEdges(vid)
if err != nil {
return err
}
return nil
}
// GetEdge gets a specific edge
func (es *Graph) GetEdge(id string, load bool) *gdbi.Edge {
ctx := context.Background()
g := es.client.Get().Index(es.edgeIndex).Id(id)
if !load {
g = g.FetchSource(true).FetchSourceContext(excludeData)
}
res, err := g.Do(ctx)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetEdge")
return nil
}
edge := &gripql.Edge{}
err = protojson.Unmarshal(*res.Source, edge)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetEdge: unmarshal")
return nil
}
o := gdbi.NewElementFromEdge(edge)
o.Loaded = load
return o
}
// GetVertex gets vertex `id`
func (es *Graph) GetVertex(id string, load bool) *gdbi.Vertex {
ctx := context.Background()
g := es.client.Get().Index(es.vertexIndex).Id(id)
if !load {
g = g.FetchSource(true).FetchSourceContext(excludeData)
}
res, err := g.Do(ctx)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetVertex")
return nil
}
vertex := &gripql.Vertex{}
err = protojson.Unmarshal(*res.Source, vertex)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetVertex: unmarshal")
return nil
}
o := gdbi.NewElementFromVertex(vertex)
o.Loaded = load
return o
}
// GetEdgeList produces a channel of all edges in the graph
func (es *Graph) GetEdgeList(ctx context.Context, load bool) <-chan *gdbi.Edge {
o := make(chan *gdbi.Edge, 100)
// 1st goroutine sends individual hits to channel.
hits := make(chan json.RawMessage, es.pageSize)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
defer close(hits)
scroll := es.client.Scroll(es.edgeIndex).Sort("gid", true).Size(es.pageSize)
if !load {
scroll = scroll.FetchSource(true).FetchSourceContext(excludeData)
}
for {
results, err := scroll.Do(ctx)
if err == io.EOF {
return nil // all results retrieved
}
if err != nil {
return fmt.Errorf("scroll call failed: %v", err)
}
// Send the hits to the hits channel
for _, hit := range results.Hits.Hits {
hits <- *hit.Source
}
}
})
// 2nd goroutine receives hits and deserializes them.
g.Go(func() error {
for hit := range hits {
edge := &gripql.Edge{}
err := protojson.Unmarshal(hit, edge)
if err != nil {
return err
}
i := gdbi.NewElementFromEdge(edge)
i.Loaded = load
o <- i
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetEdgeList")
}
}()
return o
}
// GetVertexList produces a channel of all vertices in the graph
func (es *Graph) GetVertexList(ctx context.Context, load bool) <-chan *gdbi.Vertex {
o := make(chan *gdbi.Vertex, es.pageSize)
// 1st goroutine sends individual hits to channel.
hits := make(chan json.RawMessage, es.pageSize)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
defer close(hits)
scroll := es.client.Scroll(es.vertexIndex).Sort("gid", true).Size(es.pageSize)
if !load {
scroll = scroll.FetchSource(true).FetchSourceContext(excludeData)
}
for {
results, err := scroll.Do(ctx)
if err == io.EOF {
return nil // all results retrieved
}
if err != nil {
return fmt.Errorf("scroll call failed: %v", err)
}
// Send the hits to the hits channel
for _, hit := range results.Hits.Hits {
hits <- *hit.Source
}
}
})
// 2nd goroutine receives hits and deserializes them.
g.Go(func() error {
for hit := range hits {
vertex := &gripql.Vertex{}
err := protojson.Unmarshal(hit, vertex)
if err != nil {
return fmt.Errorf("failed to unmarshal vertex: %v", err)
}
i := gdbi.NewElementFromVertex(vertex)
i.Loaded = load
o <- i
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetVertexList")
}
}()
return o
}
// GetVertexChannel get a channel that returns all vertices in a graph
func (es *Graph) GetVertexChannel(ctx context.Context, req chan gdbi.ElementLookup, load bool) chan gdbi.ElementLookup {
g, ctx := errgroup.WithContext(ctx)
// Create query batches
batches := gdbi.LookupBatcher(req, es.pageSize, time.Microsecond)
// Find all vertices
o := make(chan gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
for batch := range batches {
idBatch := make([]string, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
idBatch = append(idBatch, batch[i].ID)
batchMap[batch[i].ID] = append(batchMap[batch[i].ID], batch[i])
}
}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.vertexIndex).Size(es.pageSize)
q = q.Query(elastic.NewBoolQuery().Must(elastic.NewIdsQuery().Ids(idBatch...)))
if !load {
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("data"))
}
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
vertex := &gripql.Vertex{}
err := protojson.Unmarshal(*hit.Source, vertex)
if err != nil {
return fmt.Errorf("failed to unmarshal vertex: %s", err)
}
r := batchMap[vertex.Gid]
for _, ri := range r {
ri.Vertex = gdbi.NewElementFromVertex(vertex)
ri.Vertex.Loaded = load
o <- ri
}
}
}
for i := range signals {
o <- signals[i]
}
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetVertexChannel")
}
}()
return o
}
// GetOutChannel gets channel of all vertices connected to element via outgoing edge
func (es *Graph) GetOutChannel(ctx context.Context, req chan gdbi.ElementLookup, load bool, emitNull bool, edgeLabels []string) chan gdbi.ElementLookup {
g, ctx := errgroup.WithContext(ctx)
// Create query batches
batches := gdbi.LookupBatcher(req, es.pageSize, time.Microsecond)
// Find all outgoing edges
edgeBatches := make(chan []gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
defer close(edgeBatches)
for batch := range batches {
idBatch := make([]interface{}, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
batchMapReturnCount := make(map[string]int)
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
idBatch = append(idBatch, batch[i].ID)
batchMap[batch[i].ID] = append(batchMap[batch[i].ID], batch[i])
batchMapReturnCount[batch[i].ID] = 0
}
}
b := []gdbi.ElementLookup{}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.edgeIndex)
qParts := []elastic.Query{elastic.NewTermsQuery("from", idBatch...)}
if len(edgeLabels) > 0 {
labels := make([]interface{}, len(edgeLabels))
for i, v := range edgeLabels {
labels[i] = v
}
qParts = append(qParts, elastic.NewTermsQuery("label", labels...))
}
q = q.Query(elastic.NewBoolQuery().Must(qParts...))
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Include("from", "to"))
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
edge := &gripql.Edge{}
err := protojson.Unmarshal(*hit.Source, edge)
if err != nil {
return fmt.Errorf("failed to unmarshal edge: %s", err)
}
r := batchMap[edge.From]
batchMapReturnCount[edge.From]++
for _, ri := range r {
ri.Vertex = &gdbi.Vertex{ID: edge.To}
b = append(b, ri)
}
}
}
if emitNull {
for id, count := range batchMapReturnCount {
if count == 0 {
r := batchMap[id]
for _, ri := range r {
ri.Vertex = nil
b = append(b, ri)
}
}
}
}
for i := range signals {
b = append(b, signals[i])
}
edgeBatches <- b
}
return nil
})
// Collect all identified vertices
o := make(chan gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
for batch := range edgeBatches {
idBatch := make([]string, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
if batch[i].Vertex != nil {
idBatch = append(idBatch, batch[i].Vertex.ID)
batchMap[batch[i].Vertex.ID] = append(batchMap[batch[i].Vertex.ID], batch[i])
} else if emitNull {
o <- batch[i]
}
}
}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.vertexIndex)
q = q.Query(elastic.NewBoolQuery().Must(elastic.NewIdsQuery().Ids(idBatch...)))
if !load {
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("data"))
}
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
vertex := &gripql.Vertex{}
err := protojson.Unmarshal(*hit.Source, vertex)
if err != nil {
return fmt.Errorf("failed to unmarshal vertex: %s", err)
}
r := batchMap[vertex.Gid]
for _, ri := range r {
ri.Vertex = gdbi.NewElementFromVertex(vertex)
ri.Vertex.Loaded = load
o <- ri
}
}
}
for i := range signals {
o <- signals[i]
}
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetOutChannel")
}
}()
return o
}
// GetInChannel gets all vertices connected to lookup elements by incoming edges
func (es *Graph) GetInChannel(ctx context.Context, req chan gdbi.ElementLookup, load bool, emitNull bool, edgeLabels []string) chan gdbi.ElementLookup {
g, ctx := errgroup.WithContext(ctx)
// Create query batches
batches := gdbi.LookupBatcher(req, es.pageSize, time.Microsecond)
// Find all incoming edges
edgeBatches := make(chan []gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
defer close(edgeBatches)
for batch := range batches {
idBatch := make([]interface{}, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
batchMapReturnCount := make(map[string]int)
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
idBatch = append(idBatch, batch[i].ID)
batchMap[batch[i].ID] = append(batchMap[batch[i].ID], batch[i])
batchMapReturnCount[batch[i].ID] = 0
}
}
b := []gdbi.ElementLookup{}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.edgeIndex)
qParts := []elastic.Query{elastic.NewTermsQuery("to", idBatch...)}
if len(edgeLabels) > 0 {
labels := make([]interface{}, len(edgeLabels))
for i, v := range edgeLabels {
labels[i] = v
}
qParts = append(qParts, elastic.NewTermsQuery("label", labels...))
}
q = q.Query(elastic.NewBoolQuery().Must(qParts...))
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Include("from", "to"))
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
edge := &gripql.Edge{}
err := protojson.Unmarshal(*hit.Source, edge)
if err != nil {
return fmt.Errorf("failed to unmarshal edge: %s", err)
}
r := batchMap[edge.To]
batchMapReturnCount[edge.To]++
for _, ri := range r {
ri.Vertex = &gdbi.Vertex{ID: edge.From}
b = append(b, ri)
}
}
}
if emitNull {
for id, count := range batchMapReturnCount {
if count == 0 {
r := batchMap[id]
for _, ri := range r {
ri.Vertex = nil
b = append(b, ri)
}
}
}
}
for i := range signals {
b = append(b, signals[i])
}
edgeBatches <- b
}
return nil
})
// Collect all identified vertices
o := make(chan gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
for batch := range edgeBatches {
idBatch := make([]string, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
if batch[i].Vertex != nil {
idBatch = append(idBatch, batch[i].Vertex.ID)
batchMap[batch[i].Vertex.ID] = append(batchMap[batch[i].Vertex.ID], batch[i])
} else if emitNull {
o <- batch[i]
}
}
}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.vertexIndex)
q = q.Query(elastic.NewBoolQuery().Must(elastic.NewIdsQuery().Ids(idBatch...)))
if !load {
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("data"))
}
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
vertex := &gripql.Vertex{}
err := protojson.Unmarshal(*hit.Source, vertex)
if err != nil {
return fmt.Errorf("failed to unmarshal vertex: %s", err)
}
r := batchMap[vertex.Gid]
for _, ri := range r {
ri.Vertex = gdbi.NewElementFromVertex(vertex)
ri.Vertex.Loaded = load
o <- ri
}
}
for i := range signals {
o <- signals[i]
}
}
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetInChannel")
}
}()
return o
}
// GetOutEdgeChannel gets all outgoing edges connected to lookup element
func (es *Graph) GetOutEdgeChannel(ctx context.Context, req chan gdbi.ElementLookup, load bool, emitNull bool, edgeLabels []string) chan gdbi.ElementLookup {
g, ctx := errgroup.WithContext(ctx)
// Create query batches
batches := gdbi.LookupBatcher(req, es.pageSize, time.Microsecond)
// Find all outgoing edges
o := make(chan gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
for batch := range batches {
idBatch := make([]interface{}, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
batchMapReturnCount := make(map[string]int)
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
idBatch = append(idBatch, batch[i].ID)
batchMap[batch[i].ID] = append(batchMap[batch[i].ID], batch[i])
batchMapReturnCount[batch[i].ID] = 0
}
}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.edgeIndex)
qParts := []elastic.Query{elastic.NewTermsQuery("from", idBatch...)}
if len(edgeLabels) > 0 {
labels := make([]interface{}, len(edgeLabels))
for i, v := range edgeLabels {
labels[i] = v
}
qParts = append(qParts, elastic.NewTermsQuery("label", labels...))
}
q = q.Query(elastic.NewBoolQuery().Must(qParts...))
if !load {
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("data"))
}
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
edge := &gripql.Edge{}
err := protojson.Unmarshal(*hit.Source, edge)
if err != nil {
return fmt.Errorf("failed to unmarshal edge: %s", err)
}
r := batchMap[edge.From]
batchMapReturnCount[edge.From]++
for _, ri := range r {
ri.Edge = gdbi.NewElementFromEdge(edge)
ri.Edge.Loaded = load
o <- ri
}
}
}
if emitNull {
for id, count := range batchMapReturnCount {
if count == 0 {
r := batchMap[id]
for _, ri := range r {
ri.Edge = nil
o <- ri
}
}
}
}
for i := range signals {
o <- signals[i]
}
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetOutEdgeChannel")
}
}()
return o
}
// GetInEdgeChannel gets incoming edges connected to lookup element
func (es *Graph) GetInEdgeChannel(ctx context.Context, req chan gdbi.ElementLookup, load bool, emitNull bool, edgeLabels []string) chan gdbi.ElementLookup {
g, ctx := errgroup.WithContext(ctx)
// Create query batches
batches := gdbi.LookupBatcher(req, es.pageSize, time.Microsecond)
// Find all incoming edges
o := make(chan gdbi.ElementLookup, es.pageSize)
g.Go(func() error {
for batch := range batches {
idBatch := make([]interface{}, 0, len(batch))
batchMap := make(map[string][]gdbi.ElementLookup, len(batch))
batchMapReturnCount := make(map[string]int)
signals := []gdbi.ElementLookup{}
for i := range batch {
if batch[i].IsSignal() {
signals = append(signals, batch[i])
} else {
idBatch = append(idBatch, batch[i].ID)
batchMap[batch[i].ID] = append(batchMap[batch[i].ID], batch[i])
batchMapReturnCount[batch[i].ID] = 0
}
}
if len(idBatch) > 0 {
q := es.client.Search().Index(es.edgeIndex)
qParts := []elastic.Query{elastic.NewTermsQuery("to", idBatch...)}
if len(edgeLabels) > 0 {
labels := make([]interface{}, len(edgeLabels))
for i, v := range edgeLabels {
labels[i] = v
}
qParts = append(qParts, elastic.NewTermsQuery("label", labels...))
}
q = q.Query(elastic.NewBoolQuery().Must(qParts...))
if !load {
q = q.FetchSource(true).FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("data"))
}
q = q.Sort("gid", true).Size(es.pageSize)
for hit := range paginateQuery(ctx, q, es.pageSize) {
// Deserialize
edge := &gripql.Edge{}
err := protojson.Unmarshal(*hit.Source, edge)
if err != nil {
return fmt.Errorf("failed to unmarshal edge: %s", err)
}
r := batchMap[edge.To]
batchMapReturnCount[edge.To]++
for _, ri := range r {
ri.Edge = gdbi.NewElementFromEdge(edge)
ri.Edge.Loaded = load
o <- ri
}
}
}
if emitNull {
for id, count := range batchMapReturnCount {
if count == 0 {
r := batchMap[id]
for _, ri := range r {
ri.Edge = nil
o <- ri
}
}
}
}
for i := range signals {
o <- signals[i]
}
}
return nil
})
// Check whether any goroutines failed.
go func() {
defer close(o)
if err := g.Wait(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("GetInEdgeChannel")
}
}()
return o
}
// ListVertexLabels returns a list of vertex types in the graph
func (es *Graph) ListVertexLabels() ([]string, error) {
q := es.client.Search().Index(es.vertexIndex).Type("vertex")
aggName := "vertex.labels.aggregation"
q = q.Aggregation(aggName, elastic.NewTermsAggregation().Field("label").Size(1000000))
res, err := q.Do(context.Background())
if err != nil {
return nil, err
}
labels := []string{}
if agg, found := res.Aggregations.Terms(aggName); found {
for _, bucket := range agg.Buckets {
labels = append(labels, bucket.Key.(string))
}
}
return labels, nil
}
// ListEdgeLabels returns a list of edge types in the graph
func (es *Graph) ListEdgeLabels() ([]string, error) {
q := es.client.Search().Index(es.edgeIndex).Type("edge")
aggName := "edge.labels.aggregation"
q = q.Aggregation(aggName, elastic.NewTermsAggregation().Field("label").Size(1000000))
res, err := q.Do(context.Background())
if err != nil {
return nil, err
}
labels := []string{}
if agg, found := res.Aggregations.Terms(aggName); found {
for _, bucket := range agg.Buckets {
labels = append(labels, bucket.Key.(string))
}
}
return labels, nil
}