forked from cayleygraph/cayley
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dedup.go
207 lines (188 loc) · 4.51 KB
/
dedup.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
package command
import (
"context"
"crypto/sha1"
"errors"
"fmt"
"hash"
"sort"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/path"
"github.com/cayleygraph/cayley/quad"
"github.com/cayleygraph/cayley/voc/rdf"
)
func iriFlag(s string, err error) (quad.IRI, error) {
if err != nil {
return "", err
}
return quad.IRI(s), nil
}
func NewDedupCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "dedup",
Short: "Deduplicate bnode values",
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
printBackendInfo()
h, err := openDatabase()
if err != nil {
return err
}
defer h.Close()
pred, _ := iriFlag(cmd.Flags().GetString("pred"))
typ, _ := iriFlag(cmd.Flags().GetString("type"))
if typ == "" {
return errors.New("no type is specified")
}
return dedupProperties(ctx, h, pred, typ)
},
}
cmd.Flags().String("pred", rdf.Type, "type predicate to use to find nodes")
cmd.Flags().String("type", "", "type value to use to find nodes")
return cmd
}
func valueLess(a, b graph.Value) bool {
// TODO(dennwc): more effective way
s1, s2 := fmt.Sprint(a), fmt.Sprint(b)
return s1 < s2
}
type sortVals []graph.Value
func (a sortVals) Len() int { return len(a) }
func (a sortVals) Less(i, j int) bool { return valueLess(a[i], a[j]) }
func (a sortVals) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
type sortProp []property
func (a sortProp) Len() int { return len(a) }
func (a sortProp) Less(i, j int) bool { return valueLess(a[i].Pred, a[j].Pred) }
func (a sortProp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func hashProperties(h hash.Hash, m map[interface{}]property) string {
props := make([]property, 0, len(m))
for _, p := range m {
if len(p.Values) > 1 {
sort.Sort(sortVals(p.Values))
}
props = append(props, p)
}
sort.Sort(sortProp(props))
h.Reset()
for _, p := range props {
fmt.Fprint(h, p.Pred)
h.Write([]byte{0})
for _, v := range p.Values {
fmt.Fprint(h, v)
h.Write([]byte{1})
}
}
res := make([]byte, 0, h.Size())
res = h.Sum(res)
return string(res)
}
type property struct {
Pred graph.Value
Values []graph.Value
}
func dedupProperties(ctx context.Context, h *graph.Handle, pred, typ quad.IRI) error {
batch := viper.GetInt(KeyLoadBatch)
if batch == 0 {
batch = quad.DefaultBatch
}
qs := h.QuadStore
p := path.StartPath(qs).Has(pred, typ)
ictx, cancel := context.WithCancel(ctx)
defer cancel()
var gerr error
seen := make(map[string]graph.Value)
cnt, dedup := 0, 0
start := time.Now()
last := start
hh := sha1.New()
tx := graph.NewTransaction()
txn := 0
flush := func() {
if txn == 0 {
return
}
err := h.ApplyTransaction(tx)
if err == nil {
tx = graph.NewTransaction()
dedup += txn
txn = 0
} else {
gerr = err
cancel()
}
if now := time.Now(); now.Sub(last) > time.Second*5 {
last = now
clog.Infof("deduplicated %d/%d nodes (%.1f nodes/sec)",
dedup, cnt, float64(cnt)/now.Sub(start).Seconds(),
)
}
}
err := p.Iterate(ictx).Each(func(s graph.Value) {
cnt++
it := qs.QuadIterator(quad.Subject, s)
defer it.Close()
m := make(map[interface{}]property)
for it.Next(ictx) {
q := it.Result()
p := qs.QuadDirection(q, quad.Predicate)
o := qs.QuadDirection(q, quad.Object)
k := graph.ToKey(p)
prop := m[k]
prop.Pred = p
prop.Values = append(prop.Values, o)
m[k] = prop
}
if gerr = it.Err(); gerr != nil {
cancel()
}
ph := hashProperties(hh, m)
id, ok := seen[ph]
if !ok {
seen[ph] = s
return
}
if gerr = dedupValueTx(ictx, h, tx, s, id); gerr != nil {
cancel()
}
txn++
if txn >= batch { // TODO(dennwc): flag
flush()
}
})
flush()
clog.Infof("deduplicated %d/%d nodes in %v", dedup, cnt, time.Since(start))
if gerr != nil {
err = gerr
}
return err
}
func dedupValueTx(ctx context.Context, h *graph.Handle, tx *graph.Transaction, a, b graph.Value) error {
v := h.NameOf(b)
it := h.QuadIterator(quad.Object, a)
defer it.Close()
for it.Next(ctx) {
// TODO(dennwc): we should be able to add "raw" quads without getting values for directions
q := h.Quad(it.Result())
tx.RemoveQuad(q)
q.Object = v
tx.AddQuad(q)
}
if err := it.Err(); err != nil {
return err
}
it.Close()
it = h.QuadIterator(quad.Subject, a)
defer it.Close()
for it.Next(ctx) {
q := h.Quad(it.Result())
tx.RemoveQuad(q)
}
if err := it.Err(); err != nil {
return err
}
return nil
}