Repository navigation
Expand file tree
/
Copy pathIndexMap.java
More file actions
409 lines (375 loc) · 14.9 KB
/
Copy pathIndexMap.java
File metadata and controls
409 lines (375 loc) · 14.9 KB
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
/*
* Copyright (c) 2017-2021 Nitrite author or authors.
*
* 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 org.dizitart.no2.index;
import lombok.Getter;
import lombok.Setter;
import org.dizitart.no2.collection.NitriteId;
import org.dizitart.no2.common.DBNull;
import org.dizitart.no2.common.DBValue;
import org.dizitart.no2.common.tuples.Pair;
import org.dizitart.no2.store.NitriteMap;
import java.util.*;
/**
* @author Anindya Chatterjee
* @since 4.0
*/
@SuppressWarnings("unchecked")
public class IndexMap {
private NitriteMap<DBValue, ?> nitriteMap;
private NavigableMap<DBValue, ?> navigableMap;
// composite layout (non-unique single-field index): the backing map is keyed by
// (value, id) pairs (see IndexEntryKey). This IndexMap still presents the classic
// value -> List<NitriteId> view to the scanner and the filters.
private NitriteMap<IndexEntryKey, ?> compositeMap;
// single-id layout (unique index): values are NitriteIds, exposed as one-element lists
private boolean singleValued;
@Getter
@Setter
private boolean reverseScan;
/**
* Instantiates a new {@link IndexMap}.
*
* @param nitriteMap the nitrite map
*/
public IndexMap(NitriteMap<DBValue, ?> nitriteMap) {
this.nitriteMap = nitriteMap;
}
/**
* Instantiates a new {@link IndexMap}.
*
* @param navigableMap the navigable map
*/
public IndexMap(NavigableMap<DBValue, ?> navigableMap) {
this.navigableMap = navigableMap;
}
private IndexMap(NitriteMap<IndexEntryKey, ?> compositeMap, boolean composite) {
this.compositeMap = compositeMap;
}
/**
* Instantiates an {@link IndexMap} over a non-unique index stored in the composite-key
* layout (one row per {@code (value, id)} pair). The returned map translates between the
* caller's value-keyed view and the underlying {@link IndexEntryKey} rows.
*
* @param compositeMap the backing composite map
* @return the index map
*/
public static IndexMap composite(NitriteMap<IndexEntryKey, ?> compositeMap) {
return new IndexMap(compositeMap, true);
}
/**
* Instantiates an {@link IndexMap} over a unique index stored in the single-id layout
* ({@code value -> id}). The scanner and the filters expect a list of ids under every key,
* so each stored id is handed out as a one-element list.
*
* @param uniqueMap the backing map
* @return the index map
*/
public static IndexMap unique(NitriteMap<DBValue, NitriteId> uniqueMap) {
IndexMap indexMap = new IndexMap(uniqueMap);
indexMap.singleValued = true;
return indexMap;
}
private static Object exposeValue(Object value, boolean singleValued) {
return singleValued && value instanceof NitriteId ? Collections.singletonList(value) : value;
}
/**
* Normalizes a key returned by the backing map to the {@link DBNull} singleton
* when it represents the null key. Persistent stores deserialize the stored null
* key into a fresh {@link DBNull} instance, and every scan loop guards against
* the singleton by identity - so a stored null key must never leak out as-is.
*/
private static DBValue sentinelOrKey(DBValue dbKey) {
return dbKey == null || dbKey instanceof DBNull ? DBNull.getInstance() : dbKey;
}
public DBValue firstKey() {
if (compositeMap != null) {
IndexEntryKey first = compositeMap.firstKey();
return sentinelOrKey(first == null ? null : first.getValue());
}
DBValue dbKey;
if (nitriteMap != null) {
dbKey = nitriteMap.firstKey();
} else if (navigableMap != null) {
dbKey = navigableMap.firstKey();
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
public DBValue lastKey() {
if (compositeMap != null) {
IndexEntryKey last = compositeMap.lastKey();
return sentinelOrKey(last == null ? null : last.getValue());
}
DBValue dbKey;
if (nitriteMap != null) {
dbKey = nitriteMap.lastKey();
} else if (navigableMap != null) {
dbKey = navigableMap.lastKey();
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
/**
* Get the largest key that is smaller than the given key, or null if no
* such key exists.
*
* @param key the key
* @return the t
*/
public DBValue lowerKey(DBValue key) {
DBValue dbKey = key == null ? DBNull.getInstance() : key;
if (compositeMap != null) {
// largest distinct value strictly less than `key`: the lower bracket sorts before
// every (key, id) row, so the largest underlying key below it belongs to a smaller value
IndexEntryKey k = compositeMap.lowerKey(IndexEntryKey.lowerBound(dbKey));
return sentinelOrKey(k == null ? null : k.getValue());
}
if (nitriteMap != null) {
dbKey = nitriteMap.lowerKey(dbKey);
} else if (navigableMap != null) {
dbKey = navigableMap.lowerKey(dbKey);
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
/**
* Get the smallest key that is larger than the given key, or null if no
* such key exists.
*
* @param key the key
* @return the t
*/
public DBValue higherKey(DBValue key) {
DBValue dbKey = key == null ? DBNull.getInstance() : key;
if (compositeMap != null) {
// first distinct value strictly greater than `key`: every (key, id) row sorts at or
// below the upper bracket, so the first underlying key past it belongs to the next value
IndexEntryKey k = compositeMap.higherKey(IndexEntryKey.upperBound(dbKey));
return sentinelOrKey(k == null ? null : k.getValue());
}
if (nitriteMap != null) {
dbKey = nitriteMap.higherKey(dbKey);
} else if (navigableMap != null) {
dbKey = navigableMap.higherKey(dbKey);
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
/**
* Get the smallest key that is larger or equal to this key.
*
* @param key the key
* @return the t
*/
public DBValue ceilingKey(DBValue key) {
DBValue dbKey = key == null ? DBNull.getInstance() : key;
if (compositeMap != null) {
// first distinct value >= `key`: the lower bracket sorts before every (key, id) row
IndexEntryKey k = compositeMap.ceilingKey(IndexEntryKey.lowerBound(dbKey));
return sentinelOrKey(k == null ? null : k.getValue());
}
if (nitriteMap != null) {
dbKey = nitriteMap.ceilingKey(dbKey);
} else if (navigableMap != null) {
dbKey = navigableMap.ceilingKey(dbKey);
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
/**
* Get the largest key that is smaller or equal to this key.
*
* @param key the key
* @return the t
*/
public DBValue floorKey(DBValue key) {
DBValue dbKey = key == null ? DBNull.getInstance() : key;
if (compositeMap != null) {
// largest distinct value <= `key`: every (key, id) row sorts at or below the upper bracket
IndexEntryKey k = compositeMap.floorKey(IndexEntryKey.upperBound(dbKey));
return sentinelOrKey(k == null ? null : k.getValue());
}
if (nitriteMap != null) {
dbKey = nitriteMap.floorKey(dbKey);
} else if (navigableMap != null) {
dbKey = navigableMap.floorKey(dbKey);
} else {
dbKey = null;
}
return sentinelOrKey(dbKey);
}
/**
* Gets the value mapped with the specified key or <code>null</code> otherwise.
*
* @param dbValue the db value
* @return the object
*/
public Object get(DBValue dbValue) {
if (compositeMap != null) {
return compositeGet(dbValue == null ? DBNull.getInstance() : dbValue);
}
if (nitriteMap != null) {
return exposeValue(nitriteMap.get(dbValue), singleValued);
} else if (navigableMap != null) {
return navigableMap.get(dbValue);
}
return null;
}
/**
* Equality lookup in the composite layout: range-scan the leading-value group and collect
* all the trailing ids, returning the same {@code List<NitriteId>} the classic layout would.
*/
private List<NitriteId> compositeGet(DBValue value) {
List<NitriteId> nitriteIds = null;
IndexEntryKey key = compositeMap.ceilingKey(IndexEntryKey.lowerBound(value));
while (key != null && key.getValue().compareTo(value) == 0) {
// navigation over a transactional map can surface keys removed in the current
// transaction; the stored value is null for those, so skip them to keep the id set
// (and any covered-count short-circuit built from it) exact.
if (compositeMap.get(key) != null) {
if (nitriteIds == null) {
nitriteIds = new ArrayList<>();
}
nitriteIds.add(key.getNitriteId());
}
key = compositeMap.higherKey(key);
}
return nitriteIds;
}
/**
* Returns the iterable entries of the indexed items.
*
* @return the iterable
*/
public Iterable<? extends Pair<DBValue, ?>> entries() {
if (compositeMap != null) {
return compositeEntries();
}
if (nitriteMap != null) {
Iterator<? extends Pair<DBValue, ?>> entryIterator;
if (!reverseScan) {
entryIterator = nitriteMap.entries().iterator();
} else {
entryIterator = nitriteMap.reversedEntries().iterator();
}
return (Iterable<Pair<DBValue, ?>>) () -> new Iterator<>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Pair<DBValue, ?> next() {
Pair<DBValue, ?> next = entryIterator.next();
DBValue dbKey = next.getFirst();
Object value = exposeValue(next.getSecond(), singleValued);
if (dbKey instanceof DBNull) {
return new Pair<>(null, value);
} else {
return new Pair<>(dbKey, value);
}
}
};
} else if (navigableMap != null) {
Iterator<? extends Map.Entry<DBValue, ?>> entryIterator;
if (reverseScan) {
entryIterator = navigableMap.descendingMap().entrySet().iterator();
} else {
entryIterator = navigableMap.entrySet().iterator();
}
return (Iterable<Pair<DBValue, ?>>) () -> new Iterator<>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Pair<DBValue, ?> next() {
Map.Entry<DBValue, ?> next = entryIterator.next();
DBValue dbKey = next.getKey();
if (dbKey instanceof DBNull) {
return new Pair<>(null, next.getValue());
} else {
return new Pair<>(dbKey, next.getValue());
}
}
};
}
return Collections.EMPTY_SET;
}
/**
* Groups the sorted flat {@code (value, id)} rows back into one {@code (value, List<ids>)}
* entry per distinct value, so callers (full scans, not-equals/not-in) see the same shape
* as the classic layout.
*/
private Iterable<Pair<DBValue, ?>> compositeEntries() {
Iterator<? extends Pair<IndexEntryKey, ?>> rowIterator = reverseScan
? compositeMap.reversedEntries().iterator()
: compositeMap.entries().iterator();
return () -> new Iterator<>() {
// one-row lookahead buffer used to detect the end of a leading-value group
private Pair<IndexEntryKey, ?> pending = rowIterator.hasNext() ? rowIterator.next() : null;
@Override
public boolean hasNext() {
return pending != null;
}
@Override
public Pair<DBValue, ?> next() {
if (pending == null) {
throw new NoSuchElementException();
}
DBValue groupValue = pending.getFirst().getValue();
List<NitriteId> ids = new ArrayList<>();
ids.add(pending.getFirst().getNitriteId());
pending = rowIterator.hasNext() ? rowIterator.next() : null;
while (pending != null && pending.getFirst().getValue().compareTo(groupValue) == 0) {
ids.add(pending.getFirst().getNitriteId());
pending = rowIterator.hasNext() ? rowIterator.next() : null;
}
DBValue key = groupValue instanceof DBNull ? null : groupValue;
return new Pair<>(key, ids);
}
};
}
/**
* Gets the terminal nitrite ids from this map.
*
* @return the terminal nitrite ids
*/
public List<NitriteId> getTerminalNitriteIds() {
List<NitriteId> terminalResult = new ArrayList<>();
// scan each entry of the navigable map and collect all terminal nitrite-ids
for (Pair<DBValue, ?> entry : entries()) {
// if the value is terminal, collect all nitrite-ids
if (entry.getSecond() instanceof List) {
List<NitriteId> nitriteIds = (List<NitriteId>) entry.getSecond();
terminalResult.addAll(nitriteIds);
}
// if the value is not terminal, scan recursively
if (entry.getSecond() instanceof NavigableMap) {
NavigableMap<DBValue, ?> subMap = (NavigableMap<DBValue, ?>) entry.getSecond();
IndexMap indexMap = new IndexMap(subMap);
List<NitriteId> nitriteIds = indexMap.getTerminalNitriteIds();
terminalResult.addAll(nitriteIds);
}
}
return terminalResult;
}
}