-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
HashBasedIndex.java
334 lines (298 loc) · 10.9 KB
/
HashBasedIndex.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
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.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.api.index.inmemory;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.neo4j.collection.primitive.PrimitiveLongIterator;
import org.neo4j.collection.primitive.PrimitiveLongResourceIterator;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.internal.kernel.api.IndexQuery;
import org.neo4j.kernel.api.schema.index.IndexDescriptor;
import org.neo4j.storageengine.api.schema.IndexSampler;
import org.neo4j.values.storable.Value;
import static org.neo4j.collection.primitive.PrimitiveLongCollections.emptyIterator;
import static org.neo4j.collection.primitive.PrimitiveLongCollections.resourceIterator;
import static org.neo4j.collection.primitive.PrimitiveLongCollections.toPrimitiveIterator;
import static org.neo4j.internal.kernel.api.IndexQuery.IndexQueryType.exact;
import static org.neo4j.kernel.impl.api.PropertyValueComparison.COMPARE_VALUES;
import static org.neo4j.kernel.impl.api.PropertyValueComparison.SuperType.NUMBER;
import static org.neo4j.kernel.impl.api.PropertyValueComparison.SuperType.STRING;
class HashBasedIndex extends InMemoryIndexImplementation
{
private Map<List<Object>,Set<Long>> data;
HashBasedIndex( IndexDescriptor descriptor )
{
super( descriptor );
}
public Map<List<Object>,Set<Long>> data()
{
if ( data == null )
{
throw new IllegalStateException( "Index has not been created, or has been dropped." );
}
return data;
}
@Override
public synchronized String toString()
{
return getClass().getSimpleName() + data;
}
@Override
synchronized void initialize()
{
data = new HashMap<>();
}
@Override
synchronized void drop()
{
data = null;
}
@Override
synchronized PrimitiveLongResourceIterator doIndexSeek( Object... propertyValues )
{
Set<Long> nodes = data().get( Arrays.asList( propertyValues ) );
return asResource( nodes == null ? emptyIterator() : toPrimitiveIterator( nodes.iterator() ) );
}
private synchronized PrimitiveLongResourceIterator rangeSeekByNumberInclusive( Number lower, Number upper )
{
Set<Long> nodeIds = new HashSet<>();
for ( Map.Entry<List<Object>,Set<Long>> entry : data.entrySet() )
{
Object key = entry.getKey().get( 0 );
if ( NUMBER.isSuperTypeOf( key ) )
{
boolean lowerFilter = lower == null || COMPARE_VALUES.compare( key, lower ) >= 0;
boolean upperFilter = upper == null || COMPARE_VALUES.compare( key, upper ) <= 0;
if ( lowerFilter && upperFilter )
{
nodeIds.addAll( entry.getValue() );
}
}
}
return asResource( toPrimitiveIterator( nodeIds.iterator() ) );
}
private synchronized PrimitiveLongResourceIterator rangeSeekByString( String lower, boolean includeLower, String upper,
boolean includeUpper )
{
Set<Long> nodeIds = new HashSet<>();
for ( Map.Entry<List<Object>,Set<Long>> entry : data.entrySet() )
{
Object key = entry.getKey().get( 0 );
if ( STRING.isSuperTypeOf( key ) )
{
boolean lowerFilter;
boolean upperFilter;
if ( lower == null )
{
lowerFilter = true;
}
else
{
int cmp = COMPARE_VALUES.compare( key, lower );
lowerFilter = (includeLower && cmp >= 0) || (cmp > 0);
}
if ( upper == null )
{
upperFilter = true;
}
else
{
int cmp = COMPARE_VALUES.compare( key, upper );
upperFilter = (includeUpper && cmp <= 0) || (cmp < 0);
}
if ( lowerFilter && upperFilter )
{
nodeIds.addAll( entry.getValue() );
}
}
}
return asResource( toPrimitiveIterator( nodeIds.iterator() ) );
}
private synchronized PrimitiveLongResourceIterator rangeSeekByPrefix( String prefix )
{
return stringSearch( entry -> entry.startsWith( prefix ) );
}
private synchronized PrimitiveLongResourceIterator containsString( String exactTerm )
{
return stringSearch( entry -> entry.contains( exactTerm ) );
}
private PrimitiveLongResourceIterator endsWith( String suffix )
{
return stringSearch( entry -> entry.endsWith( suffix ) );
}
private synchronized PrimitiveLongResourceIterator scan()
{
Iterable<Long> all = Iterables.flattenIterable( data.values() );
return asResource( toPrimitiveIterator( all.iterator() ) );
}
@Override
synchronized boolean doAdd( long nodeId, boolean applyIdempotently, Object... propertyValue )
{
Set<Long> nodes = data().computeIfAbsent( Arrays.asList( propertyValue ), k -> new HashSet<>() );
// In this implementation we don't care about idempotency.
return nodes.add( nodeId );
}
@Override
synchronized void doRemove( long nodeId, Object... propertyValues )
{
Set<Long> nodes = data().get( Arrays.asList( propertyValues ) );
if ( nodes != null )
{
nodes.remove( nodeId );
}
}
@Override
synchronized void remove( long nodeId )
{
for ( Set<Long> nodes : data().values() )
{
nodes.remove( nodeId );
}
}
@Override
synchronized void iterateAll( IndexEntryIterator iterator ) throws Exception
{
for ( Map.Entry<List<Object>,Set<Long>> entry : data().entrySet() )
{
iterator.visitEntry( entry.getKey(), entry.getValue() );
}
}
@Override
public synchronized long maxCount()
{
return ids().size();
}
@Override
public synchronized Iterator<Long> iterator()
{
return ids().iterator();
}
private Collection<Long> ids()
{
Set<Long> allIds = new HashSet<>();
for ( Set<Long> someIds : data().values() )
{
allIds.addAll( someIds );
}
return allIds;
}
@Override
synchronized InMemoryIndexImplementation snapshot()
{
HashBasedIndex snapshot = new HashBasedIndex( descriptor );
snapshot.initialize();
for ( Map.Entry<List<Object>,Set<Long>> entry : data().entrySet() )
{
snapshot.data().put( entry.getKey(), new HashSet<>( entry.getValue() ) );
}
return snapshot;
}
@Override
protected synchronized long doCountIndexedNodes( long nodeId, Object... propertyValues )
{
Set<Long> candidates = data().get( Arrays.asList( propertyValues ) );
return candidates != null && candidates.contains( nodeId ) ? 1 : 0;
}
@Override
public synchronized IndexSampler createSampler()
{
return new HashBasedIndexSampler( data );
}
@Override
public PrimitiveLongResourceIterator query( IndexQuery... predicates )
{
if ( predicates.length > 1 )
{
Value[] values = new Value[predicates.length];
for ( int i = 0; i < predicates.length; i++ )
{
assert predicates[i].type() == exact : "composite indexes only supported for seek";
values[i] = ((IndexQuery.ExactPredicate)predicates[i]).value();
}
return seek( values );
}
assert predicates.length == 1 : "composite indexes not yet supported, except for seek on all properties";
IndexQuery predicate = predicates[0];
switch ( predicate.type() )
{
case exists:
return scan();
case exact:
return seek( ((IndexQuery.ExactPredicate) predicate).value() );
case rangeNumeric:
IndexQuery.NumberRangePredicate np = (IndexQuery.NumberRangePredicate) predicate;
return rangeSeekByNumberInclusive( np.from(), np.to() );
case rangeString:
IndexQuery.StringRangePredicate srp = (IndexQuery.StringRangePredicate) predicate;
return rangeSeekByString( srp.from(), srp.fromInclusive(), srp.to(), srp.toInclusive() );
case stringPrefix:
IndexQuery.StringPrefixPredicate spp = (IndexQuery.StringPrefixPredicate) predicate;
return rangeSeekByPrefix( spp.prefix() );
case stringContains:
IndexQuery.StringContainsPredicate scp = (IndexQuery.StringContainsPredicate) predicate;
return containsString( scp.contains() );
case stringSuffix:
IndexQuery.StringSuffixPredicate ssp = (IndexQuery.StringSuffixPredicate) predicate;
return endsWith( ssp.suffix() );
default:
throw new RuntimeException( "Unsupported query: " + Arrays.toString( predicates ) );
}
}
@Override
public boolean hasFullNumberPrecision( IndexQuery... predicates )
{
return false;
}
private interface StringFilter
{
boolean test( String s );
}
private PrimitiveLongResourceIterator stringSearch( StringFilter filter )
{
Set<Long> nodeIds = new HashSet<>();
for ( Map.Entry<List<Object>,Set<Long>> entry : data.entrySet() )
{
Object key = entry.getKey().get( 0 );
if ( key instanceof String )
{
if ( filter.test( (String) key ) )
{
nodeIds.addAll( entry.getValue() );
}
}
}
return asResource( toPrimitiveIterator( nodeIds.iterator() ) );
}
private PrimitiveLongResourceIterator asResource( PrimitiveLongIterator iterator )
{
return resourceIterator( iterator, null );
}
@Override
boolean hasSameContentsAs( InMemoryIndexImplementation other )
{
return this.data.equals( ((HashBasedIndex)other).data );
}
}