Debian Codegraph @

src/main/org/h2/mvstore/rtree/MVRTreeMap.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore.rtree;
7
8 import java.util.ArrayList;
9 import java.util.Collection;
10 import java.util.Iterator;
11 import java.util.Map;
12
13 import org.h2.mvstore.CursorPos;
14 import org.h2.mvstore.MVMap;
15 import org.h2.mvstore.Page;
16 import org.h2.mvstore.RootReference;
17 import org.h2.mvstore.type.DataType;
18
19 /**
20 * An r-tree implementation. It supports both the linear and the quadratic split
21 * algorithm.
22 *
23 * @param <V> the value class
24 */
25 public final class MVRTreeMap<V> extends MVMap<Spatial, V> {
26
27 /**
28 * The spatial key type.
29 */
30 private final SpatialDataType keyType;
31
32 private boolean quadraticSplit;
33
34 public MVRTreeMap(Map<String, Object> config, SpatialDataType keyType, DataType<V> valueType) {
35 super(config, keyType, valueType);
36 this.keyType = keyType;
37 quadraticSplit = Boolean.parseBoolean(String.valueOf(config.get("quadraticSplit")));
38 }
39
40 private MVRTreeMap(MVRTreeMap<V> source) {
41 super(source);
42 this.keyType = source.keyType;
43 this.quadraticSplit = source.quadraticSplit;
44 }
45
46 @Override
47 public MVRTreeMap<V> cloneIt() {
48 return new MVRTreeMap<>(this);
49 }
50
51 /**
52 * Iterate over all keys that have an intersection with the given rectangle.
53 *
54 * @param x the rectangle
55 * @return the iterator
56 */
57 public RTreeCursor<V> findIntersectingKeys(Spatial x) {
58 return new IntersectsRTreeCursor<>(getRootPage(), x, keyType);
59 }
60
61 /**
62 * Iterate over all keys that are fully contained within the given
63 * rectangle.
64 *
65 * @param x the rectangle
66 * @return the iterator
67 */
68 public RTreeCursor<V> findContainedKeys(Spatial x) {
69 return new ContainsRTreeCursor<>(getRootPage(), x, keyType);
70 }
71
72 private boolean contains(Page<Spatial,V> p, int index, Spatial key) {
73 return keyType.contains(p.getKey(index), key);
74 }
75
76 /**
77 * Get the object for the given key. An exact match is required.
78 *
79 * @param p the page
80 * @param key the key
81 * @return the value, or null if not found
82 */
83 @Override
84 public V get(Page<Spatial,V> p, Spatial key) {
85 int keyCount = p.getKeyCount();
86 if (!p.isLeaf()) {
87 for (int i = 0; i < keyCount; i++) {
88 if (contains(p, i, key)) {
89 V o = get(p.getChildPage(i), key);
90 if (o != null) {
91 return o;
92 }
93 }
94 }
95 } else {
96 for (int i = 0; i < keyCount; i++) {
97 if (keyType.equals(p.getKey(i), key)) {
98 return p.getValue(i);
99 }
100 }
101 }
102 return null;
103 }
104
105 /**
106 * Remove a key-value pair, if the key exists.
107 *
108 * @param key the key (may not be null)
109 * @return the old value if the key existed, or null otherwise
110 */
111 @Override
112 public V remove(Object key) {
113 return operate((Spatial) key, null, DecisionMaker.REMOVE);
114 }
115
116 @Override
117 public V operate(Spatial key, V value, DecisionMaker<? super V> decisionMaker) {
118 int attempt = 0;
119 final Collection<Page<Spatial,V>> removedPages = isPersistent() ? new ArrayList<>() : null;
120 while(true) {
121 RootReference<Spatial,V> rootReference = flushAndGetRoot();
122 if (attempt++ == 0 && !rootReference.isLockedByCurrentThread()) {
123 beforeWrite();
124 }
125 Page<Spatial,V> p = rootReference.root;
126 if (removedPages != null && p.getTotalCount() > 0) {
127 removedPages.add(p);
128 }
129 p = p.copy();
130 V result = operate(p, key, value, decisionMaker, removedPages);
131 if (!p.isLeaf() && p.getTotalCount() == 0) {
132 if (removedPages != null) {
133 removedPages.add(p);
134 }
135 p = createEmptyLeaf();
136 } else if (p.getKeyCount() > store.getKeysPerPage() || p.getMemory() > store.getMaxPageSize()
137 && p.getKeyCount() > 3) {
138 // only possible if this is the root, else we would have
139 // split earlier (this requires pageSplitSize is fixed)
140 long totalCount = p.getTotalCount();
141 Page<Spatial,V> split = split(p);
142 Spatial k1 = getBounds(p);
143 Spatial k2 = getBounds(split);
144 Spatial[] keys = p.createKeyStorage(2);
145 keys[0] = k1;
146 keys[1] = k2;
147 Page.PageReference<Spatial,V>[] children = Page.createRefStorage(3);
148 children[0] = new Page.PageReference<>(p);
149 children[1] = new Page.PageReference<>(split);
150 children[2] = Page.PageReference.empty();
151 p = Page.createNode(this, keys, children, totalCount, 0);
152 registerUnsavedMemory(p.getMemory());
153 }
154
155 if (removedPages == null) {
156 if (updateRoot(rootReference, p, attempt)) {
157 return result;
158 }
159 } else {
160 RootReference<Spatial,V> lockedRootReference = tryLock(rootReference, attempt);
161 if (lockedRootReference != null) {
162 try {
163 long version = lockedRootReference.version;
164 int unsavedMemory = 0;
165 for (Page<Spatial,V> page : removedPages) {
166 if (!page.isRemoved()) {
167 unsavedMemory += page.removePage(version);
168 }
169 }
170 registerUnsavedMemory(unsavedMemory);
171 } finally {
172 unlockRoot(p);
173 }
174 return result;
175 }
176 removedPages.clear();
177 }
178 decisionMaker.reset();
179 }
180 }
181
182 private V operate(Page<Spatial,V> p, Spatial key, V value, DecisionMaker<? super V> decisionMaker,
183 Collection<Page<Spatial,V>> removedPages) {
184 V result;
185 if (p.isLeaf()) {
186 int index = -1;
187 int keyCount = p.getKeyCount();
188 for (int i = 0; i < keyCount; i++) {
189 if (keyType.equals(p.getKey(i), key)) {
190 index = i;
191 }
192 }
193 result = index < 0 ? null : p.getValue(index);
194 Decision decision = decisionMaker.decide(result, value);
195 switch (decision) {
196 case REPEAT:
197 case ABORT:
198 break;
199 case REMOVE:
200 if(index >= 0) {
201 p.remove(index);
202 }
203 break;
204 case PUT:
205 value = decisionMaker.selectValue(result, value);
206 if(index < 0) {
207 p.insertLeaf(p.getKeyCount(), key, value);
208 } else {
209 p.setKey(index, key);
210 p.setValue(index, value);
211 }
212 break;
213 }
214 return result;
215 }
216
217 // p is an internal node
218 int index = -1;
219 for (int i = 0; i < p.getKeyCount(); i++) {
220 if (contains(p, i, key)) {
221 Page<Spatial,V> c = p.getChildPage(i);
222 if(get(c, key) != null) {
223 index = i;
224 break;
225 }
226 if(index < 0) {
227 index = i;
228 }
229 }
230 }
231 if (index < 0) {
232 // a new entry, we don't know where to add yet
233 float min = Float.MAX_VALUE;
234 for (int i = 0; i < p.getKeyCount(); i++) {
235 Spatial k = p.getKey(i);
236 float areaIncrease = keyType.getAreaIncrease(k, key);
237 if (areaIncrease < min) {
238 index = i;
239 min = areaIncrease;
240 }
241 }
242 }
243 Page<Spatial,V> c = p.getChildPage(index);
244 if (removedPages != null) {
245 removedPages.add(c);
246 }
247 c = c.copy();
248 if (c.getKeyCount() > store.getKeysPerPage() || c.getMemory() > store.getMaxPageSize()
249 && c.getKeyCount() > 4) {
250 // split on the way down
251 Page<Spatial,V> split = split(c);
252 p.setKey(index, getBounds(c));
253 p.setChild(index, c);
254 p.insertNode(index, getBounds(split), split);
255 // now we are not sure where to add
256 result = operate(p, key, value, decisionMaker, removedPages);
257 } else {
258 result = operate(c, key, value, decisionMaker, removedPages);
259 Spatial bounds = p.getKey(index);
260 if (!keyType.contains(bounds, key)) {
261 bounds = keyType.createBoundingBox(bounds);
262 keyType.increaseBounds(bounds, key);
263 p.setKey(index, bounds);
264 }
265 if (c.getTotalCount() > 0) {
266 p.setChild(index, c);
267 } else {
268 p.remove(index);
269 }
270 }
271 return result;
272 }
273
274 private Spatial getBounds(Page<Spatial,V> x) {
275 Spatial bounds = keyType.createBoundingBox(x.getKey(0));
276 int keyCount = x.getKeyCount();
277 for (int i = 1; i < keyCount; i++) {
278 keyType.increaseBounds(bounds, x.getKey(i));
279 }
280 return bounds;
281 }
282
283 @Override
284 public V put(Spatial key, V value) {
285 return operate(key, value, DecisionMaker.PUT);
286 }
287
288 /**
289 * Add a given key-value pair. The key should not exist (if it exists, the
290 * result is undefined).
291 *
292 * @param key the key
293 * @param value the value
294 */
295 public void add(Spatial key, V value) {
296 operate(key, value, DecisionMaker.PUT);
297 }
298
299 private Page<Spatial,V> split(Page<Spatial,V> p) {
300 return quadraticSplit ?
301 splitQuadratic(p) :
302 splitLinear(p);
303 }
304
305 private Page<Spatial,V> splitLinear(Page<Spatial,V> p) {
306 int keyCount = p.getKeyCount();
307 ArrayList<Spatial> keys = new ArrayList<>(keyCount);
308 for (int i = 0; i < keyCount; i++) {
309 keys.add(p.getKey(i));
310 }
311 int[] extremes = keyType.getExtremes(keys);
312 if (extremes == null) {
313 return splitQuadratic(p);
314 }
315 Page<Spatial,V> splitA = newPage(p.isLeaf());
316 Page<Spatial,V> splitB = newPage(p.isLeaf());
317 move(p, splitA, extremes[0]);
318 if (extremes[1] > extremes[0]) {
319 extremes[1]--;
320 }
321 move(p, splitB, extremes[1]);
322 Spatial boundsA = keyType.createBoundingBox(splitA.getKey(0));
323 Spatial boundsB = keyType.createBoundingBox(splitB.getKey(0));
324 while (p.getKeyCount() > 0) {
325 Spatial o = p.getKey(0);
326 float a = keyType.getAreaIncrease(boundsA, o);
327 float b = keyType.getAreaIncrease(boundsB, o);
328 if (a < b) {
329 keyType.increaseBounds(boundsA, o);
330 move(p, splitA, 0);
331 } else {
332 keyType.increaseBounds(boundsB, o);
333 move(p, splitB, 0);
334 }
335 }
336 while (splitB.getKeyCount() > 0) {
337 move(splitB, p, 0);
338 }
339 return splitA;
340 }
341
342 private Page<Spatial,V> splitQuadratic(Page<Spatial,V> p) {
343 Page<Spatial,V> splitA = newPage(p.isLeaf());
344 Page<Spatial,V> splitB = newPage(p.isLeaf());
345 float largest = Float.MIN_VALUE;
346 int ia = 0, ib = 0;
347 int keyCount = p.getKeyCount();
348 for (int a = 0; a < keyCount; a++) {
349 Spatial objA = p.getKey(a);
350 for (int b = 0; b < keyCount; b++) {
351 if (a == b) {
352 continue;
353 }
354 Spatial objB = p.getKey(b);
355 float area = keyType.getCombinedArea(objA, objB);
356 if (area > largest) {
357 largest = area;
358 ia = a;
359 ib = b;
360 }
361 }
362 }
363 move(p, splitA, ia);
364 if (ia < ib) {
365 ib--;
366 }
367 move(p, splitB, ib);
368 Spatial boundsA = keyType.createBoundingBox(splitA.getKey(0));
369 Spatial boundsB = keyType.createBoundingBox(splitB.getKey(0));
370 while (p.getKeyCount() > 0) {
371 float diff = 0, bestA = 0, bestB = 0;
372 int best = 0;
373 keyCount = p.getKeyCount();
374 for (int i = 0; i < keyCount; i++) {
375 Spatial o = p.getKey(i);
376 float incA = keyType.getAreaIncrease(boundsA, o);
377 float incB = keyType.getAreaIncrease(boundsB, o);
378 float d = Math.abs(incA - incB);
379 if (d > diff) {
380 diff = d;
381 bestA = incA;
382 bestB = incB;
383 best = i;
384 }
385 }
386 if (bestA < bestB) {
387 keyType.increaseBounds(boundsA, p.getKey(best));
388 move(p, splitA, best);
389 } else {
390 keyType.increaseBounds(boundsB, p.getKey(best));
391 move(p, splitB, best);
392 }
393 }
394 while (splitB.getKeyCount() > 0) {
395 move(splitB, p, 0);
396 }
397 return splitA;
398 }
399
400 private Page<Spatial,V> newPage(boolean leaf) {
401 Page<Spatial,V> page = leaf ? createEmptyLeaf() : createEmptyNode();
402 registerUnsavedMemory(page.getMemory());
403 return page;
404 }
405
406 private static <V> void move(Page<Spatial,V> source, Page<Spatial,V> target, int sourceIndex) {
407 Spatial k = source.getKey(sourceIndex);
408 if (source.isLeaf()) {
409 V v = source.getValue(sourceIndex);
410 target.insertLeaf(0, k, v);
411 } else {
412 Page<Spatial,V> c = source.getChildPage(sourceIndex);
413 target.insertNode(0, k, c);
414 }
415 source.remove(sourceIndex);
416 }
417
418 /**
419 * Add all node keys (including internal bounds) to the given list.
420 * This is mainly used to visualize the internal splits.
421 *
422 * @param list the list
423 * @param p the root page
424 */
425 public void addNodeKeys(ArrayList<Spatial> list, Page<Spatial,V> p) {
426 if (p != null && !p.isLeaf()) {
427 int keyCount = p.getKeyCount();
428 for (int i = 0; i < keyCount; i++) {
429 list.add(p.getKey(i));
430 addNodeKeys(list, p.getChildPage(i));
431 }
432 }
433 }
434
435 @SuppressWarnings("unused")
436 public boolean isQuadraticSplit() {
437 return quadraticSplit;
438 }
439
440 public void setQuadraticSplit(boolean quadraticSplit) {
441 this.quadraticSplit = quadraticSplit;
442 }
443
444 @Override
445 protected int getChildPageCount(Page<Spatial,V> p) {
446 return p.getRawChildPageCount() - 1;
447 }
448
449 /**
450 * A cursor to iterate over a subset of the keys.
451 */
452 public abstract static class RTreeCursor<V> implements Iterator<Spatial> {
453
454 private final Spatial filter;
455 private CursorPos<Spatial,V> pos;
456 private Spatial current;
457 private final Page<Spatial,V> root;
458 private boolean initialized;
459
460 protected RTreeCursor(Page<Spatial,V> root, Spatial filter) {
461 this.root = root;
462 this.filter = filter;
463 }
464
465 @Override
466 public boolean hasNext() {
467 if (!initialized) {
468 // init
469 pos = new CursorPos<>(root, 0, null);
470 fetchNext();
471 initialized = true;
472 }
473 return current != null;
474 }
475
476 /**
477 * Skip over that many entries. This method is relatively fast (for this
478 * map implementation) even if many entries need to be skipped.
479 *
480 * @param n the number of entries to skip
481 */
482 public void skip(long n) {
483 while (hasNext() && n-- > 0) {
484 fetchNext();
485 }
486 }
487
488 @Override
489 public Spatial next() {
490 if (!hasNext()) {
491 return null;
492 }
493 Spatial c = current;
494 fetchNext();
495 return c;
496 }
497
498 /**
499 * Fetch the next entry if there is one.
500 */
501 void fetchNext() {
502 while (pos != null) {
503 Page<Spatial,V> p = pos.page;
504 if (p.isLeaf()) {
505 while (pos.index < p.getKeyCount()) {
506 Spatial c = p.getKey(pos.index++);
507 if (filter == null || check(true, c, filter)) {
508 current = c;
509 return;
510 }
511 }
512 } else {
513 boolean found = false;
514 while (pos.index < p.getKeyCount()) {
515 int index = pos.index++;
516 Spatial c = p.getKey(index);
517 if (filter == null || check(false, c, filter)) {
518 Page<Spatial,V> child = pos.page.getChildPage(index);
519 pos = new CursorPos<>(child, 0, pos);
520 found = true;
521 break;
522 }
523 }
524 if (found) {
525 continue;
526 }
527 }
528 // parent
529 pos = pos.parent;
530 }
531 current = null;
532 }
533
534 /**
535 * Check a given key.
536 *
537 * @param leaf if the key is from a leaf page
538 * @param key the stored key
539 * @param test the user-supplied test key
540 * @return true if there is a match
541 */
542 protected abstract boolean check(boolean leaf, Spatial key, Spatial test);
543 }
544
545 private static final class IntersectsRTreeCursor<V> extends RTreeCursor<V> {
546 private final SpatialDataType keyType;
547
548 public IntersectsRTreeCursor(Page<Spatial,V> root, Spatial filter, SpatialDataType keyType) {
549 super(root, filter);
550 this.keyType = keyType;
551 }
552
553 @Override
554 protected boolean check(boolean leaf, Spatial key,
555 Spatial test) {
556 return keyType.isOverlap(key, test);
557 }
558 }
559
560 private static final class ContainsRTreeCursor<V> extends RTreeCursor<V> {
561 private final SpatialDataType keyType;
562
563 public ContainsRTreeCursor(Page<Spatial,V> root, Spatial filter, SpatialDataType keyType) {
564 super(root, filter);
565 this.keyType = keyType;
566 }
567
568 @Override
569 protected boolean check(boolean leaf, Spatial key, Spatial test) {
570 return leaf ?
571 keyType.isInside(key, test) :
572 keyType.isOverlap(key, test);
573 }
574 }
575
576 @Override
577 public String getType() {
578 return "rtree";
579 }
580
581 /**
582 * A builder for this class.
583 *
584 * @param <V> the value type
585 */
586 public static class Builder<V> extends MVMap.BasicBuilder<MVRTreeMap<V>, Spatial, V> {
587
588 private int dimensions = 2;
589
590 /**
591 * Create a new builder for maps with 2 dimensions.
592 */
593 public Builder() {
594 setKeyType(new SpatialDataType(dimensions));
595 }
596
597 /**
598 * Set the dimensions.
599 *
600 * @param dimensions the dimensions to use
601 * @return this
602 */
603 public Builder<V> dimensions(int dimensions) {
604 this.dimensions = dimensions;
605 setKeyType(new SpatialDataType(dimensions));
606 return this;
607 }
608
609 /**
610 * Set the key data type.
611 *
612 * @param valueType the key type
613 * @return this
614 */
615 @Override
616 public Builder<V> valueType(DataType<? super V> valueType) {
617 setValueType(valueType);
618 return this;
619 }
620
621 @Override
622 public MVRTreeMap<V> create(Map<String, Object> config) {
623 return new MVRTreeMap<>(config, (SpatialDataType)getKeyType(), getValueType());
624 }
625 }
626 }