-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
index_test.go
412 lines (361 loc) · 13.4 KB
/
index_test.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
/*
* Copyright 2016-2018 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package posting
import (
"bytes"
"context"
"math"
"testing"
"time"
"github.com/dgraph-io/badger"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/schema"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/x"
)
func uids(l *List, readTs uint64) []uint64 {
r, err := l.Uids(ListOptions{ReadTs: readTs})
x.Check(err)
return r.Uids
}
func TestIndexingInt(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("age:int @index(int) ."), 1))
a, err := indexTokens("age", "", types.Val{Tid: types.StringID, Value: []byte("10")})
require.NoError(t, err)
require.EqualValues(t, []byte{0x6, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa}, []byte(a[0]))
}
func TestIndexingIntNegative(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("age:int @index(int) ."), 1))
a, err := indexTokens("age", "", types.Val{Tid: types.StringID, Value: []byte("-10")})
require.NoError(t, err)
require.EqualValues(t, []byte{0x6, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6},
[]byte(a[0]))
}
func TestIndexingFloat(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("age:float @index(float) ."), 1))
a, err := indexTokens("age", "", types.Val{Tid: types.StringID, Value: []byte("10.43")})
require.NoError(t, err)
require.EqualValues(t, []byte{0x7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa}, []byte(a[0]))
}
func TestIndexingTime(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("age:dateTime @index(year) ."), 1))
a, err := indexTokens("age", "", types.Val{Tid: types.StringID,
Value: []byte("0010-01-01T01:01:01.000000001")})
require.NoError(t, err)
require.EqualValues(t, []byte{0x4, 0x0, 0xa}, []byte(a[0]))
}
func TestIndexing(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("name:string @index(term) ."), 1))
a, err := indexTokens("name", "", types.Val{Tid: types.StringID, Value: []byte("abc")})
require.NoError(t, err)
require.EqualValues(t, "\x01abc", string(a[0]))
}
func TestIndexingMultiLang(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("name:string @index(fulltext) ."), 1))
// ensure that default tokenizer is suitable for English
a, err := indexTokens("name", "", types.Val{Tid: types.StringID, Value: []byte("stemming")})
require.NoError(t, err)
require.EqualValues(t, "\x08stem", string(a[0]))
// ensure that Finnish tokenizer is used
a, err = indexTokens("name", "fi", types.Val{Tid: types.StringID,
Value: []byte("edeltäneessä")})
require.NoError(t, err)
require.EqualValues(t, "\x08edeltän", string(a[0]))
// ensure that German tokenizer is used
a, err = indexTokens("name", "de", types.Val{Tid: types.StringID,
Value: []byte("Auffassungsvermögen")})
require.NoError(t, err)
require.EqualValues(t, "\x08auffassungsvermog", string(a[0]))
// ensure that default tokenizer works differently than German
a, err = indexTokens("name", "", types.Val{Tid: types.StringID,
Value: []byte("Auffassungsvermögen")})
require.NoError(t, err)
require.EqualValues(t, "\x08auffassungsvermögen", string(a[0]))
}
func TestIndexingInvalidLang(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("name:string @index(fulltext) ."), 1))
// tokenizer for "xx" language won't return an error.
_, err := indexTokens("name", "xx", types.Val{Tid: types.StringID, Value: []byte("error")})
require.NoError(t, err)
}
func TestIndexingAliasedLang(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte("name:string @index(fulltext) @lang ."), 1))
_, err := indexTokens("name", "es", types.Val{Tid: types.StringID, Value: []byte("base")})
require.NoError(t, err)
// es-es and es-419 are aliased to es
_, err = indexTokens("name", "es-es", types.Val{Tid: types.StringID, Value: []byte("alias")})
require.NoError(t, err)
_, err = indexTokens("name", "es-419", types.Val{Tid: types.StringID, Value: []byte("alias")})
require.NoError(t, err)
}
func addMutation(t *testing.T, l *List, edge *pb.DirectedEdge, op uint32,
startTs uint64, commitTs uint64, index bool) {
if op == Del {
edge.Op = pb.DirectedEdge_DEL
} else if op == Set {
edge.Op = pb.DirectedEdge_SET
} else {
x.Fatalf("Unhandled op: %v", op)
}
txn := Oracle().RegisterStartTs(startTs)
txn.cache.Set(string(l.key), l)
if index {
require.NoError(t, l.AddMutationWithIndex(context.Background(), edge, txn))
} else {
err := l.AddMutation(context.Background(), txn, edge)
require.NoError(t, err)
}
writer := NewTxnWriter(pstore)
require.NoError(t, txn.CommitToDisk(writer, commitTs))
require.NoError(t, writer.Flush())
require.NoError(t, txn.CommitToMemory(commitTs))
}
const schemaVal = `
name:string @index(term) .
name2:string @index(term) .
dob:dateTime @index(year) .
friend:uid @reverse .
`
// TODO(Txn): We can't read index key on disk if it was written in same txn.
func TestTokensTable(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte(schemaVal), 1))
key := x.DataKey("name", 1)
l, err := getNew(key, ps)
require.NoError(t, err)
edge := &pb.DirectedEdge{
Value: []byte("david"),
Label: "testing",
Attr: "name",
Entity: 157,
}
addMutation(t, l, edge, Set, 1, 2, true)
key = x.IndexKey("name", "\x01david")
time.Sleep(10 * time.Millisecond)
txn := ps.NewTransactionAt(3, false)
_, err = txn.Get(key)
require.NoError(t, err)
require.EqualValues(t, []string{"\x01david"}, tokensForTest("name"))
}
// tokensForTest returns keys for a table. This is just for testing / debugging.
func tokensForTest(attr string) []string {
pk := x.ParsedKey{Attr: attr}
prefix := pk.IndexPrefix()
txn := pstore.NewTransactionAt(math.MaxUint64, false)
defer txn.Discard()
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
var out []string
for it.Seek(prefix); it.Valid(); it.Next() {
key := it.Item().Key()
if !bytes.HasPrefix(key, prefix) {
break
}
k := x.Parse(key)
x.AssertTrue(k.IsIndex())
out = append(out, k.Term)
}
return out
}
// addEdgeToValue adds edge without indexing.
func addEdgeToValue(t *testing.T, attr string, src uint64,
value string, startTs, commitTs uint64) {
edge := &pb.DirectedEdge{
Value: []byte(value),
Label: "testing",
Attr: attr,
Entity: src,
Op: pb.DirectedEdge_SET,
}
l, err := GetNoStore(x.DataKey(attr, src))
require.NoError(t, err)
// No index entries added here as we do not call AddMutationWithIndex.
addMutation(t, l, edge, Set, startTs, commitTs, false)
}
// addEdgeToUID adds uid edge with reverse edge
func addEdgeToUID(t *testing.T, attr string, src uint64,
dst uint64, startTs, commitTs uint64) {
edge := &pb.DirectedEdge{
ValueId: dst,
Label: "testing",
Attr: attr,
Entity: src,
Op: pb.DirectedEdge_SET,
}
l, err := GetNoStore(x.DataKey(attr, src))
require.NoError(t, err)
// No index entries added here as we do not call AddMutationWithIndex.
addMutation(t, l, edge, Set, startTs, commitTs, false)
}
func TestRebuildIndex(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte(schemaVal), 1))
addEdgeToValue(t, "name2", 91, "Michonne", uint64(1), uint64(2))
addEdgeToValue(t, "name2", 92, "David", uint64(3), uint64(4))
{
txn := ps.NewTransactionAt(1, true)
require.NoError(t, txn.Set(x.IndexKey("name2", "wrongname21"), []byte("nothing")))
require.NoError(t, txn.Set(x.IndexKey("name2", "wrongname22"), []byte("nothing")))
require.NoError(t, txn.CommitAt(1, nil))
}
currentSchema, _ := schema.State().Get("name2")
rb := IndexRebuild{
Attr: "name2",
StartTs: 5,
OldSchema: nil,
CurrentSchema: ¤tSchema,
}
require.NoError(t, RebuildIndex(context.Background(), &rb))
// Check index entries in data store.
txn := ps.NewTransactionAt(6, false)
defer txn.Discard()
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
pk := x.ParsedKey{Attr: "name2"}
prefix := pk.IndexPrefix()
var idxKeys []string
var idxVals []*List
for it.Seek(prefix); it.Valid(); it.Next() {
item := it.Item()
key := item.Key()
if !bytes.HasPrefix(key, prefix) {
break
}
if item.UserMeta()&BitEmptyPosting == BitEmptyPosting {
continue
}
idxKeys = append(idxKeys, string(key))
l, err := GetNoStore(key)
require.NoError(t, err)
idxVals = append(idxVals, l)
}
require.Len(t, idxKeys, 2)
require.Len(t, idxVals, 2)
require.EqualValues(t, idxKeys[0], x.IndexKey("name2", "\x01david"))
require.EqualValues(t, idxKeys[1], x.IndexKey("name2", "\x01michonne"))
uids1 := uids(idxVals[0], 6)
uids2 := uids(idxVals[1], 6)
require.Len(t, uids1, 1)
require.Len(t, uids2, 1)
require.EqualValues(t, 92, uids1[0])
require.EqualValues(t, 91, uids2[0])
}
func TestRebuildReverseEdges(t *testing.T) {
require.NoError(t, schema.ParseBytes([]byte(schemaVal), 1))
addEdgeToUID(t, "friend", 1, 23, uint64(10), uint64(11))
addEdgeToUID(t, "friend", 1, 24, uint64(12), uint64(13))
addEdgeToUID(t, "friend", 2, 23, uint64(14), uint64(15))
currentSchema, _ := schema.State().Get("name2")
rb := IndexRebuild{
Attr: "friend",
StartTs: 16,
OldSchema: nil,
CurrentSchema: ¤tSchema,
}
// TODO: Remove after fixing sync marks.
require.NoError(t, RebuildReverseEdges(context.Background(), &rb))
// Check index entries in data store.
txn := ps.NewTransactionAt(17, false)
defer txn.Discard()
iterOpts := badger.DefaultIteratorOptions
iterOpts.AllVersions = true
it := txn.NewIterator(iterOpts)
defer it.Close()
pk := x.ParsedKey{Attr: "friend"}
prefix := pk.ReversePrefix()
var revKeys []string
var revVals []*List
var prevKey []byte
it.Seek(prefix)
for it.ValidForPrefix(prefix) {
item := it.Item()
key := item.Key()
if bytes.Equal(key, prevKey) {
it.Next()
continue
}
prevKey = append(prevKey[:0], key...)
revKeys = append(revKeys, string(key))
l, err := ReadPostingList(key, it)
require.NoError(t, err)
revVals = append(revVals, l)
}
require.Len(t, revKeys, 2)
require.Len(t, revVals, 2)
uids0 := uids(revVals[0], 17)
uids1 := uids(revVals[1], 17)
require.Len(t, uids0, 2)
require.Len(t, uids1, 1)
require.EqualValues(t, 1, uids0[0])
require.EqualValues(t, 2, uids0[1])
require.EqualValues(t, 1, uids1[0])
}
func TestNeedsIndexRebuild(t *testing.T) {
s1 := pb.SchemaUpdate{ValueType: pb.Posting_UID}
s2 := pb.SchemaUpdate{ValueType: pb.Posting_UID}
require.False(t, needsIndexRebuild(&s1, &s2))
require.True(t, needsIndexRebuild(nil, &s2))
s1 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"exact"}}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"exact"}}
require.False(t, needsIndexRebuild(&s1, &s2))
s1 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"term"}}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX}
require.True(t, needsIndexRebuild(&s1, &s2))
s1 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"exact"}}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_FLOAT, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"exact"}}
require.True(t, needsIndexRebuild(&s1, &s2))
s1 = pb.SchemaUpdate{ValueType: pb.Posting_STRING, Directive: pb.SchemaUpdate_INDEX,
Tokenizer: []string{"exact"}}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_FLOAT, Directive: pb.SchemaUpdate_NONE}
require.True(t, needsIndexRebuild(&s1, &s2))
}
func TestNeedsCountIndexRebuild(t *testing.T) {
s1 := pb.SchemaUpdate{ValueType: pb.Posting_UID}
s2 := pb.SchemaUpdate{ValueType: pb.Posting_UID, Count: true}
require.True(t, needsCountIndexRebuild(&s1, &s2))
require.True(t, needsCountIndexRebuild(nil, &s2))
s1 = pb.SchemaUpdate{ValueType: pb.Posting_UID, Count: false}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_UID, Count: false}
require.False(t, needsCountIndexRebuild(&s1, &s2))
}
func TestNeedsReverseEdgesRebuild(t *testing.T) {
s1 := pb.SchemaUpdate{ValueType: pb.Posting_UID, Directive: pb.SchemaUpdate_INDEX}
s2 := pb.SchemaUpdate{ValueType: pb.Posting_UID, Directive: pb.SchemaUpdate_REVERSE}
require.True(t, needsReverseEdgesRebuild(&s1, &s2))
require.True(t, needsReverseEdgesRebuild(nil, &s2))
s2 = pb.SchemaUpdate{ValueType: pb.Posting_UID, Directive: pb.SchemaUpdate_REVERSE}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_UID, Directive: pb.SchemaUpdate_INDEX}
require.False(t, needsReverseEdgesRebuild(&s1, &s2))
}
func TestNeedsListTypeRebuild(t *testing.T) {
s1 := pb.SchemaUpdate{ValueType: pb.Posting_UID, List: false}
s2 := pb.SchemaUpdate{ValueType: pb.Posting_UID, List: true}
rebuild, err := needsListTypeRebuild(&s1, &s2)
require.True(t, rebuild)
require.NoError(t, err)
rebuild, err = needsListTypeRebuild(nil, &s2)
require.False(t, rebuild)
require.NoError(t, err)
s1 = pb.SchemaUpdate{ValueType: pb.Posting_UID, List: true}
s2 = pb.SchemaUpdate{ValueType: pb.Posting_UID, List: false}
rebuild, err = needsListTypeRebuild(&s1, &s2)
require.False(t, rebuild)
require.Error(t, err)
}