-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
NativeIndexAccessorTest.java
942 lines (809 loc) · 31.4 KB
/
NativeIndexAccessorTest.java
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.index.schema;
import org.eclipse.collections.api.iterator.LongIterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.neo4j.collection.PrimitiveLongCollections;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.internal.kernel.api.IndexOrder;
import org.neo4j.internal.kernel.api.IndexQuery;
import org.neo4j.internal.kernel.api.exceptions.schema.IndexNotApplicableKernelException;
import org.neo4j.io.pagecache.IOLimiter;
import org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.api.index.IndexUpdater;
import org.neo4j.kernel.impl.api.index.IndexUpdateMode;
import org.neo4j.storageengine.api.schema.IndexDescriptor;
import org.neo4j.storageengine.api.schema.IndexProgressor;
import org.neo4j.storageengine.api.schema.IndexReader;
import org.neo4j.storageengine.api.schema.IndexSample;
import org.neo4j.storageengine.api.schema.IndexSampler;
import org.neo4j.values.storable.RandomValues;
import org.neo4j.values.storable.Value;
import static java.lang.String.format;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.neo4j.collection.PrimitiveLongCollections.EMPTY_LONG_ARRAY;
import static org.neo4j.function.Predicates.alwaysTrue;
import static org.neo4j.function.Predicates.in;
import static org.neo4j.helpers.collection.Iterables.asUniqueSet;
import static org.neo4j.helpers.collection.Iterators.filter;
import static org.neo4j.kernel.api.index.IndexEntryUpdate.change;
import static org.neo4j.kernel.api.index.IndexEntryUpdate.remove;
import static org.neo4j.kernel.impl.api.index.IndexUpdateMode.ONLINE;
import static org.neo4j.kernel.impl.index.schema.LayoutTestUtil.countUniqueValues;
import static org.neo4j.values.storable.Values.of;
/**
* Tests for
* <ul>
* <li>{@link NumberIndexAccessor}</li>
* <li>{@link NativeIndexUpdater}</li>
* <li>{@link NumberIndexReader}</li>
* </ul>
*/
public abstract class NativeIndexAccessorTest<KEY extends NativeIndexKey<KEY>, VALUE extends NativeIndexValue>
extends NativeIndexTestUtil<KEY,VALUE>
{
private static final int N_VALUES = 10;
NativeIndexAccessor<KEY,VALUE> accessor;
@Rule
public ExpectedException expected = ExpectedException.none();
@Before
public void setupAccessor() throws IOException
{
accessor = makeAccessor();
}
abstract NativeIndexAccessor<KEY,VALUE> makeAccessor() throws IOException;
@After
public void closeAccessor()
{
accessor.close();
}
// UPDATER
@Test
public void shouldHandleCloseWithoutCallsToProcess() throws Exception
{
// given
IndexUpdater updater = accessor.newUpdater( ONLINE );
// when
updater.close();
// then
// ... should be fine
}
@Test
public void processMustThrowAfterClose() throws Exception
{
// given
IndexUpdater updater = accessor.newUpdater( ONLINE );
updater.close();
// then
expected.expect( IllegalStateException.class );
// when
updater.process( simpleUpdate() );
}
@Test
public void shouldIndexAdd() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
try ( IndexUpdater updater = accessor.newUpdater( ONLINE ) )
{
// when
processAll( updater, updates );
}
// then
forceAndCloseAccessor();
verifyUpdates( updates );
}
@Test
public void shouldIndexChange() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
Iterator<IndexEntryUpdate<IndexDescriptor>> generator = filter( skipExisting( updates ), layoutUtil.randomUpdateGenerator( random ) );
for ( int i = 0; i < updates.length; i++ )
{
IndexEntryUpdate<IndexDescriptor> update = updates[i];
Value newValue = generator.next().values()[0];
updates[i] = change( update.getEntityId(), indexDescriptor, update.values()[0], newValue );
}
// when
processAll( updates );
// then
forceAndCloseAccessor();
verifyUpdates( updates );
}
@Test
public void shouldIndexRemove() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
for ( int i = 0; i < updates.length; i++ )
{
// when
IndexEntryUpdate<IndexDescriptor> update = updates[i];
IndexEntryUpdate<IndexDescriptor> remove = remove( update.getEntityId(), indexDescriptor, update.values() );
processAll( remove );
forceAndCloseAccessor();
// then
verifyUpdates( Arrays.copyOfRange( updates, i + 1, updates.length ) );
setupAccessor();
}
}
@Test
public void shouldHandleRandomUpdates() throws Exception
{
// given
Set<IndexEntryUpdate<IndexDescriptor>> expectedData = new HashSet<>();
Iterator<IndexEntryUpdate<IndexDescriptor>> newDataGenerator = layoutUtil.randomUpdateGenerator( random );
// when
int rounds = 50;
for ( int round = 0; round < rounds; round++ )
{
// generate a batch of updates (add, change, remove)
IndexEntryUpdate<IndexDescriptor>[] batch =
generateRandomUpdates( expectedData, newDataGenerator, random.nextInt( 5, 20 ), (float) round / rounds * 2 );
// apply to tree
processAll( batch );
// apply to expectedData
applyUpdatesToExpectedData( expectedData, batch );
// verifyUpdates
forceAndCloseAccessor();
verifyUpdates( expectedData.toArray( new IndexEntryUpdate[0] ) );
setupAccessor();
}
}
// === READER ===
@Test
public void shouldReturnZeroCountForEmptyIndex()
{
// given
try ( IndexReader reader = accessor.newReader() )
{
// when
IndexEntryUpdate<IndexDescriptor> update = layoutUtil.randomUpdateGenerator( random ).next();
long count = reader.countIndexedNodes( 123, layoutUtil.indexDescriptor.properties(), update.values()[0] );
// then
assertEquals( 0, count );
}
}
@Test
public void shouldReturnCountOneForExistingData() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
try ( IndexReader reader = accessor.newReader() )
{
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
long count = reader.countIndexedNodes( update.getEntityId(), layoutUtil.indexDescriptor.properties(), update.values() );
// then
assertEquals( 1, count );
}
// and when
Iterator<IndexEntryUpdate<IndexDescriptor>> generator = filter( skipExisting( updates ), layoutUtil.randomUpdateGenerator( random ) );
long count = reader.countIndexedNodes( 123, layoutUtil.indexDescriptor.properties(), generator.next().values()[0] );
// then
assertEquals( 0, count );
}
}
@Test
public void shouldReturnCountZeroForMismatchingData() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
IndexReader reader = accessor.newReader();
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
int[] propKeys = layoutUtil.indexDescriptor.properties();
long countWithMismatchingData = reader.countIndexedNodes( update.getEntityId() + 1, propKeys, update.values() );
long countWithNonExistentEntityId = reader.countIndexedNodes( NON_EXISTENT_ENTITY_ID, propKeys, update.values() );
long countWithNonExistentValue = reader.countIndexedNodes( update.getEntityId(), propKeys, generateUniqueValue( updates ) );
// then
assertEquals( 0, countWithMismatchingData );
assertEquals( 0, countWithNonExistentEntityId );
assertEquals( 0, countWithNonExistentValue );
}
}
@Test
public void shouldReturnAllEntriesForExistsPredicate() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader, IndexQuery.exists( 0 ) );
// then
assertEntityIdHits( extractEntityIds( updates, alwaysTrue() ), result );
}
@Test
public void shouldReturnNoEntriesForExistsPredicateForEmptyIndex() throws Exception
{
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader, IndexQuery.exists( 0 ) );
// then
long[] actual = PrimitiveLongCollections.asArray( result );
assertEquals( 0, actual.length );
}
@Test
public void shouldReturnMatchingEntriesForExactPredicate() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
IndexReader reader = accessor.newReader();
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
Value value = update.values()[0];
LongIterator result = query( reader, IndexQuery.exact( 0, value ) );
assertEntityIdHits( extractEntityIds( updates, in( value ) ), result );
}
}
@Test
public void shouldReturnNoEntriesForMismatchingExactPredicate() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
IndexReader reader = accessor.newReader();
Object value = generateUniqueValue( updates );
LongIterator result = query( reader, IndexQuery.exact( 0, value ) );
assertEntityIdHits( EMPTY_LONG_ARRAY, result );
}
@Test
public void shouldReturnMatchingEntriesForRangePredicateWithInclusiveStartAndExclusiveEnd() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesNoDuplicateValues();
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader,
layoutUtil.rangeQuery( valueOf( updates[0] ), true, valueOf( updates[updates.length - 1] ), false ) );
assertEntityIdHits( extractEntityIds( Arrays.copyOf( updates, updates.length - 1 ), alwaysTrue() ), result );
}
@Test
public void shouldReturnMatchingEntriesForRangePredicateWithInclusiveStartAndInclusiveEnd() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesNoDuplicateValues();
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader,
layoutUtil.rangeQuery( valueOf( updates[0] ), true, valueOf( updates[updates.length - 1] ), true ) );
assertEntityIdHits( extractEntityIds( updates, alwaysTrue() ), result );
}
@Test
public void shouldReturnMatchingEntriesForRangePredicateWithExclusiveStartAndExclusiveEnd() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesNoDuplicateValues();
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader,
layoutUtil.rangeQuery( valueOf( updates[0] ), false, valueOf( updates[updates.length - 1] ), false ) );
assertEntityIdHits( extractEntityIds( Arrays.copyOfRange( updates, 1, updates.length - 1 ), alwaysTrue() ), result );
}
@Test
public void shouldReturnMatchingEntriesForRangePredicateWithExclusiveStartAndInclusiveEnd() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesNoDuplicateValues();
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader,
layoutUtil.rangeQuery( valueOf( updates[0] ), false, valueOf( updates[updates.length - 1] ), true ) );
assertEntityIdHits( extractEntityIds( Arrays.copyOfRange( updates, 1, updates.length ), alwaysTrue() ), result );
}
@Test
public void shouldReturnNoEntriesForRangePredicateOutsideAnyMatch() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdates();
layoutUtil.sort( updates );
processAll( updates[0], updates[1], updates[updates.length - 1], updates[updates.length - 2] );
// when
IndexReader reader = accessor.newReader();
LongIterator result = query( reader,
layoutUtil.rangeQuery( valueOf( updates[2] ), true, valueOf( updates[updates.length - 3] ), true ) );
assertEntityIdHits( EMPTY_LONG_ARRAY, result );
}
@Test( timeout = 10_000L )
public void mustHandleNestedQueries() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
mustHandleNestedQueries( updates );
}
void mustHandleNestedQueries( IndexEntryUpdate<IndexDescriptor>[] updates ) throws IndexEntryConflictException, IndexNotApplicableKernelException
{
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
IndexQuery outerQuery = layoutUtil.rangeQuery( valueOf( updates[2] ), true, valueOf( updates[3] ), true );
IndexQuery innerQuery = layoutUtil.rangeQuery( valueOf( updates[0] ), true, valueOf( updates[1] ), true );
long[] expectedOuter = new long[]{entityIdOf( updates[2] ), entityIdOf( updates[3] )};
long[] expectedInner = new long[]{entityIdOf( updates[0] ), entityIdOf( updates[1] )};
LongIterator outerIter = query( reader, outerQuery );
Collection<Long> outerResult = new ArrayList<>();
while ( outerIter.hasNext() )
{
outerResult.add( outerIter.next() );
LongIterator innerIter = query( reader, innerQuery );
assertEntityIdHits( expectedInner, innerIter );
}
assertEntityIdHits( expectedOuter, outerResult );
}
@Test
public void mustHandleMultipleNestedQueries() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
mustHandleMultipleNestedQueries( updates );
}
void mustHandleMultipleNestedQueries( IndexEntryUpdate<IndexDescriptor>[] updates )
throws IndexEntryConflictException, IndexNotApplicableKernelException
{
processAll( updates );
layoutUtil.sort( updates );
// when
IndexReader reader = accessor.newReader();
IndexQuery query1 = layoutUtil.rangeQuery( valueOf( updates[4] ), true, valueOf( updates[5] ), true );
IndexQuery query2 = layoutUtil.rangeQuery( valueOf( updates[2] ), true, valueOf( updates[3] ), true );
IndexQuery query3 = layoutUtil.rangeQuery( valueOf( updates[0] ), true, valueOf( updates[1] ), true );
long[] expected1 = new long[]{entityIdOf( updates[4] ), entityIdOf( updates[5] )};
long[] expected2 = new long[]{entityIdOf( updates[2] ), entityIdOf( updates[3] )};
long[] expected3 = new long[]{entityIdOf( updates[0] ), entityIdOf( updates[1] )};
Collection<Long> result1 = new ArrayList<>();
LongIterator iter1 = query( reader, query1 );
while ( iter1.hasNext() )
{
result1.add( iter1.next() );
Collection<Long> result2 = new ArrayList<>();
LongIterator iter2 = query( reader, query2 );
while ( iter2.hasNext() )
{
result2.add( iter2.next() );
Collection<Long> result3 = new ArrayList<>();
LongIterator iter3 = query( reader, query3 );
while ( iter3.hasNext() )
{
result3.add( iter3.next() );
}
assertEntityIdHits( expected3, result3 );
}
assertEntityIdHits( expected2, result2 );
}
assertEntityIdHits( expected1, result1 );
}
private long entityIdOf( IndexEntryUpdate<IndexDescriptor> update )
{
return update.getEntityId();
}
@Test
public void shouldHandleMultipleConsecutiveUpdaters() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
// when
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
try ( IndexUpdater updater = accessor.newUpdater( ONLINE ) )
{
updater.process( update );
}
}
// then
forceAndCloseAccessor();
verifyUpdates( updates );
}
@Test
public void requestForSecondUpdaterMustThrow() throws Exception
{
// given
try ( IndexUpdater ignored = accessor.newUpdater( ONLINE ) )
{
// then
expected.expect( IllegalStateException.class );
// when
accessor.newUpdater( ONLINE );
}
}
@Test
public void dropShouldDeleteAndCloseIndex()
{
// given
assertFilePresent();
// when
accessor.drop();
// then
assertFileNotPresent();
}
@Test
public void forceShouldCheckpointTree() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] data = someUpdatesSingleType();
processAll( data );
// when
accessor.force( IOLimiter.UNLIMITED );
accessor.close();
// then
verifyUpdates( data );
}
@SuppressWarnings( "unchecked" )
@Test
public void closeShouldCloseTreeWithoutCheckpoint() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] data = someUpdatesSingleType();
processAll( data );
// when
accessor.close();
// then
verifyUpdates( new IndexEntryUpdate[0] );
}
@Test
public void snapshotFilesShouldReturnIndexFile()
{
// when
ResourceIterator<File> files = accessor.snapshotFiles();
// then
assertTrue( files.hasNext() );
assertEquals( getIndexFile(), files.next() );
assertFalse( files.hasNext() );
}
@Test
public void shouldSampleIndex() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
try ( IndexReader reader = accessor.newReader() )
{
IndexSampler sampler = reader.createSampler();
// when
IndexSample sample = sampler.sampleIndex();
// then
assertEquals( updates.length, sample.indexSize() );
assertEquals( updates.length, sample.sampleSize() );
assertEquals( countUniqueValues( updates ), sample.uniqueValues() );
}
}
@Test
public void readingAfterDropShouldThrow()
{
// given
accessor.drop();
// then
expected.expect( IllegalStateException.class );
// when
accessor.newReader();
}
@Test
public void writingAfterDropShouldThrow()
{
// given
accessor.drop();
// then
expected.expect( IllegalStateException.class );
// when
accessor.newUpdater( IndexUpdateMode.ONLINE );
}
@Test
public void readingAfterCloseShouldThrow()
{
// given
accessor.close();
// then
expected.expect( IllegalStateException.class );
// when
accessor.newReader();
}
@Test
public void writingAfterCloseShouldThrow()
{
// given
accessor.close();
// then
expected.expect( IllegalStateException.class );
// when
accessor.newUpdater( IndexUpdateMode.ONLINE );
}
@Test
public void shouldSeeAllEntriesInAllEntriesReader() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = someUpdatesSingleType();
processAll( updates );
// when
Set<Long> ids = asUniqueSet( accessor.newAllEntriesReader() );
// then
Set<Long> expectedIds = Stream.of( updates )
.map( IndexEntryUpdate::getEntityId )
.collect( Collectors.toCollection( HashSet::new ) );
assertEquals( expectedIds, ids );
}
@Test
public void shouldSeeNoEntriesInAllEntriesReaderOnEmptyIndex()
{
// when
Set<Long> ids = asUniqueSet( accessor.newAllEntriesReader() );
// then
Set<Long> expectedIds = Collections.emptySet();
assertEquals( expectedIds, ids );
}
@Test
public void shouldNotSeeFilteredEntries() throws Exception
{
// given
IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesNoDuplicateValues();
processAll( updates );
layoutUtil.sort( updates );
IndexReader reader = accessor.newReader();
// when
NodeValueIterator iter = new NodeValueIterator();
IndexQuery.ExactPredicate filter = IndexQuery.exact( 0, valueOf( updates[1]) );
IndexQuery rangeQuery = layoutUtil.rangeQuery( valueOf( updates[0] ), true, valueOf( updates[2] ), true );
IndexProgressor.NodeValueClient filterClient = filterClient( iter, filter );
reader.query( filterClient, IndexOrder.NONE, false, rangeQuery );
// then
assertTrue( iter.hasNext() );
assertEquals( entityIdOf( updates[1] ), iter.next() );
assertFalse( iter.hasNext() );
}
private Value generateUniqueValue( IndexEntryUpdate<IndexDescriptor>[] updates )
{
return filter( skipExisting( updates ), layoutUtil.randomUpdateGenerator( random ) ).next().values()[0];
}
private static Predicate<IndexEntryUpdate<IndexDescriptor>> skipExisting( IndexEntryUpdate<IndexDescriptor>[] existing )
{
return update ->
{
for ( IndexEntryUpdate<IndexDescriptor> e : existing )
{
if ( Arrays.equals( e.values(), update.values() ) )
{
return false;
}
}
return true;
};
}
private Value valueOf( IndexEntryUpdate<IndexDescriptor> update )
{
return update.values()[0];
}
private IndexProgressor.NodeValueClient filterClient( final NodeValueIterator iter, final IndexQuery filter )
{
return new IndexProgressor.NodeValueClient()
{
@Override
public void initialize( IndexDescriptor descriptor, IndexProgressor progressor, IndexQuery[] query, IndexOrder indexOrder, boolean needsValues )
{
iter.initialize( descriptor, progressor, query, indexOrder, needsValues );
}
@Override
public boolean acceptNode( long reference, Value... values )
{
//noinspection SimplifiableIfStatement
if ( values.length > 1 )
{
return false;
}
return filter.acceptsValue( values[0] ) && iter.acceptNode( reference, values );
}
@Override
public boolean needsValues()
{
return true;
}
};
}
private LongIterator query( IndexReader reader, IndexQuery query ) throws IndexNotApplicableKernelException
{
NodeValueIterator client = new NodeValueIterator();
reader.query( client, IndexOrder.NONE, false, query );
return client;
}
private void assertEntityIdHits( long[] expected, LongIterator result )
{
long[] actual = PrimitiveLongCollections.asArray( result );
assertSameContent( expected, actual );
}
private void assertEntityIdHits( long[] expected, Collection<Long> result )
{
long[] actual = new long[result.size()];
int index = 0;
for ( Long aLong : result )
{
actual[index++] = aLong;
}
assertSameContent( expected, actual );
}
private void assertSameContent( long[] expected, long[] actual )
{
Arrays.sort( actual );
Arrays.sort( expected );
assertArrayEquals( format( "Expected arrays to be equal but wasn't.%nexpected:%s%n actual:%s%n",
Arrays.toString( expected ), Arrays.toString( actual ) ), expected, actual );
}
private long[] extractEntityIds( IndexEntryUpdate<?>[] updates, Predicate<Value> valueFilter )
{
long[] entityIds = new long[updates.length];
int cursor = 0;
for ( IndexEntryUpdate<?> update : updates )
{
if ( valueFilter.test( update.values()[0] ) )
{
entityIds[cursor++] = update.getEntityId();
}
}
return Arrays.copyOf( entityIds, cursor );
}
private void applyUpdatesToExpectedData( Set<IndexEntryUpdate<IndexDescriptor>> expectedData,
IndexEntryUpdate<IndexDescriptor>[] batch )
{
for ( IndexEntryUpdate<IndexDescriptor> update : batch )
{
IndexEntryUpdate<IndexDescriptor> addition = null;
IndexEntryUpdate<IndexDescriptor> removal = null;
switch ( update.updateMode() )
{
case ADDED:
addition = layoutUtil.add( update.getEntityId(), update.values()[0] );
break;
case CHANGED:
addition = layoutUtil.add( update.getEntityId(), update.values()[0] );
removal = layoutUtil.add( update.getEntityId(), update.beforeValues()[0] );
break;
case REMOVED:
removal = layoutUtil.add( update.getEntityId(), update.values()[0] );
break;
default:
throw new IllegalArgumentException( update.updateMode().name() );
}
if ( removal != null )
{
expectedData.remove( removal );
}
if ( addition != null )
{
expectedData.add( addition );
}
}
}
private IndexEntryUpdate<IndexDescriptor>[] generateRandomUpdates(
Set<IndexEntryUpdate<IndexDescriptor>> expectedData,
Iterator<IndexEntryUpdate<IndexDescriptor>> newDataGenerator, int count, float removeFactor )
{
@SuppressWarnings( "unchecked" )
IndexEntryUpdate<IndexDescriptor>[] updates = new IndexEntryUpdate[count];
float addChangeRatio = 0.5f;
for ( int i = 0; i < count; i++ )
{
float factor = random.nextFloat();
if ( !expectedData.isEmpty() && factor < removeFactor )
{
// remove something
IndexEntryUpdate<IndexDescriptor> toRemove = selectRandomItem( expectedData );
updates[i] = remove( toRemove.getEntityId(), indexDescriptor, toRemove.values() );
}
else if ( !expectedData.isEmpty() && factor < (1 - removeFactor) * addChangeRatio )
{
// change
IndexEntryUpdate<IndexDescriptor> toChange = selectRandomItem( expectedData );
// use the data generator to generate values, even if the whole update as such won't be used
IndexEntryUpdate<IndexDescriptor> updateContainingValue = newDataGenerator.next();
updates[i] = change( toChange.getEntityId(), indexDescriptor, toChange.values(),
updateContainingValue.values() );
}
else
{
// add
updates[i] = newDataGenerator.next();
}
}
return updates;
}
@SuppressWarnings( "unchecked" )
private IndexEntryUpdate<IndexDescriptor> selectRandomItem( Set<IndexEntryUpdate<IndexDescriptor>> expectedData )
{
return expectedData.toArray( new IndexEntryUpdate[0] )[random.nextInt( expectedData.size() )];
}
@SafeVarargs
final void processAll( IndexEntryUpdate<IndexDescriptor>... updates )
throws IndexEntryConflictException
{
try ( IndexUpdater updater = accessor.newUpdater( ONLINE ) )
{
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
updater.process( update );
}
}
}
private void forceAndCloseAccessor()
{
accessor.force( IOLimiter.UNLIMITED );
closeAccessor();
}
private void processAll( IndexUpdater updater, IndexEntryUpdate<IndexDescriptor>[] updates )
throws IndexEntryConflictException
{
for ( IndexEntryUpdate<IndexDescriptor> update : updates )
{
updater.process( update );
}
}
private IndexEntryUpdate<IndexDescriptor> simpleUpdate()
{
return IndexEntryUpdate.add( 0, indexDescriptor, of( 0 ) );
}
private IndexEntryUpdate<IndexDescriptor>[] someUpdatesSingleType()
{
RandomValues.Type type = randomValues.among( layoutUtil.supportedTypes() );
Value[] values = new Value[N_VALUES];
for ( int i = 0; i < N_VALUES; i++ )
{
values[i] = randomValues.nextValueOfTypes( type );
}
return layoutUtil.generateAddUpdatesFor( values );
}
// TODO: multiple query predicates... actually Lucene SimpleIndexReader only supports single predicate
// so perhaps we should wait with this until we know exactly how this works and which combinations
// that should be supported/optimized for.
}