Skip to content

Apache Lucene open-source search software

LUCENE-6477: add experimental but very fast BKD tree for geo-spatial 'bbox/poly contains indexed lat/lon points' queries

Michael McCandless0311e20f816c
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 4c4073c8a37..1f741fa7cb8 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -50,6 +50,10 @@ New Features
* LUCENE-6487: Spatial Geo3D API now has a WGS84 ellipsoid world model option.
(Karl Wright via David Smiley)
+* LUCENE-6477: Add experimental BKD geospatial tree doc values format
+ and queries, for fast "bbox/polygon contains lat/lon points" (Mike
+ McCandless)
+
Bug fixes
* LUCENE-6500: ParallelCompositeReader did not always call
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointField.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointField.java
new file mode 100644
index 00000000000..8cc1f5b2fa3
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointField.java
@@ -0,0 +1,50 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.FieldType;
+import org.apache.lucene.index.DocValuesType;
+
+/** Add this to a document to index lat/lon point, but be sure to use {@link BKDTreeDocValuesFormat} for the field. */
+public final class BKDPointField extends Field {
+
+ public static final FieldType TYPE = new FieldType();
+ static {
+ TYPE.setDocValuesType(DocValuesType.SORTED_NUMERIC);
+ TYPE.freeze();
+ }
+
+ /**
+ * Creates a new BKDPointField field with the specified lat and lon
+ * @param name field name
+ * @param lat double latitude
+ * @param lon double longitude
+ * @throws IllegalArgumentException if the field name is null or lat or lon are out of bounds
+ */
+ public BKDPointField(String name, double lat, double lon) {
+ super(name, TYPE);
+ if (BKDTreeWriter.validLat(lat) == false) {
+ throw new IllegalArgumentException("invalid lat (" + lat + "): must be -90 to 90");
+ }
+ if (BKDTreeWriter.validLon(lon) == false) {
+ throw new IllegalArgumentException("invalid lon (" + lon + "): must be -180 to 180");
+ }
+ fieldsData = Long.valueOf(((long) BKDTreeWriter.encodeLat(lat) << 32) | (BKDTreeWriter.encodeLon(lon) & 0xffffffffL));
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java
new file mode 100644
index 00000000000..3f96e3a7e3e
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java
@@ -0,0 +1,214 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+import java.util.Set;
+
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.DocIdSet;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.ToStringUtils;
+
+/** Finds all previously indexed points that fall within the specified boundings box.
+ *
+ * <p>The field must be indexed with {@link BKDTreeDocValuesFormat}, and {@link BKDPointField} added per document.
+ *
+ * <p><b>NOTE</b>: for fastest performance, this allocates FixedBitSet(maxDoc) for each segment. The score of each hit is the query boost.
+ *
+ * @lucene.experimental */
+
+public class BKDPointInBBoxQuery extends Query {
+ final String field;
+ final double minLat;
+ final double maxLat;
+ final double minLon;
+ final double maxLon;
+
+ /** Matches all points &gt;= minLon, minLat (inclusive) and &lt; maxLon, maxLat (exclusive). */
+ public BKDPointInBBoxQuery(String field, double minLat, double maxLat, double minLon, double maxLon) {
+ this.field = field;
+ if (BKDTreeWriter.validLat(minLat) == false) {
+ throw new IllegalArgumentException("minLat=" + minLat + " is not a valid latitude");
+ }
+ if (BKDTreeWriter.validLat(maxLat) == false) {
+ throw new IllegalArgumentException("maxLat=" + maxLat + " is not a valid latitude");
+ }
+ if (BKDTreeWriter.validLon(minLon) == false) {
+ throw new IllegalArgumentException("minLon=" + minLon + " is not a valid longitude");
+ }
+ if (BKDTreeWriter.validLon(maxLon) == false) {
+ throw new IllegalArgumentException("maxLon=" + maxLon + " is not a valid longitude");
+ }
+ this.minLon = minLon;
+ this.maxLon = maxLon;
+ this.minLat = minLat;
+ this.maxLat = maxLat;
+ }
+
+ @Override
+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
+
+ // I don't use RandomAccessWeight here: it's no good to approximate with "match all docs"; this is an inverted structure and should be
+ // used in the first pass:
+
+ return new Weight(this) {
+ private float queryNorm;
+ private float queryWeight;
+
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ }
+
+ @Override
+ public float getValueForNormalization() throws IOException {
+ queryWeight = getBoost();
+ return queryWeight * queryWeight;
+ }
+
+ @Override
+ public void normalize(float norm, float topLevelBoost) {
+ queryNorm = norm * topLevelBoost;
+ queryWeight *= queryNorm;
+ }
+
+ @Override
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ final Scorer s = scorer(context, context.reader().getLiveDocs());
+ final boolean exists = s != null && s.advance(doc) == doc;
+
+ if (exists) {
+ return Explanation.match(queryWeight, BKDPointInBBoxQuery.this.toString() + ", product of:",
+ Explanation.match(getBoost(), "boost"), Explanation.match(queryNorm, "queryNorm"));
+ } else {
+ return Explanation.noMatch(BKDPointInBBoxQuery.this.toString() + " doesn't match id " + doc);
+ }
+ }
+
+ @Override
+ public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {
+ LeafReader reader = context.reader();
+ SortedNumericDocValues sdv = reader.getSortedNumericDocValues(field);
+ if (sdv == null) {
+ // No docs in this segment had this field
+ return null;
+ }
+
+ if (sdv instanceof BKDTreeSortedNumericDocValues == false) {
+ throw new IllegalStateException("field \"" + field + "\" was not indexed with BKDTreeDocValuesFormat: got: " + sdv);
+ }
+ BKDTreeSortedNumericDocValues treeDV = (BKDTreeSortedNumericDocValues) sdv;
+ BKDTreeReader tree = treeDV.getBKDTreeReader();
+
+ DocIdSet result = tree.intersect(acceptDocs, minLat, maxLat, minLon, maxLon, treeDV.delegate);
+
+ final DocIdSetIterator disi = result.iterator();
+
+ return new Scorer(this) {
+
+ @Override
+ public float score() throws IOException {
+ return queryWeight;
+ }
+
+ @Override
+ public int freq() throws IOException {
+ return 1;
+ }
+
+ @Override
+ public int docID() {
+ return disi.docID();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return disi.nextDoc();
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ return disi.advance(target);
+ }
+
+ @Override
+ public long cost() {
+ return disi.cost();
+ }
+ };
+ }
+ };
+ }
+ @Override
+ public int hashCode() {
+ int hash = super.hashCode();
+ hash += Double.hashCode(minLat)^0x14fa55fb;
+ hash += Double.hashCode(maxLat)^0x733fa5fe;
+ hash += Double.hashCode(minLon)^0x14fa55fb;
+ hash += Double.hashCode(maxLon)^0x733fa5fe;
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (super.equals(other) && other instanceof BKDPointInBBoxQuery) {
+ final BKDPointInBBoxQuery q = (BKDPointInBBoxQuery) other;
+ return field.equals(q.field) &&
+ minLat == q.minLat &&
+ maxLat == q.maxLat &&
+ minLon == q.minLon &&
+ maxLon == q.maxLon;
+ }
+
+ return false;
+ }
+
+ @Override
+ public String toString(String field) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(getClass().getSimpleName());
+ sb.append(':');
+ if (this.field.equals(field) == false) {
+ sb.append("field=");
+ sb.append(this.field);
+ sb.append(':');
+ }
+
+ return sb.append(" Lower Left: [")
+ .append(minLon)
+ .append(',')
+ .append(minLat)
+ .append(']')
+ .append(" Upper Right: [")
+ .append(maxLon)
+ .append(',')
+ .append(maxLat)
+ .append("]")
+ .append(ToStringUtils.boost(getBoost()))
+ .toString();
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java
new file mode 100644
index 00000000000..36e415b2526
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java
@@ -0,0 +1,284 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Set;
+
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.DocIdSet;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.ToStringUtils;
+
+/** Finds all previously indexed points that fall within the specified polygon.
+ *
+ * <p>The field must be indexed with {@link BKDTreeDocValuesFormat}, and {@link BKDPointField} added per document.
+ *
+ * <p>Because this implementation cannot intersect each cell with the polygon, it will be costly especially for large polygons, as every
+ * possible point must be checked.
+ *
+ * <p><b>NOTE</b>: for fastest performance, this allocates FixedBitSet(maxDoc) for each segment. The score of each hit is the query boost.
+ *
+ * @lucene.experimental */
+
+public class BKDPointInPolygonQuery extends Query {
+ final String field;
+ final double minLat;
+ final double maxLat;
+ final double minLon;
+ final double maxLon;
+ final double[] polyLats;
+ final double[] polyLons;
+
+ /** The lats/lons must be clockwise or counter-clockwise. */
+ public BKDPointInPolygonQuery(String field, double[] polyLats, double[] polyLons) {
+ this.field = field;
+ if (polyLats.length != polyLons.length) {
+ throw new IllegalArgumentException("polyLats and polyLons must be equal length");
+ }
+ if (polyLats.length < 4) {
+ throw new IllegalArgumentException("at least 4 polygon points required");
+ }
+ if (polyLats[0] != polyLats[polyLats.length-1]) {
+ throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLats[0]=" + polyLats[0] + " polyLats[" + (polyLats.length-1) + "]=" + polyLats[polyLats.length-1]);
+ }
+ if (polyLons[0] != polyLons[polyLons.length-1]) {
+ throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLons[0]=" + polyLons[0] + " polyLons[" + (polyLons.length-1) + "]=" + polyLons[polyLons.length-1]);
+ }
+
+ this.polyLats = polyLats;
+ this.polyLons = polyLons;
+
+ double minLon = Double.POSITIVE_INFINITY;
+ double minLat = Double.POSITIVE_INFINITY;
+ double maxLon = Double.NEGATIVE_INFINITY;
+ double maxLat = Double.NEGATIVE_INFINITY;
+ for(int i=0;i<polyLats.length;i++) {
+ double lat = polyLats[i];
+ if (BKDTreeWriter.validLat(lat) == false) {
+ throw new IllegalArgumentException("polyLats[" + i + "]=" + lat + " is not a valid latitude");
+ }
+ minLat = Math.min(minLat, lat);
+ maxLat = Math.max(maxLat, lat);
+ double lon = polyLons[i];
+ if (BKDTreeWriter.validLon(lon) == false) {
+ throw new IllegalArgumentException("polyLons[" + i + "]=" + lat + " is not a valid longitude");
+ }
+ minLon = Math.min(minLon, lon);
+ maxLon = Math.max(maxLon, lon);
+ }
+ this.minLon = minLon;
+ this.maxLon = maxLon;
+ this.minLat = minLat;
+ this.maxLat = maxLat;
+ }
+
+ @Override
+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
+
+ // I don't use RandomAccessWeight here: it's no good to approximate with "match all docs"; this is an inverted structure and should be
+ // used in the first pass:
+
+ // TODO: except that the polygon verify is costly! The approximation should be all docs in all overlapping cells, and matches() should
+ // then check the polygon
+
+ return new Weight(this) {
+ private float queryNorm;
+ private float queryWeight;
+
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ }
+
+ @Override
+ public float getValueForNormalization() throws IOException {
+ queryWeight = getBoost();
+ return queryWeight * queryWeight;
+ }
+
+ @Override
+ public void normalize(float norm, float topLevelBoost) {
+ queryNorm = norm * topLevelBoost;
+ queryWeight *= queryNorm;
+ }
+
+ @Override
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ final Scorer s = scorer(context, context.reader().getLiveDocs());
+ final boolean exists = s != null && s.advance(doc) == doc;
+
+ if (exists) {
+ return Explanation.match(queryWeight, BKDPointInPolygonQuery.this.toString() + ", product of:",
+ Explanation.match(getBoost(), "boost"), Explanation.match(queryNorm, "queryNorm"));
+ } else {
+ return Explanation.noMatch(BKDPointInPolygonQuery.this.toString() + " doesn't match id " + doc);
+ }
+ }
+
+ @Override
+ public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {
+ LeafReader reader = context.reader();
+ SortedNumericDocValues sdv = reader.getSortedNumericDocValues(field);
+ if (sdv == null) {
+ // No docs in this segment had this field
+ return null;
+ }
+
+ if (sdv instanceof BKDTreeSortedNumericDocValues == false) {
+ throw new IllegalStateException("field \"" + field + "\" was not indexed with BKDTreeDocValuesFormat: got: " + sdv);
+ }
+ BKDTreeSortedNumericDocValues treeDV = (BKDTreeSortedNumericDocValues) sdv;
+ BKDTreeReader tree = treeDV.getBKDTreeReader();
+
+ // TODO: make this more efficient: as we recurse the BKD tree we should check whether the
+ // bbox we are recursing into intersects our shape; Apache SIS may have (non-GPL!) code to do this?
+ DocIdSet result = tree.intersect(acceptDocs, minLat, maxLat, minLon, maxLon,
+ new BKDTreeReader.LatLonFilter() {
+ @Override
+ public boolean accept(double lat, double lon) {
+ return pointInPolygon(lat, lon);
+ }
+ }, treeDV.delegate);
+
+ final DocIdSetIterator disi = result.iterator();
+
+ return new Scorer(this) {
+
+ @Override
+ public float score() throws IOException {
+ return queryWeight;
+ }
+
+ @Override
+ public int freq() throws IOException {
+ return 1;
+ }
+
+ @Override
+ public int docID() {
+ return disi.docID();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return disi.nextDoc();
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ return disi.advance(target);
+ }
+
+ @Override
+ public long cost() {
+ return disi.cost();
+ }
+ };
+ }
+ };
+ }
+
+ // TODO: share w/ GeoUtils:
+
+ /**
+ * simple even-odd point in polygon computation
+ * 1. Determine if point is contained in the longitudinal range
+ * 2. Determine whether point crosses the edge by computing the latitudinal delta
+ * between the end-point of a parallel vector (originating at the point) and the
+ * y-component of the edge sink
+ *
+ * NOTE: Requires polygon point (x,y) order either clockwise or counter-clockwise
+ */
+ boolean pointInPolygon(double lat, double lon) {
+ /**
+ * Note: This is using a euclidean coordinate system which could result in
+ * upwards of 110KM error at the equator.
+ * TODO convert coordinates to cylindrical projection (e.g. mercator)
+ */
+
+ // TODO: this quantizes a bit differently ... boundary cases will fail here:
+ boolean inPoly = false;
+ for (int i = 1; i < polyLons.length; i++) {
+ if (polyLons[i] <= lon && polyLons[i-1] > lon || polyLons[i-1] <= lon && polyLons[i] > lon) {
+ if (polyLats[i] + (lon - polyLons[i]) / (polyLons[i-1] - polyLons[i]) * (polyLats[i-1] - polyLats[i]) <= lat) {
+ inPoly = !inPoly;
+ }
+ }
+ }
+ return inPoly;
+ }
+
+ @Override
+ @SuppressWarnings({"unchecked","rawtypes"})
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ if (!super.equals(o)) return false;
+
+ BKDPointInPolygonQuery that = (BKDPointInPolygonQuery) o;
+
+ if (Arrays.equals(polyLons, that.polyLons) == false) {
+ return false;
+ }
+ if (Arrays.equals(polyLats, that.polyLats) == false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public final int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + Arrays.hashCode(polyLons);
+ result = 31 * result + Arrays.hashCode(polyLats);
+ return result;
+ }
+
+ @Override
+ public String toString(String field) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(getClass().getSimpleName());
+ sb.append(':');
+ if (this.field.equals(field) == false) {
+ sb.append(" field=");
+ sb.append(this.field);
+ sb.append(':');
+ }
+ sb.append(" Points: ");
+ for (int i=0; i<polyLons.length; ++i) {
+ sb.append("[")
+ .append(polyLons[i])
+ .append(", ")
+ .append(polyLats[i])
+ .append("] ");
+ }
+ sb.append(ToStringUtils.boost(getBoost()));
+ return sb.toString();
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesConsumer.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesConsumer.java
new file mode 100644
index 00000000000..aa1bf2077eb
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesConsumer.java
@@ -0,0 +1,133 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.DocValuesConsumer;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IOUtils;
+
+class BKDTreeDocValuesConsumer extends DocValuesConsumer implements Closeable {
+ final DocValuesConsumer delegate;
+ final int maxPointsInLeafNode;
+ final int maxPointsSortInHeap;
+ final IndexOutput out;
+ final Map<Integer,Long> fieldIndexFPs = new HashMap<>();
+ final SegmentWriteState state;
+
+ public BKDTreeDocValuesConsumer(DocValuesConsumer delegate, SegmentWriteState state, int maxPointsInLeafNode, int maxPointsSortInHeap) throws IOException {
+ BKDTreeWriter.verifyParams(maxPointsInLeafNode, maxPointsSortInHeap);
+ this.delegate = delegate;
+ this.maxPointsInLeafNode = maxPointsInLeafNode;
+ this.maxPointsSortInHeap = maxPointsSortInHeap;
+ this.state = state;
+ String datFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, BKDTreeDocValuesFormat.DATA_EXTENSION);
+ out = state.directory.createOutput(datFileName, state.context);
+ CodecUtil.writeIndexHeader(out, BKDTreeDocValuesFormat.DATA_CODEC_NAME, BKDTreeDocValuesFormat.DATA_VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ }
+
+ @Override
+ public void close() throws IOException {
+ boolean success = false;
+ try {
+ CodecUtil.writeFooter(out);
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(delegate, out);
+ } else {
+ IOUtils.closeWhileHandlingException(delegate, out);
+ }
+ }
+
+ String metaFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, BKDTreeDocValuesFormat.META_EXTENSION);
+ IndexOutput metaOut = state.directory.createOutput(metaFileName, state.context);
+ success = false;
+ try {
+ CodecUtil.writeIndexHeader(metaOut, BKDTreeDocValuesFormat.META_CODEC_NAME, BKDTreeDocValuesFormat.META_VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ metaOut.writeVInt(fieldIndexFPs.size());
+ for(Map.Entry<Integer,Long> ent : fieldIndexFPs.entrySet()) {
+ metaOut.writeVInt(ent.getKey());
+ metaOut.writeVLong(ent.getValue());
+ }
+ CodecUtil.writeFooter(metaOut);
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(metaOut);
+ } else {
+ IOUtils.closeWhileHandlingException(metaOut);
+ }
+ }
+ }
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ delegate.addSortedNumericField(field, docToValueCount, values);
+ BKDTreeWriter writer = new BKDTreeWriter(maxPointsInLeafNode, maxPointsSortInHeap);
+ Iterator<Number> valueIt = values.iterator();
+ Iterator<Number> valueCountIt = docToValueCount.iterator();
+ for (int docID=0;docID<state.segmentInfo.maxDoc();docID++) {
+ assert valueCountIt.hasNext();
+ int count = valueCountIt.next().intValue();
+ for(int i=0;i<count;i++) {
+ assert valueIt.hasNext();
+ long value = valueIt.next().longValue();
+ int latEnc = (int) (value >> 32);
+ int lonEnc = (int) (value & 0xffffffff);
+ writer.add(latEnc, lonEnc, docID);
+ }
+ }
+
+ long indexStartFP = writer.finish(out);
+
+ fieldIndexFPs.put(field.number, indexStartFP);
+ }
+
+ @Override
+ public void addNumericField(FieldInfo field, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void addBinaryField(FieldInfo field, Iterable<BytesRef> values) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void addSortedField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrd) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesFormat.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesFormat.java
new file mode 100644
index 00000000000..6333716e766
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesFormat.java
@@ -0,0 +1,109 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.codecs.DocValuesConsumer;
+import org.apache.lucene.codecs.DocValuesFormat;
+import org.apache.lucene.codecs.DocValuesProducer;
+import org.apache.lucene.codecs.lucene50.Lucene50DocValuesFormat;
+import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
+
+/**
+ * A {@link DocValuesFormat} to efficiently index geo-spatial lat/lon points
+ * from {@link BKDPointField} for fast bounding-box ({@link BKDPointInBBoxQuery})
+ * and polygon ({@link BKDPointInPolygonQuery}) queries.
+ *
+ * <p>This wraps {@link Lucene50DocValuesFormat}, but saves its own BKD tree
+ * structures to disk for fast query-time intersection. See <a
+ * href="https://www.cs.duke.edu/~pankaj/publications/papers/bkd-sstd.pdf">this paper</a>
+ * for details.
+ *
+ * <p>The BKD tree slices up 2D (lat/lon) space into smaller and
+ * smaller rectangles, until the smallest rectangles have approximately
+ * between X/2 and X (X default is 1024) points in them, at which point
+ * such leaf cells are written as a block to disk, while the index tree
+ * structure recording how space was sub-divided is loaded into HEAP
+ * at search time. At search time, the tree is recursed based on whether
+ * each of left or right child overlap with the query shape, and once
+ * a leaf block is reached, all documents in that leaf block are collected
+ * if the cell is fully enclosed by the query shape, or filtered and then
+ * collected, if not.
+ *
+ * <p>The index is also quite compact, because docs only appear once in
+ * the tree (no "prefix terms").
+ *
+ * <p>In addition to the files written by {@link Lucene50DocValuesFormat}, this format writes:
+ * <ol>
+ * <li><tt>.kdd</tt>: BKD leaf data and index</li>
+ * <li><tt>.kdm</tt>: BKD metadata</li>
+ * </ol>
+ *
+ * <p>The disk format is experimental and free to change suddenly, and this code likely has new and exciting bugs!
+ *
+ * @lucene.experimental */
+
+public class BKDTreeDocValuesFormat extends DocValuesFormat {
+
+ static final String DATA_CODEC_NAME = "BKDData";
+ static final int DATA_VERSION_START = 0;
+ static final int DATA_VERSION_CURRENT = DATA_VERSION_START;
+ static final String DATA_EXTENSION = "kdd";
+
+ static final String META_CODEC_NAME = "BKDMeta";
+ static final int META_VERSION_START = 0;
+ static final int META_VERSION_CURRENT = META_VERSION_START;
+ static final String META_EXTENSION = "kdm";
+
+ private final int maxPointsInLeafNode;
+ private final int maxPointsSortInHeap;
+
+ private final DocValuesFormat delegate = new Lucene50DocValuesFormat();
+
+ /** Default constructor */
+ public BKDTreeDocValuesFormat() {
+ this(BKDTreeWriter.DEFAULT_MAX_POINTS_IN_LEAF_NODE, BKDTreeWriter.DEFAULT_MAX_POINTS_SORT_IN_HEAP);
+ }
+
+ /** Creates this with custom configuration.
+ *
+ * @param maxPointsInLeafNode Maximum number of points in each leaf cell. Smaller values create a deeper tree with larger in-heap index and possibly
+ * faster searching. The default is 1024.
+ * @param maxPointsSortInHeap Maximum number of points where in-heap sort can be used. When the number of points exceeds this, a (slower)
+ * offline sort is used. The default is 128 * 1024.
+ *
+ * @lucene.experimental */
+ public BKDTreeDocValuesFormat(int maxPointsInLeafNode, int maxPointsSortInHeap) {
+ super("BKDTree");
+ BKDTreeWriter.verifyParams(maxPointsInLeafNode, maxPointsSortInHeap);
+ this.maxPointsInLeafNode = maxPointsInLeafNode;
+ this.maxPointsSortInHeap = maxPointsSortInHeap;
+ }
+
+ @Override
+ public DocValuesConsumer fieldsConsumer(final SegmentWriteState state) throws IOException {
+ return new BKDTreeDocValuesConsumer(delegate.fieldsConsumer(state), state, maxPointsInLeafNode, maxPointsSortInHeap);
+ }
+
+ @Override
+ public DocValuesProducer fieldsProducer(SegmentReadState state) throws IOException {
+ return new BKDTreeDocValuesProducer(delegate.fieldsProducer(state), state);
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesProducer.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesProducer.java
new file mode 100644
index 00000000000..0283a7247d4
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeDocValuesProducer.java
@@ -0,0 +1,169 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.DocValuesProducer;
+import org.apache.lucene.index.BinaryDocValues;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.store.ChecksumIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.Accountables;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.RamUsageEstimator;
+
+class BKDTreeDocValuesProducer extends DocValuesProducer {
+
+ private final Map<String,BKDTreeReader> treeReaders = new HashMap<>();
+ private final Map<Integer,Long> fieldToIndexFPs = new HashMap<>();
+
+ private final IndexInput datIn;
+ private final AtomicLong ramBytesUsed;
+ private final int maxDoc;
+ private final DocValuesProducer delegate;
+ private final boolean merging;
+
+ public BKDTreeDocValuesProducer(DocValuesProducer delegate, SegmentReadState state) throws IOException {
+ String metaFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, BKDTreeDocValuesFormat.META_EXTENSION);
+ ChecksumIndexInput metaIn = state.directory.openChecksumInput(metaFileName, state.context);
+ CodecUtil.checkIndexHeader(metaIn, BKDTreeDocValuesFormat.META_CODEC_NAME, BKDTreeDocValuesFormat.META_VERSION_START, BKDTreeDocValuesFormat.META_VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ int fieldCount = metaIn.readVInt();
+ for(int i=0;i<fieldCount;i++) {
+ int fieldNumber = metaIn.readVInt();
+ long indexFP = metaIn.readVLong();
+ fieldToIndexFPs.put(fieldNumber, indexFP);
+ }
+ CodecUtil.checkFooter(metaIn);
+ metaIn.close();
+
+ String datFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, BKDTreeDocValuesFormat.DATA_EXTENSION);
+ datIn = state.directory.openInput(datFileName, state.context);
+ CodecUtil.checkIndexHeader(datIn, BKDTreeDocValuesFormat.DATA_CODEC_NAME, BKDTreeDocValuesFormat.DATA_VERSION_START, BKDTreeDocValuesFormat.DATA_VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ ramBytesUsed = new AtomicLong(RamUsageEstimator.shallowSizeOfInstance(getClass()));
+ maxDoc = state.segmentInfo.maxDoc();
+ this.delegate = delegate;
+ merging = false;
+ }
+
+ // clone for merge: we don't hang onto the BKDTrees we load
+ BKDTreeDocValuesProducer(BKDTreeDocValuesProducer orig) throws IOException {
+ assert Thread.holdsLock(orig);
+ datIn = orig.datIn.clone();
+ ramBytesUsed = new AtomicLong(orig.ramBytesUsed.get());
+ delegate = orig.delegate.getMergeInstance();
+ fieldToIndexFPs.putAll(orig.fieldToIndexFPs);
+ treeReaders.putAll(orig.treeReaders);
+ merging = true;
+ maxDoc = orig.maxDoc;
+ }
+
+ @Override
+ public synchronized SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ BKDTreeReader treeReader = treeReaders.get(field.name);
+ if (treeReader == null) {
+ // Lazy load
+ Long fp = fieldToIndexFPs.get(field.number);
+ if (fp == null) {
+ throw new IllegalArgumentException("this field was not indexed as a BKDPointField");
+ }
+ datIn.seek(fp);
+ treeReader = new BKDTreeReader(datIn, maxDoc);
+
+ // Only hang onto the reader when we are not merging:
+ if (merging == false) {
+ treeReaders.put(field.name, treeReader);
+ ramBytesUsed.addAndGet(treeReader.ramBytesUsed());
+ }
+ }
+
+ return new BKDTreeSortedNumericDocValues(treeReader, delegate.getSortedNumeric(field));
+ }
+
+ @Override
+ public void close() throws IOException {
+ IOUtils.close(datIn, delegate);
+ }
+
+ @Override
+ public void checkIntegrity() throws IOException {
+ CodecUtil.checksumEntireFile(datIn);
+ }
+
+ @Override
+ public NumericDocValues getNumeric(FieldInfo field) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public BinaryDocValues getBinary(FieldInfo field) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public SortedDocValues getSorted(FieldInfo field) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public SortedSetDocValues getSortedSet(FieldInfo field) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Bits getDocsWithField(FieldInfo field) throws IOException {
+ return delegate.getDocsWithField(field);
+ }
+
+ @Override
+ public synchronized Collection<Accountable> getChildResources() {
+ List<Accountable> resources = new ArrayList<>();
+ for(Map.Entry<String,BKDTreeReader> ent : treeReaders.entrySet()) {
+ resources.add(Accountables.namedAccountable("field " + ent.getKey(), ent.getValue()));
+ }
+
+ return resources;
+ }
+
+ @Override
+ public synchronized DocValuesProducer getMergeInstance() throws IOException {
+ return new BKDTreeDocValuesProducer(this);
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return ramBytesUsed.get();
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeReader.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeReader.java
new file mode 100644
index 00000000000..59f94721cb5
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeReader.java
@@ -0,0 +1,385 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.search.DocIdSet;
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.BitDocIdSet;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.RamUsageEstimator;
+
+/** Handles intersection of a shape with a BKD tree previously written with {@link BKDTreeWriter}.
+ *
+ * @lucene.experimental */
+
+final class BKDTreeReader implements Accountable {
+ final private int[] splitValues;
+ final private int leafNodeOffset;
+ final private long[] leafBlockFPs;
+ final int maxDoc;
+ final IndexInput in;
+
+ interface LatLonFilter {
+ boolean accept(double lat, double lon);
+ }
+
+ public BKDTreeReader(IndexInput in, int maxDoc) throws IOException {
+
+ // Read index:
+ int numLeaves = in.readVInt();
+ leafNodeOffset = numLeaves;
+
+ // Tree is fully balanced binary tree, so number of nodes = numLeaves-1, except our nodeIDs are 1-based (splitValues[0] is unused):
+ splitValues = new int[numLeaves];
+ for(int i=0;i<numLeaves;i++) {
+ splitValues[i] = in.readInt();
+ }
+ leafBlockFPs = new long[numLeaves];
+ for(int i=0;i<numLeaves;i++) {
+ leafBlockFPs[i] = in.readVLong();
+ }
+
+ this.maxDoc = maxDoc;
+ this.in = in;
+ }
+
+ private static final class QueryState {
+ final IndexInput in;
+ byte[] scratch = new byte[16];
+ final ByteArrayDataInput scratchReader = new ByteArrayDataInput(scratch);
+ final FixedBitSet bits;
+ final int latMinEnc;
+ final int latMaxEnc;
+ final int lonMinEnc;
+ final int lonMaxEnc;
+ final LatLonFilter latLonFilter;
+ final SortedNumericDocValues sndv;
+
+ public QueryState(IndexInput in, int maxDoc,
+ int latMinEnc, int latMaxEnc,
+ int lonMinEnc, int lonMaxEnc,
+ LatLonFilter latLonFilter,
+ SortedNumericDocValues sndv) {
+ this.in = in;
+ this.bits = new FixedBitSet(maxDoc);
+ this.latMinEnc = latMinEnc;
+ this.latMaxEnc = latMaxEnc;
+ this.lonMinEnc = lonMinEnc;
+ this.lonMaxEnc = lonMaxEnc;
+ this.latLonFilter = latLonFilter;
+ this.sndv = sndv;
+ }
+ }
+
+ public DocIdSet intersect(Bits acceptDocs, double latMin, double latMax, double lonMin, double lonMax, SortedNumericDocValues sndv) throws IOException {
+ return intersect(acceptDocs, latMin, latMax, lonMin, lonMax, null, sndv);
+ }
+
+ public DocIdSet intersect(Bits acceptDocs, double latMin, double latMax, double lonMin, double lonMax, LatLonFilter filter, SortedNumericDocValues sndv) throws IOException {
+ if (BKDTreeWriter.validLat(latMin) == false) {
+ throw new IllegalArgumentException("invalid latMin: " + latMin);
+ }
+ if (BKDTreeWriter.validLat(latMax) == false) {
+ throw new IllegalArgumentException("invalid latMax: " + latMax);
+ }
+ if (BKDTreeWriter.validLon(lonMin) == false) {
+ throw new IllegalArgumentException("invalid lonMin: " + lonMin);
+ }
+ if (BKDTreeWriter.validLon(lonMax) == false) {
+ throw new IllegalArgumentException("invalid lonMax: " + lonMax);
+ }
+
+ int latMinEnc = BKDTreeWriter.encodeLat(latMin);
+ int latMaxEnc = BKDTreeWriter.encodeLat(latMax);
+ int lonMinEnc = BKDTreeWriter.encodeLon(lonMin);
+ int lonMaxEnc = BKDTreeWriter.encodeLon(lonMax);
+
+ // TODO: we should use a sparse bit collector here, but BitDocIdSet.Builder is 2.4X slower than straight FixedBitSet.
+ // Maybe we should use simple int[] (not de-duping) up until size X, then cutover. Or maybe SentinelIntSet when it's
+ // small.
+
+ QueryState state = new QueryState(in.clone(), maxDoc,
+ latMinEnc, latMaxEnc,
+ lonMinEnc, lonMaxEnc,
+ filter,
+ sndv);
+
+ int hitCount = intersect(acceptDocs, state, 1,
+ BKDTreeWriter.encodeLat(-90.0),
+ BKDTreeWriter.encodeLat(Math.nextAfter(90.0, Double.POSITIVE_INFINITY)),
+ BKDTreeWriter.encodeLon(-180.0),
+ BKDTreeWriter.encodeLon(Math.nextAfter(180.0, Double.POSITIVE_INFINITY)));
+
+ // NOTE: hitCount is an over-estimate in the multi-valued case:
+ return new BitDocIdSet(state.bits, hitCount);
+ }
+
+ /** Fast path: this is called when the query rect fully encompasses all cells under this node. */
+ private int addAll(Bits acceptDocs, QueryState state, int nodeID) throws IOException {
+ if (nodeID >= leafNodeOffset) {
+ // Leaf node
+ long fp = leafBlockFPs[nodeID-leafNodeOffset];
+ //System.out.println(" leaf nodeID=" + nodeID + " vs leafNodeOffset=" + leafNodeOffset + " fp=" + fp);
+ if (fp == 0) {
+ // Dead end node (adversary case):
+ return 0;
+ }
+ //IndexInput in = leafDISI.in;
+ state.in.seek(fp);
+ //allLeafDISI.reset(fp);
+
+ //System.out.println(" seek to leafFP=" + fp);
+ // How many points are stored in this leaf cell:
+ int count = state.in.readVInt();
+ if (state.latLonFilter != null) {
+ // Handle this differently since we must also look up lat/lon:
+
+ int hitCount = 0;
+ for(int i=0;i<count;i++) {
+
+ int docID = state.in.readInt();
+
+ if (acceptDocs == null || acceptDocs.get(docID)) {
+
+ state.sndv.setDocument(docID);
+
+ // How many values this doc has:
+ int docValueCount = state.sndv.count();
+ for(int j=0;j<docValueCount;j++) {
+ long enc = state.sndv.valueAt(j);
+ int latEnc = (int) ((enc>>32) & 0xffffffffL);
+ int lonEnc = (int) (enc & 0xffffffffL);
+
+ // TODO: maybe we can fix LatLonFilter to operate on encoded forms?
+ if (state.latLonFilter.accept(BKDTreeWriter.decodeLat(latEnc), BKDTreeWriter.decodeLon(lonEnc))) {
+ state.bits.set(docID);
+ hitCount++;
+
+ // Stop processing values for this doc since it's now accepted:
+ break;
+ }
+ }
+ }
+ }
+
+ return hitCount;
+
+ } else if (acceptDocs != null) {
+ for(int i=0;i<count;i++) {
+ int docID = state.in.readInt();
+ if (acceptDocs.get(docID)) {
+ state.bits.set(docID);
+ }
+ }
+ } else {
+ for(int i=0;i<count;i++) {
+ int docID = state.in.readInt();
+ state.bits.set(docID);
+ }
+ }
+
+ //bits.or(allLeafDISI);
+ //return allLeafDISI.getHitCount();
+ return count;
+ } else {
+ int splitValue = splitValues[nodeID];
+
+ if (splitValue == Integer.MAX_VALUE) {
+ // Dead end node (adversary case):
+ return 0;
+ }
+
+ //System.out.println(" splitValue=" + splitValue);
+
+ //System.out.println(" addAll: inner");
+ int count = 0;
+ count += addAll(acceptDocs, state, 2*nodeID);
+ count += addAll(acceptDocs, state, 2*nodeID+1);
+ //System.out.println(" addAll: return count=" + count);
+ return count;
+ }
+ }
+
+ private int intersect(Bits acceptDocs, QueryState state,
+ int nodeID,
+ int cellLatMinEnc, int cellLatMaxEnc, int cellLonMinEnc, int cellLonMaxEnc)
+ throws IOException {
+
+ // 2.06 sec -> 1.52 sec for 225 OSM London queries:
+ if (state.latMinEnc <= cellLatMinEnc && state.latMaxEnc >= cellLatMaxEnc && state.lonMinEnc <= cellLonMinEnc && state.lonMaxEnc >= cellLonMaxEnc) {
+ // Optimize the case when the query fully contains this cell: we can
+ // recursively add all points without checking if they match the query:
+
+ /*
+ System.out.println("A: " + BKDTreeWriter.decodeLat(cellLatMinEnc)
+ + " " + BKDTreeWriter.decodeLat(cellLatMaxEnc)
+ + " " + BKDTreeWriter.decodeLon(cellLonMinEnc)
+ + " " + BKDTreeWriter.decodeLon(cellLonMaxEnc));
+ */
+
+ return addAll(acceptDocs, state, nodeID);
+ }
+
+ long latRange = (long) cellLatMaxEnc - (long) cellLatMinEnc;
+ long lonRange = (long) cellLonMaxEnc - (long) cellLonMinEnc;
+
+ int dim;
+ if (latRange >= lonRange) {
+ dim = 0;
+ } else {
+ dim = 1;
+ }
+
+ //System.out.println("\nintersect node=" + nodeID + " vs " + leafNodeOffset);
+
+ if (nodeID >= leafNodeOffset) {
+ // Leaf node; scan and filter all points in this block:
+ //System.out.println(" intersect leaf nodeID=" + nodeID + " vs leafNodeOffset=" + leafNodeOffset + " fp=" + leafBlockFPs[nodeID-leafNodeOffset]);
+ int hitCount = 0;
+
+ //IndexInput in = leafDISI.in;
+ long fp = leafBlockFPs[nodeID-leafNodeOffset];
+ if (fp == 0) {
+ // Dead end node (adversary case):
+ //System.out.println(" dead-end leaf");
+ return 0;
+ }
+
+ /*
+ System.out.println("I: " + BKDTreeWriter.decodeLat(cellLatMinEnc)
+ + " " + BKDTreeWriter.decodeLat(cellLatMaxEnc)
+ + " " + BKDTreeWriter.decodeLon(cellLonMinEnc)
+ + " " + BKDTreeWriter.decodeLon(cellLonMaxEnc));
+ */
+
+ state.in.seek(fp);
+
+ // How many points are stored in this leaf cell:
+ int count = state.in.readVInt();
+
+ for(int i=0;i<count;i++) {
+ int docID = state.in.readInt();
+ if (acceptDocs == null || acceptDocs.get(docID)) {
+ state.sndv.setDocument(docID);
+ // How many values this doc has:
+ int docValueCount = state.sndv.count();
+ for(int j=0;j<docValueCount;j++) {
+ long enc = state.sndv.valueAt(j);
+
+ int latEnc = (int) ((enc>>32) & 0xffffffffL);
+ int lonEnc = (int) (enc & 0xffffffffL);
+
+ if (latEnc >= state.latMinEnc &&
+ latEnc < state.latMaxEnc &&
+ lonEnc >= state.lonMinEnc &&
+ lonEnc < state.lonMaxEnc &&
+ (state.latLonFilter == null ||
+ state.latLonFilter.accept(BKDTreeWriter.decodeLat(latEnc), BKDTreeWriter.decodeLon(lonEnc)))) {
+ state.bits.set(docID);
+ hitCount++;
+
+ // Stop processing values for this doc:
+ break;
+ }
+ }
+ }
+ }
+
+ return hitCount;
+
+ // this (using BitDocIdSet.Builder) is 3.4X slower!
+ /*
+ //bits.or(leafDISI);
+ //return leafDISI.getHitCount();
+ */
+
+ } else {
+
+ int splitValue = splitValues[nodeID];
+
+ if (splitValue == Integer.MAX_VALUE) {
+ // Dead end node (adversary case):
+ //System.out.println(" dead-end sub-tree");
+ return 0;
+ }
+
+ //System.out.println(" splitValue=" + splitValue);
+
+ int count = 0;
+
+ if (dim == 0) {
+
+ //System.out.println(" split on lat=" + splitValue);
+
+ // Inner node split on lat:
+
+ // Left node:
+ if (state.latMinEnc < splitValue) {
+ //System.out.println(" recurse left");
+ count += intersect(acceptDocs, state,
+ 2*nodeID,
+ cellLatMinEnc, splitValue, cellLonMinEnc, cellLonMaxEnc);
+ }
+
+ // Right node:
+ if (state.latMaxEnc >= splitValue) {
+ //System.out.println(" recurse right");
+ count += intersect(acceptDocs, state,
+ 2*nodeID+1,
+ splitValue, cellLatMaxEnc, cellLonMinEnc, cellLonMaxEnc);
+ }
+
+ } else {
+ // Inner node split on lon:
+ assert dim == 1;
+
+ // System.out.println(" split on lon=" + splitValue);
+
+ // Left node:
+ if (state.lonMinEnc < splitValue) {
+ // System.out.println(" recurse left");
+ count += intersect(acceptDocs, state,
+ 2*nodeID,
+ cellLatMinEnc, cellLatMaxEnc, cellLonMinEnc, splitValue);
+ }
+
+ // Right node:
+ if (state.lonMaxEnc >= splitValue) {
+ // System.out.println(" recurse right");
+ count += intersect(acceptDocs, state,
+ 2*nodeID+1,
+ cellLatMinEnc, cellLatMaxEnc, splitValue, cellLonMaxEnc);
+ }
+ }
+
+ return count;
+ }
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return splitValues.length * RamUsageEstimator.NUM_BYTES_INT +
+ leafBlockFPs.length * RamUsageEstimator.NUM_BYTES_LONG;
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeSortedNumericDocValues.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeSortedNumericDocValues.java
new file mode 100644
index 00000000000..1a2c1796623
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeSortedNumericDocValues.java
@@ -0,0 +1,49 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import org.apache.lucene.index.SortedNumericDocValues;
+
+class BKDTreeSortedNumericDocValues extends SortedNumericDocValues {
+ final BKDTreeReader bkdTreeReader;
+ final SortedNumericDocValues delegate;
+
+ public BKDTreeSortedNumericDocValues(BKDTreeReader bkdTreeReader, SortedNumericDocValues delegate) {
+ this.bkdTreeReader = bkdTreeReader;
+ this.delegate = delegate;
+ }
+
+ public BKDTreeReader getBKDTreeReader() {
+ return bkdTreeReader;
+ }
+
+ @Override
+ public void setDocument(int doc) {
+ delegate.setDocument(doc);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return delegate.valueAt(index);
+ }
+
+ @Override
+ public int count() {
+ return delegate.count();
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeWriter.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeWriter.java
new file mode 100644
index 00000000000..2d02ee96e02
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDTreeWriter.java
@@ -0,0 +1,897 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Comparator;
+
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.store.ByteArrayDataOutput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.InPlaceMergeSorter;
+import org.apache.lucene.util.LongBitSet;
+import org.apache.lucene.util.OfflineSorter.ByteSequencesWriter;
+import org.apache.lucene.util.OfflineSorter;
+import org.apache.lucene.util.RamUsageEstimator;
+
+// TODO
+// - could we just "use postings" to map leaf -> docIDs?
+// - the polygon query really should be 2-phase
+// - if we could merge trees, we could drop delegating to wrapped DV?
+// - we could also index "auto-prefix terms" here, and use better compression, and maybe only use for the "fully contained" case so we'd
+// only index docIDs
+// - the index could be efficiently encoded as an FST, so we don't have wasteful
+// (monotonic) long[] leafBlockFPs; or we could use MonotonicLongValues ... but then
+// the index is already plenty small: 60M OSM points --> 1.1 MB with 128 points
+// per leaf, and you can reduce that by putting more points per leaf
+// - we can quantize the split values to 2 bytes (short): http://people.csail.mit.edu/tmertens/papers/qkdtree.pdf
+// - we could use threads while building; the higher nodes are very parallelizable
+// - generalize to N dimenions? i think there are reasonable use cases here, e.g.
+// 2 dimensional points to store houses, plus e.g. 3rd dimension for "household income"
+// - geo3d integration should be straightforward? better accuracy, faster performance for small-poly-with-bbox cases? right now the poly
+// check is very costly...
+
+/** Recursively builds a BKD tree to assign all incoming points to smaller
+ * and smaller rectangles until the number of points in a given
+ * rectangle is &lt= the <code>maxPointsInLeafNode</code>. The tree is
+ * fully balanced, which means the leaf nodes will have between 50% and 100% of
+ * the requested <code>maxPointsInLeafNode</code>, except for the adversarial case
+ * of indexing exactly the same point many times.
+ *
+ * <p>
+ * See <a href="https://www.cs.duke.edu/~pankaj/publications/papers/bkd-sstd.pdf">this paper</a> for details.
+ *
+ * <p>This consumes heap during writing: it allocates a <code>LongBitSet(numPoints)</code>,
+ * and for any nodes with fewer than <code>maxPointsSortInHeap</code>, it holds
+ * the points in memory as simple java arrays.
+ *
+ * <p>
+ * <b>NOTE</b>: This can write at most Integer.MAX_VALUE * <code>maxPointsInLeafNode</code> total points.
+ *
+ * @lucene.experimental */
+
+class BKDTreeWriter {
+
+ // latEnc (int) + lonEnc (int) + ord (long) + docID (int)
+ static final int BYTES_PER_DOC = RamUsageEstimator.NUM_BYTES_LONG + 3 * RamUsageEstimator.NUM_BYTES_INT;
+
+ //static final boolean DEBUG = false;
+
+ public static final int DEFAULT_MAX_POINTS_IN_LEAF_NODE = 1024;
+
+ /** This works out to max of ~10 MB peak heap tied up during writing: */
+ public static final int DEFAULT_MAX_POINTS_SORT_IN_HEAP = 128*1024;;
+
+ private final byte[] scratchBytes = new byte[BYTES_PER_DOC];
+ private final ByteArrayDataOutput scratchBytesOutput = new ByteArrayDataOutput(scratchBytes);
+
+ private OfflineSorter.ByteSequencesWriter writer;
+ private GrowingHeapLatLonWriter heapWriter;
+
+ private Path tempInput;
+ private Path tempDir;
+ private final int maxPointsInLeafNode;
+ private final int maxPointsSortInHeap;
+
+ private long pointCount;
+
+ public BKDTreeWriter() throws IOException {
+ this(DEFAULT_MAX_POINTS_IN_LEAF_NODE, DEFAULT_MAX_POINTS_SORT_IN_HEAP);
+ }
+
+ // TODO: instead of maxPointsSortInHeap, change to maxMBHeap ... the mapping is non-obvious:
+ public BKDTreeWriter(int maxPointsInLeafNode, int maxPointsSortInHeap) throws IOException {
+ verifyParams(maxPointsInLeafNode, maxPointsSortInHeap);
+ this.maxPointsInLeafNode = maxPointsInLeafNode;
+ this.maxPointsSortInHeap = maxPointsSortInHeap;
+
+ // We write first maxPointsSortInHeap in heap, then cutover to offline for additional points:
+ heapWriter = new GrowingHeapLatLonWriter(maxPointsSortInHeap);
+ }
+
+ public static void verifyParams(int maxPointsInLeafNode, int maxPointsSortInHeap) {
+ if (maxPointsInLeafNode <= 0) {
+ throw new IllegalArgumentException("maxPointsInLeafNode must be > 0; got " + maxPointsInLeafNode);
+ }
+ if (maxPointsInLeafNode > ArrayUtil.MAX_ARRAY_LENGTH) {
+ throw new IllegalArgumentException("maxPointsInLeafNode must be <= ArrayUtil.MAX_ARRAY_LENGTH (= " + ArrayUtil.MAX_ARRAY_LENGTH + "); got " + maxPointsInLeafNode);
+ }
+ if (maxPointsSortInHeap < maxPointsInLeafNode) {
+ throw new IllegalArgumentException("maxPointsSortInHeap must be >= maxPointsInLeafNode; got " + maxPointsSortInHeap + " vs maxPointsInLeafNode="+ maxPointsInLeafNode);
+ }
+ if (maxPointsSortInHeap > ArrayUtil.MAX_ARRAY_LENGTH) {
+ throw new IllegalArgumentException("maxPointsSortInHeap must be <= ArrayUtil.MAX_ARRAY_LENGTH (= " + ArrayUtil.MAX_ARRAY_LENGTH + "); got " + maxPointsSortInHeap);
+ }
+ }
+
+ public void add(double lat, double lon, int docID) throws IOException {
+
+ if (validLat(lat) == false) {
+ throw new IllegalArgumentException("invalid lat: " + lat);
+ }
+ if (validLon(lon) == false) {
+ throw new IllegalArgumentException("invalid lon: " + lon);
+ }
+
+ // Quantize to 32 bit precision, which is plenty: ~.0093 meter precision (longitude) at the equator
+ add(encodeLat(lat), encodeLon(lon), docID);
+ }
+
+ /** If the current segment has too many points then we switchover to temp files / offline sort. */
+ private void switchToOffline() throws IOException {
+
+ // OfflineSorter isn't thread safe, but our own private tempDir works around this:
+ tempDir = Files.createTempDirectory(OfflineSorter.defaultTempDir(), BKDTreeWriter.class.getSimpleName());
+
+ // For each .add we just append to this input file, then in .finish we sort this input and resursively build the tree:
+ tempInput = tempDir.resolve("in");
+ writer = new OfflineSorter.ByteSequencesWriter(tempInput);
+ for(int i=0;i<pointCount;i++) {
+ scratchBytesOutput.reset(scratchBytes);
+ scratchBytesOutput.writeInt(heapWriter.latEncs[i]);
+ scratchBytesOutput.writeInt(heapWriter.lonEncs[i]);
+ scratchBytesOutput.writeVInt(heapWriter.docIDs[i]);
+ scratchBytesOutput.writeVLong(i);
+ // TODO: can/should OfflineSorter optimize the fixed-width case?
+ writer.write(scratchBytes, 0, scratchBytes.length);
+ }
+
+ heapWriter = null;
+ }
+
+ void add(int latEnc, int lonEnc, int docID) throws IOException {
+ assert latEnc > Integer.MIN_VALUE;
+ assert latEnc < Integer.MAX_VALUE;
+ assert lonEnc > Integer.MIN_VALUE;
+ assert lonEnc < Integer.MAX_VALUE;
+
+ if (pointCount >= maxPointsSortInHeap) {
+ if (writer == null) {
+ switchToOffline();
+ }
+ scratchBytesOutput.reset(scratchBytes);
+ scratchBytesOutput.writeInt(latEnc);
+ scratchBytesOutput.writeInt(lonEnc);
+ scratchBytesOutput.writeVInt(docID);
+ scratchBytesOutput.writeVLong(pointCount);
+ writer.write(scratchBytes, 0, scratchBytes.length);
+ } else {
+ // Not too many points added yet, continue using heap:
+ heapWriter.append(latEnc, lonEnc, pointCount, docID);
+ }
+
+ pointCount++;
+ }
+
+ /** Changes incoming {@link ByteSequencesWriter} file to to fixed-width-per-entry file, because we need to be able to slice
+ * as we recurse in {@link #build}. */
+ private LatLonWriter convertToFixedWidth(Path in) throws IOException {
+ BytesRefBuilder scratch = new BytesRefBuilder();
+ scratch.grow(BYTES_PER_DOC);
+ BytesRef bytes = scratch.get();
+ ByteArrayDataInput dataReader = new ByteArrayDataInput();
+
+ OfflineSorter.ByteSequencesReader reader = null;
+ LatLonWriter sortedWriter = null;
+ boolean success = false;
+ try {
+ reader = new OfflineSorter.ByteSequencesReader(in);
+ sortedWriter = getWriter(pointCount);
+ for (long i=0;i<pointCount;i++) {
+ boolean result = reader.read(scratch);
+ assert result;
+ dataReader.reset(bytes.bytes, bytes.offset, bytes.length);
+ int latEnc = dataReader.readInt();
+ int lonEnc = dataReader.readInt();
+ int docID = dataReader.readVInt();
+ long ord = dataReader.readVLong();
+ assert docID >= 0: "docID=" + docID;
+ assert latEnc > Integer.MIN_VALUE;
+ assert latEnc < Integer.MAX_VALUE;
+ assert lonEnc > Integer.MIN_VALUE;
+ assert lonEnc < Integer.MAX_VALUE;
+ sortedWriter.append(latEnc, lonEnc, ord, docID);
+ }
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(sortedWriter, reader);
+ } else {
+ IOUtils.closeWhileHandlingException(reader);
+ try {
+ sortedWriter.destroy();
+ } catch (Throwable t) {
+ // Suppress to keep throwing original exc
+ }
+ }
+ }
+
+ return sortedWriter;
+ }
+
+ private LatLonWriter sort(boolean lon) throws IOException {
+ if (heapWriter != null) {
+
+ assert pointCount < Integer.MAX_VALUE;
+
+ // All buffered points are still in heap
+ new InPlaceMergeSorter() {
+ @Override
+ protected void swap(int i, int j) {
+ int docID = heapWriter.docIDs[i];
+ heapWriter.docIDs[i] = heapWriter.docIDs[j];
+ heapWriter.docIDs[j] = docID;
+
+ long ord = heapWriter.ords[i];
+ heapWriter.ords[i] = heapWriter.ords[j];
+ heapWriter.ords[j] = ord;
+
+ int latEnc = heapWriter.latEncs[i];
+ heapWriter.latEncs[i] = heapWriter.latEncs[j];
+ heapWriter.latEncs[j] = latEnc;
+
+ int lonEnc = heapWriter.lonEncs[i];
+ heapWriter.lonEncs[i] = heapWriter.lonEncs[j];
+ heapWriter.lonEncs[j] = lonEnc;
+ }
+
+ @Override
+ protected int compare(int i, int j) {
+ int cmp;
+ if (lon) {
+ cmp = Integer.compare(heapWriter.lonEncs[i], heapWriter.lonEncs[j]);
+ } else {
+ cmp = Integer.compare(heapWriter.latEncs[i], heapWriter.latEncs[j]);
+ }
+ if (cmp != 0) {
+ return cmp;
+ }
+
+ // Tie-break
+ cmp = Integer.compare(heapWriter.docIDs[i], heapWriter.docIDs[j]);
+ if (cmp != 0) {
+ return cmp;
+ }
+
+ return Long.compare(heapWriter.ords[i], heapWriter.ords[j]);
+ }
+ }.sort(0, (int) pointCount);
+
+ HeapLatLonWriter sorted = new HeapLatLonWriter((int) pointCount);
+ for(int i=0;i<pointCount;i++) {
+ sorted.append(heapWriter.latEncs[i],
+ heapWriter.lonEncs[i],
+ heapWriter.ords[i],
+ heapWriter.docIDs[i]);
+ }
+
+ return sorted;
+ } else {
+
+ // Offline sort:
+ assert tempDir != null;
+
+ final ByteArrayDataInput reader = new ByteArrayDataInput();
+ Comparator<BytesRef> cmp = new Comparator<BytesRef>() {
+ private final ByteArrayDataInput readerB = new ByteArrayDataInput();
+
+ @Override
+ public int compare(BytesRef a, BytesRef b) {
+ reader.reset(a.bytes, a.offset, a.length);
+ final int latAEnc = reader.readInt();
+ final int lonAEnc = reader.readInt();
+ final int docIDA = reader.readVInt();
+ final long ordA = reader.readVLong();
+
+ reader.reset(b.bytes, b.offset, b.length);
+ final int latBEnc = reader.readInt();
+ final int lonBEnc = reader.readInt();
+ final int docIDB = reader.readVInt();
+ final long ordB = reader.readVLong();
+
+ int cmp;
+ if (lon) {
+ cmp = Integer.compare(lonAEnc, lonBEnc);
+ } else {
+ cmp = Integer.compare(latAEnc, latBEnc);
+ }
+ if (cmp != 0) {
+ return cmp;
+ }
+
+ // Tie-break
+ cmp = Integer.compare(docIDA, docIDB);
+ if (cmp != 0) {
+ return cmp;
+ }
+
+ return Long.compare(ordA, ordB);
+ }
+ };
+
+ Path sorted = tempDir.resolve("sorted");
+ boolean success = false;
+ try {
+ OfflineSorter latSorter = new OfflineSorter(cmp, OfflineSorter.BufferSize.automatic(), tempDir, OfflineSorter.MAX_TEMPFILES);
+ latSorter.sort(tempInput, sorted);
+ LatLonWriter writer = convertToFixedWidth(sorted);
+ success = true;
+ return writer;
+ } finally {
+ if (success) {
+ IOUtils.rm(sorted);
+ } else {
+ IOUtils.deleteFilesIgnoringExceptions(sorted);
+ }
+ }
+ }
+ }
+
+ /** Writes the BKD tree to the provided {@link IndexOutput} and returns the file offset where index was written. */
+ public long finish(IndexOutput out) throws IOException {
+ //System.out.println("\nBKDTreeWriter.finish pointCount=" + pointCount + " out=" + out + " heapWriter=" + heapWriter);
+
+ if (writer != null) {
+ writer.close();
+ }
+
+ LongBitSet bitSet = new LongBitSet(pointCount);
+
+ // TODO: we should use in-memory sort here, if number of points is small enough:
+
+ long countPerLeaf = pointCount;
+ long innerNodeCount = 1;
+
+ while (countPerLeaf > maxPointsInLeafNode) {
+ countPerLeaf /= 2;
+ innerNodeCount *= 2;
+ }
+
+ //System.out.println("innerNodeCount=" + innerNodeCount);
+
+ if (1+2*innerNodeCount >= Integer.MAX_VALUE) {
+ throw new IllegalStateException("too many nodes; increase maxPointsInLeafNode (currently " + maxPointsInLeafNode + ") and reindex");
+ }
+
+ innerNodeCount--;
+
+ int numLeaves = (int) (innerNodeCount+1);
+
+ // Indexed by nodeID, but first (root) nodeID is 1
+ int[] splitValues = new int[numLeaves];
+
+ // +1 because leaf count is power of 2 (e.g. 8), and innerNodeCount is power of 2 minus 1 (e.g. 7)
+ long[] leafBlockFPs = new long[numLeaves];
+
+ // Make sure the math above "worked":
+ assert pointCount / splitValues.length <= maxPointsInLeafNode: "pointCount=" + pointCount + " splitValues.length=" + splitValues.length + " maxPointsInLeafNode=" + maxPointsInLeafNode;
+ //System.out.println(" avg pointsPerLeaf=" + (pointCount/splitValues.length));
+
+ // Sort all docs once by lat, once by lon:
+ LatLonWriter latSortedWriter = null;
+ LatLonWriter lonSortedWriter = null;
+
+ boolean success = false;
+ try {
+ lonSortedWriter = sort(true);
+ latSortedWriter = sort(false);
+ heapWriter = null;
+
+ build(1, numLeaves, new PathSlice(latSortedWriter, 0, pointCount),
+ new PathSlice(lonSortedWriter, 0, pointCount),
+ bitSet, out,
+ Integer.MIN_VALUE, Integer.MAX_VALUE,
+ Integer.MIN_VALUE, Integer.MAX_VALUE,
+ //encodeLat(-90.0), encodeLat(Math.nextAfter(90.0, Double.POSITIVE_INFINITY)),
+ //encodeLon(-180.0), encodeLon(Math.nextAfter(180.0, Double.POSITIVE_INFINITY)),
+ splitValues,
+ leafBlockFPs);
+ success = true;
+ } finally {
+ if (success) {
+ latSortedWriter.destroy();
+ lonSortedWriter.destroy();
+ IOUtils.rm(tempInput);
+ } else {
+ try {
+ latSortedWriter.destroy();
+ } catch (Throwable t) {
+ // Suppress to keep throwing original exc
+ }
+ try {
+ lonSortedWriter.destroy();
+ } catch (Throwable t) {
+ // Suppress to keep throwing original exc
+ }
+ IOUtils.deleteFilesIgnoringExceptions(tempInput);
+ }
+ }
+
+ //System.out.println("Total nodes: " + innerNodeCount);
+
+ // Write index:
+ long indexFP = out.getFilePointer();
+ out.writeVInt(numLeaves);
+
+ // NOTE: splitValues[0] is unused, because nodeID is 1-based:
+ for (int i=0;i<splitValues.length;i++) {
+ out.writeInt(splitValues[i]);
+ }
+ for (int i=0;i<leafBlockFPs.length;i++) {
+ out.writeVLong(leafBlockFPs[i]);
+ }
+
+ if (tempDir != null) {
+ // If we had to go offline, we should have removed all temp files we wrote:
+ assert directoryIsEmpty(tempDir);
+ IOUtils.rm(tempDir);
+ }
+
+ return indexFP;
+ }
+
+ // Called only from assert
+ private boolean directoryIsEmpty(Path in) {
+ try (DirectoryStream<Path> dir = Files.newDirectoryStream(in)) {
+ for (Path path : dir) {
+ assert false: "dir=" + in + " still has file=" + path;
+ return false;
+ }
+ } catch (IOException ioe) {
+ // Just ignore: we are only called from assert
+ }
+ return true;
+ }
+
+ /** Sliced reference to points in an OfflineSorter.ByteSequencesWriter file. */
+ private static final class PathSlice {
+ final LatLonWriter writer;
+ final long start;
+ final long count;
+
+ public PathSlice(LatLonWriter writer, long start, long count) {
+ this.writer = writer;
+ this.start = start;
+ this.count = count;
+ }
+
+ @Override
+ public String toString() {
+ return "PathSlice(start=" + start + " count=" + count + " writer=" + writer + ")";
+ }
+ }
+
+ /** Marks bits for the ords (points) that belong in the left sub tree. */
+ private long markLeftTree(int splitDim, PathSlice source, LongBitSet bitSet, int[] splitValueRet,
+ int minLatEnc, int maxLatEnc, int minLonEnc, int maxLonEnc) throws IOException {
+
+ // This is the initital size of our left tree, but we may lower it below for == case:
+ long leftCount = source.count / 2;
+
+ // Read the split value:
+ //if (DEBUG) System.out.println(" leftCount=" + leftCount + " vs " + source.count);
+ LatLonReader reader = source.writer.getReader(source.start + leftCount);
+ boolean success = false;
+ int splitValue;
+ try {
+ boolean result = reader.next();
+ assert result;
+
+ int latSplitEnc = reader.latEnc();
+ assert latSplitEnc >= minLatEnc && latSplitEnc < maxLatEnc: "latSplitEnc=" + latSplitEnc + " minLatEnc=" + minLatEnc + " maxLatEnc=" + maxLatEnc;
+
+ int lonSplitEnc = reader.lonEnc();
+ assert lonSplitEnc >= minLonEnc && lonSplitEnc < maxLonEnc: "lonSplitEnc=" + lonSplitEnc + " minLonEnc=" + minLonEnc + " maxLonEnc=" + maxLonEnc;
+
+ if (splitDim == 0) {
+ splitValue = latSplitEnc;
+ //if (DEBUG) System.out.println(" splitValue=" + decodeLat(splitValue));
+ } else {
+ splitValue = lonSplitEnc;
+ //if (DEBUG) System.out.println(" splitValue=" + decodeLon(splitValue));
+ }
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(reader);
+ } else {
+ IOUtils.closeWhileHandlingException(reader);
+ }
+ }
+
+ splitValueRet[0] = splitValue;
+
+ // Mark ords that fall into the left half, and also handle the == boundary case:
+ assert bitSet.cardinality() == 0: "cardinality=" + bitSet.cardinality();
+
+ success = false;
+ reader = source.writer.getReader(source.start);
+ try {
+ int lastValue = Integer.MIN_VALUE;
+ for (int i=0;i<leftCount;i++) {
+ boolean result = reader.next();
+ assert result;
+ int latEnc = reader.latEnc();
+ int lonEnc = reader.lonEnc();
+
+ int value;
+ if (splitDim == 0) {
+ value = latEnc;
+ } else {
+ value = lonEnc;
+ }
+
+ // Our input source is supposed to be sorted on the incoming dimension:
+ assert value >= lastValue;
+ lastValue = value;
+
+ if (value == splitValue) {
+ // If we have identical points at the split, we move the count back to before the identical points:
+ leftCount = i;
+ break;
+ }
+ assert value < splitValue: "i=" + i + " value=" + value + " vs splitValue=" + splitValue;
+ long ord = reader.ord();
+ int docID = reader.docID();
+ assert docID >= 0: "docID=" + docID + " reader=" + reader;
+
+ // We should never see dup ords:
+ assert bitSet.get(ord) == false;
+ bitSet.set(ord);
+ }
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(reader);
+ } else {
+ IOUtils.closeWhileHandlingException(reader);
+ }
+ }
+
+ assert leftCount == bitSet.cardinality(): "leftCount=" + leftCount + " cardinality=" + bitSet.cardinality();
+
+ return leftCount;
+ }
+
+ /** dim=0 means we split on lat, dim=1 means lon. The incoming PathSlice for the dim we will split is already partitioned/sorted. */
+ private void build(int nodeID, int leafNodeOffset,
+ PathSlice lastLatSorted,
+ PathSlice lastLonSorted,
+ LongBitSet bitSet,
+ IndexOutput out,
+ int minLatEnc, int maxLatEnc, int minLonEnc, int maxLonEnc,
+ int[] splitValues,
+ long[] leafBlockFPs) throws IOException {
+
+ PathSlice source;
+ PathSlice nextSource;
+
+ long latRange = (long) maxLatEnc - (long) minLatEnc;
+ long lonRange = (long) maxLonEnc - (long) minLonEnc;
+
+ int splitDim;
+ if (latRange >= lonRange) {
+ // Split by lat:
+ splitDim = 0;
+ source = lastLatSorted;
+ nextSource = lastLonSorted;
+ } else {
+ // Split by lon:
+ splitDim = 1;
+ source = lastLonSorted;
+ nextSource = lastLatSorted;
+ }
+
+ long count = source.count;
+
+ //if (DEBUG) System.out.println("\nBUILD: nodeID=" + nodeID + " leafNodeOffset=" + leafNodeOffset + " splitDim=" + splitDim + "\n lastLatSorted=" + lastLatSorted + "\n lastLonSorted=" + lastLonSorted + "\n count=" + count + " lat=" + decodeLat(minLatEnc) + " TO " + decodeLat(maxLatEnc) + " lon=" + decodeLon(minLonEnc) + " TO " + decodeLon(maxLonEnc));
+
+ if (count == 0) {
+ // Dead end in the tree, due to adversary cases, e.g. many identical points:
+ if (nodeID < splitValues.length) {
+ // Sentinel used to mark that the tree is dead under here:
+ splitValues[nodeID] = Integer.MAX_VALUE;
+ }
+ //if (DEBUG) System.out.println(" dead-end sub-tree");
+ return;
+ }
+
+ if (nodeID >= leafNodeOffset) {
+ // Leaf node: write block
+ //if (DEBUG) System.out.println(" leaf");
+ assert maxLatEnc > minLatEnc;
+ assert maxLonEnc > minLonEnc;
+
+ //System.out.println("\nleaf:\n lat range: " + ((long) maxLatEnc-minLatEnc));
+ //System.out.println(" lon range: " + ((long) maxLonEnc-minLonEnc));
+
+ assert count == source.count: "count=" + count + " vs source.count=" + source.count;
+
+ // Sort by docID in the leaf so we can .or(DISI) at search time:
+ LatLonReader reader = source.writer.getReader(source.start);
+
+ int[] docIDs = new int[(int) count];
+
+ boolean success = false;
+ try {
+ for (int i=0;i<source.count;i++) {
+
+ // NOTE: we discard ord at this point; we only needed it temporarily
+ // during building to uniquely identify each point to properly handle
+ // the multi-valued case (one docID having multiple values):
+
+ // We also discard lat/lon, since at search time, we reside on the
+ // wrapped doc values for this:
+
+ boolean result = reader.next();
+ assert result;
+ docIDs[i] = reader.docID();
+ }
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(reader);
+ } else {
+ IOUtils.closeWhileHandlingException(reader);
+ }
+ }
+
+ Arrays.sort(docIDs);
+
+ // Dedup docIDs: for the multi-valued case where more than one value for the doc
+ // wound up in this leaf cell, we only need to store the docID once:
+ int lastDocID = -1;
+ int uniqueCount = 0;
+ for(int i=0;i<docIDs.length;i++) {
+ int docID = docIDs[i];
+ if (docID != lastDocID) {
+ uniqueCount++;
+ lastDocID = docID;
+ }
+ }
+ assert uniqueCount <= count;
+
+ long startFP = out.getFilePointer();
+ out.writeVInt(uniqueCount);
+
+ // Save the block file pointer:
+ leafBlockFPs[nodeID - leafNodeOffset] = startFP;
+ //System.out.println(" leafFP=" + startFP);
+
+ lastDocID = -1;
+ for (int i=0;i<docIDs.length;i++) {
+ // Absolute int encode; with "vInt of deltas" encoding, the .kdd size dropped from
+ // 697 MB -> 539 MB, but query time for 225 queries went from 1.65 sec -> 2.64 sec.
+ // I think if we also indexed prefix terms here we could do less costly compression
+ // on those lists:
+ int docID = docIDs[i];
+ if (docID != lastDocID) {
+ out.writeInt(docID);
+ lastDocID = docID;
+ }
+ }
+ //long endFP = out.getFilePointer();
+ //System.out.println(" bytes/doc: " + ((endFP - startFP) / count));
+ } else {
+ // Inner node: sort, partition/recurse
+
+ assert nodeID < splitValues.length: "nodeID=" + nodeID + " splitValues.length=" + splitValues.length;
+
+ int[] splitValueArray = new int[1];
+
+ assert source.count == count;
+ long leftCount = markLeftTree(splitDim, source, bitSet, splitValueArray,
+ minLatEnc, maxLatEnc, minLonEnc, maxLonEnc);
+ int splitValue = splitValueArray[0];
+
+ // TODO: we could save split value in here so we don't have to re-open file later:
+
+ // Partition nextSource into sorted left and right sets, so we can recurse. This is somewhat hairy: we partition the next lon set
+ // according to how we had just partitioned the lat set, and vice/versa:
+
+ LatLonWriter leftWriter = null;
+ LatLonWriter rightWriter = null;
+ LatLonReader reader = null;
+
+ boolean success = false;
+
+ int nextLeftCount = 0;
+
+ try {
+ leftWriter = getWriter(leftCount);
+ rightWriter = getWriter(nextSource.count - leftCount);
+
+ //if (DEBUG) System.out.println(" partition:\n splitValueEnc=" + splitValue + "\n " + nextSource + "\n --> leftSorted=" + leftWriter + "\n --> rightSorted=" + rightWriter + ")");
+ assert nextSource.count == count;
+ reader = nextSource.writer.getReader(nextSource.start);
+
+ // TODO: we could compute the split value here for each sub-tree and save an O(N) pass on recursion, but makes code hairier and only
+ // changes the constant factor of building, not the big-oh:
+ for (int i=0;i<nextSource.count;i++) {
+ boolean result = reader.next();
+ assert result;
+ int latEnc = reader.latEnc();
+ int lonEnc = reader.lonEnc();
+ long ord = reader.ord();
+ int docID = reader.docID();
+ assert docID >= 0: "docID=" + docID + " reader=" + reader;
+ if (bitSet.get(ord)) {
+ if (splitDim == 0) {
+ assert latEnc < splitValue: "latEnc=" + latEnc + " splitValue=" + splitValue;
+ } else {
+ assert lonEnc < splitValue: "lonEnc=" + lonEnc + " splitValue=" + splitValue;
+ }
+ leftWriter.append(latEnc, lonEnc, ord, docID);
+ nextLeftCount++;
+ } else {
+ if (splitDim == 0) {
+ assert latEnc >= splitValue: "latEnc=" + latEnc + " splitValue=" + splitValue;
+ } else {
+ assert lonEnc >= splitValue: "lonEnc=" + lonEnc + " splitValue=" + splitValue;
+ }
+ rightWriter.append(latEnc, lonEnc, ord, docID);
+ }
+ }
+ bitSet.clear(0, pointCount);
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(reader, leftWriter, rightWriter);
+ } else {
+ IOUtils.closeWhileHandlingException(reader, leftWriter, rightWriter);
+ }
+ }
+
+ assert leftCount == nextLeftCount: "leftCount=" + leftCount + " nextLeftCount=" + nextLeftCount;
+ assert count == nextSource.count: "count=" + count + " nextSource.count=" + count;
+
+ success = false;
+ try {
+ if (splitDim == 0) {
+ //if (DEBUG) System.out.println(" recurse left");
+ build(2*nodeID, leafNodeOffset,
+ new PathSlice(source.writer, source.start, leftCount),
+ new PathSlice(leftWriter, 0, leftCount),
+ bitSet,
+ out,
+ minLatEnc, splitValue, minLonEnc, maxLonEnc,
+ splitValues, leafBlockFPs);
+ leftWriter.destroy();
+
+ //if (DEBUG) System.out.println(" recurse right");
+ build(2*nodeID+1, leafNodeOffset,
+ new PathSlice(source.writer, source.start+leftCount, count-leftCount),
+ new PathSlice(rightWriter, 0, count - leftCount),
+ bitSet,
+ out,
+ splitValue, maxLatEnc, minLonEnc, maxLonEnc,
+ splitValues, leafBlockFPs);
+ rightWriter.destroy();
+ } else {
+ //if (DEBUG) System.out.println(" recurse left");
+ build(2*nodeID, leafNodeOffset,
+ new PathSlice(leftWriter, 0, leftCount),
+ new PathSlice(source.writer, source.start, leftCount),
+ bitSet,
+ out,
+ minLatEnc, maxLatEnc, minLonEnc, splitValue,
+ splitValues, leafBlockFPs);
+
+ leftWriter.destroy();
+
+ //if (DEBUG) System.out.println(" recurse right");
+ build(2*nodeID+1, leafNodeOffset,
+ new PathSlice(rightWriter, 0, count-leftCount),
+ new PathSlice(source.writer, source.start+leftCount, count-leftCount),
+ bitSet,
+ out,
+ minLatEnc, maxLatEnc, splitValue, maxLonEnc,
+ splitValues, leafBlockFPs);
+ rightWriter.destroy();
+ }
+ success = true;
+ } finally {
+ if (success == false) {
+ try {
+ leftWriter.destroy();
+ } catch (Throwable t) {
+ // Suppress to keep throwing original exc
+ }
+ try {
+ rightWriter.destroy();
+ } catch (Throwable t) {
+ // Suppress to keep throwing original exc
+ }
+ }
+ }
+
+ splitValues[nodeID] = splitValue;
+ }
+ }
+
+ LatLonWriter getWriter(long count) throws IOException {
+ if (count < maxPointsSortInHeap) {
+ return new HeapLatLonWriter((int) count);
+ } else {
+ return new OfflineLatLonWriter(tempDir, count);
+ }
+ }
+
+ // TODO: move/share all this into GeoUtils
+
+ // We allow one iota over the true max:
+ static final double MAX_LAT_INCL = Math.nextAfter(90.0D, Double.POSITIVE_INFINITY);
+ static final double MAX_LON_INCL = Math.nextAfter(180.0D, Double.POSITIVE_INFINITY);
+ static final double MIN_LAT_INCL = -90.0D;
+ static final double MIN_LON_INCL = -180.0D;
+
+ static boolean validLat(double lat) {
+ return Double.isNaN(lat) == false && lat >= MIN_LAT_INCL && lat <= MAX_LAT_INCL;
+ }
+
+ static boolean validLon(double lon) {
+ return Double.isNaN(lon) == false && lon >= MIN_LON_INCL && lon <= MAX_LON_INCL;
+ }
+
+ private static final int BITS = 32;
+
+ // -3 so valid lat/lon never hit the Integer.MIN_VALUE nor Integer.MAX_VALUE:
+ private static final double LON_SCALE = ((0x1L<<BITS)-3)/360.0D;
+ private static final double LAT_SCALE = ((0x1L<<BITS)-3)/180.0D;
+
+ /** Max quantization error for both lat and lon when encoding/decoding into 32 bits */
+ public static final double TOLERANCE = 1E-7;
+
+ /** Quantizes double (64 bit) latitude into 32 bits */
+ static int encodeLat(double lat) {
+ assert validLat(lat): "lat=" + lat;
+ long x = (long) (lat * LAT_SCALE);
+ // We use Integer.MAX_VALUE as a sentinel:
+ assert x < Integer.MAX_VALUE: "lat=" + lat + " mapped to Integer.MAX_VALUE + " + (x - Integer.MAX_VALUE);
+ assert x > Integer.MIN_VALUE: "lat=" + lat + " mapped to Integer.MIN_VALUE";
+ return (int) x;
+ }
+
+ /** Quantizes double (64 bit) longitude into 32 bits */
+ static int encodeLon(double lon) {
+ assert validLon(lon): "lon=" + lon;
+ long x = (long) (lon * LON_SCALE);
+ // We use Integer.MAX_VALUE as a sentinel:
+ assert x < Integer.MAX_VALUE;
+ assert x > Integer.MIN_VALUE;
+ return (int) x;
+ }
+
+ /** Turns quantized value from {@link #encodeLat} back into a double. */
+ static double decodeLat(int x) {
+ return x / LAT_SCALE;
+ }
+
+ /** Turns quantized value from {@link #encodeLon} back into a double. */
+ static double decodeLon(int x) {
+ return x / LON_SCALE;
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/GrowingHeapLatLonWriter.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/GrowingHeapLatLonWriter.java
new file mode 100644
index 00000000000..742fc4f8321
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/GrowingHeapLatLonWriter.java
@@ -0,0 +1,88 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.RamUsageEstimator;
+
+final class GrowingHeapLatLonWriter implements LatLonWriter {
+ int[] latEncs;
+ int[] lonEncs;
+ int[] docIDs;
+ long[] ords;
+ private int nextWrite;
+ final int maxSize;
+
+ public GrowingHeapLatLonWriter(int maxSize) {
+ latEncs = new int[16];
+ lonEncs = new int[16];
+ docIDs = new int[16];
+ ords = new long[16];
+ this.maxSize = maxSize;
+ }
+
+ private int[] growExact(int[] arr, int size) {
+ assert size > arr.length;
+ int[] newArr = new int[size];
+ System.arraycopy(arr, 0, newArr, 0, arr.length);
+ return newArr;
+ }
+
+ private long[] growExact(long[] arr, int size) {
+ assert size > arr.length;
+ long[] newArr = new long[size];
+ System.arraycopy(arr, 0, newArr, 0, arr.length);
+ return newArr;
+ }
+
+ @Override
+ public void append(int latEnc, int lonEnc, long ord, int docID) {
+ assert ord == nextWrite;
+ if (latEncs.length == nextWrite) {
+ int nextSize = Math.min(maxSize, ArrayUtil.oversize(nextWrite+1, RamUsageEstimator.NUM_BYTES_INT));
+ assert nextSize > nextWrite: "nextSize=" + nextSize + " vs nextWrite=" + nextWrite;
+ latEncs = growExact(latEncs, nextSize);
+ lonEncs = growExact(lonEncs, nextSize);
+ ords = growExact(ords, nextSize);
+ docIDs = growExact(docIDs, nextSize);
+ }
+ latEncs[nextWrite] = latEnc;
+ lonEncs[nextWrite] = lonEnc;
+ ords[nextWrite] = ord;
+ docIDs[nextWrite] = docID;
+ nextWrite++;
+ }
+
+ @Override
+ public LatLonReader getReader(long start) {
+ return new HeapLatLonReader(latEncs, lonEncs, ords, docIDs, (int) start, nextWrite);
+ }
+
+ @Override
+ public void close() {
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ @Override
+ public String toString() {
+ return "GrowingHeapLatLonWriter(count=" + nextWrite + " alloc=" + latEncs.length + ")";
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonReader.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonReader.java
new file mode 100644
index 00000000000..67940f6bbea
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonReader.java
@@ -0,0 +1,67 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+final class HeapLatLonReader implements LatLonReader {
+ private int curRead;
+ final int[] latEncs;
+ final int[] lonEncs;
+ final long[] ords;
+ final int[] docIDs;
+ final int end;
+
+ HeapLatLonReader(int[] latEncs, int[] lonEncs, long[] ords, int[] docIDs, int start, int end) {
+ this.latEncs = latEncs;
+ this.lonEncs = lonEncs;
+ this.ords = ords;
+ this.docIDs = docIDs;
+ curRead = start-1;
+ this.end = end;
+ }
+
+ @Override
+ public boolean next() {
+ curRead++;
+ return curRead < end;
+ }
+
+ @Override
+ public int latEnc() {
+ return latEncs[curRead];
+ }
+
+ @Override
+ public int lonEnc() {
+ return lonEncs[curRead];
+ }
+
+ @Override
+ public int docID() {
+ return docIDs[curRead];
+ }
+
+ @Override
+ public long ord() {
+ return ords[curRead];
+ }
+
+ @Override
+ public void close() {
+ }
+}
+
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonWriter.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonWriter.java
new file mode 100644
index 00000000000..0bf68a24ce7
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/HeapLatLonWriter.java
@@ -0,0 +1,63 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+final class HeapLatLonWriter implements LatLonWriter {
+ final int[] latEncs;
+ final int[] lonEncs;
+ final int[] docIDs;
+ final long[] ords;
+ private int nextWrite;
+
+ public HeapLatLonWriter(int count) {
+ latEncs = new int[count];
+ lonEncs = new int[count];
+ docIDs = new int[count];
+ ords = new long[count];
+ }
+
+ @Override
+ public void append(int latEnc, int lonEnc, long ord, int docID) {
+ latEncs[nextWrite] = latEnc;
+ lonEncs[nextWrite] = lonEnc;
+ ords[nextWrite] = ord;
+ docIDs[nextWrite] = docID;
+ nextWrite++;
+ }
+
+ @Override
+ public LatLonReader getReader(long start) {
+ return new HeapLatLonReader(latEncs, lonEncs, ords, docIDs, (int) start, latEncs.length);
+ }
+
+ @Override
+ public void close() {
+ if (nextWrite != latEncs.length) {
+ throw new IllegalStateException("only wrote " + nextWrite + " values, but expected " + latEncs.length);
+ }
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ @Override
+ public String toString() {
+ return "HeapLatLonWriter(count=" + latEncs.length + ")";
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonReader.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonReader.java
new file mode 100644
index 00000000000..aadfc7fe7c3
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonReader.java
@@ -0,0 +1,31 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/** Abstracts away whether OfflineSorter or simple arrays in heap are used. */
+interface LatLonReader extends Closeable {
+ boolean next() throws IOException;
+ int latEnc();
+ int lonEnc();
+ long ord();
+ int docID();
+}
+
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonWriter.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonWriter.java
new file mode 100644
index 00000000000..161fe9caec7
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/LatLonWriter.java
@@ -0,0 +1,29 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/** Abstracts away whether OfflineSorter or simple arrays in heap are used. */
+interface LatLonWriter extends Closeable {
+ void append(int latEnc, int lonEnc, long ord, int docID) throws IOException;
+ LatLonReader getReader(long start) throws IOException;
+ void destroy() throws IOException;
+}
+
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonReader.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonReader.java
new file mode 100644
index 00000000000..c898d3876f5
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonReader.java
@@ -0,0 +1,89 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.lucene.store.InputStreamDataInput;
+
+final class OfflineLatLonReader implements LatLonReader {
+ final InputStreamDataInput in;
+ long countLeft;
+ private int latEnc;
+ private int lonEnc;
+ private long ord;
+ private int docID;
+
+ OfflineLatLonReader(Path tempFile, long start, long count) throws IOException {
+ InputStream fis = Files.newInputStream(tempFile);
+ long seekFP = start * BKDTreeWriter.BYTES_PER_DOC;
+ long skipped = 0;
+ while (skipped < seekFP) {
+ long inc = fis.skip(seekFP - skipped);
+ skipped += inc;
+ if (inc == 0) {
+ throw new RuntimeException("skip returned 0");
+ }
+ }
+ in = new InputStreamDataInput(new BufferedInputStream(fis));
+ this.countLeft = count;
+ }
+
+ @Override
+ public boolean next() throws IOException {
+ if (countLeft == 0) {
+ return false;
+ }
+ countLeft--;
+ latEnc = in.readInt();
+ lonEnc = in.readInt();
+ ord = in.readLong();
+ docID = in.readInt();
+ return true;
+ }
+
+ @Override
+ public int latEnc() {
+ return latEnc;
+ }
+
+ @Override
+ public int lonEnc() {
+ return lonEnc;
+ }
+
+ @Override
+ public long ord() {
+ return ord;
+ }
+
+ @Override
+ public int docID() {
+ return docID;
+ }
+
+ @Override
+ public void close() throws IOException {
+ in.close();
+ }
+}
+
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonWriter.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonWriter.java
new file mode 100644
index 00000000000..ec22883371d
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/OfflineLatLonWriter.java
@@ -0,0 +1,76 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.lucene.store.ByteArrayDataOutput;
+import org.apache.lucene.store.OutputStreamDataOutput;
+import org.apache.lucene.util.IOUtils;
+
+final class OfflineLatLonWriter implements LatLonWriter {
+
+ final Path tempFile;
+ final byte[] scratchBytes = new byte[BKDTreeWriter.BYTES_PER_DOC];
+ final ByteArrayDataOutput scratchBytesOutput = new ByteArrayDataOutput(scratchBytes);
+ final OutputStreamDataOutput out;
+ final long count;
+ private long countWritten;
+
+ public OfflineLatLonWriter(Path tempDir, long count) throws IOException {
+ tempFile = Files.createTempFile(tempDir, "size" + count + ".", "");
+ out = new OutputStreamDataOutput(new BufferedOutputStream(Files.newOutputStream(tempFile)));
+ this.count = count;
+ }
+
+ @Override
+ public void append(int latEnc, int lonEnc, long ord, int docID) throws IOException {
+ out.writeInt(latEnc);
+ out.writeInt(lonEnc);
+ out.writeLong(ord);
+ out.writeInt(docID);
+ countWritten++;
+ }
+
+ @Override
+ public LatLonReader getReader(long start) throws IOException {
+ return new OfflineLatLonReader(tempFile, start, count-start);
+ }
+
+ @Override
+ public void close() throws IOException {
+ out.close();
+ if (count != countWritten) {
+ throw new IllegalStateException("wrote " + countWritten + " values, but expected " + count);
+ }
+ }
+
+ @Override
+ public void destroy() throws IOException {
+ IOUtils.rm(tempFile);
+ }
+
+ @Override
+ public String toString() {
+ return "OfflineLatLonWriter(count=" + count + " tempFile=" + tempFile + ")";
+ }
+}
+
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/package.html b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/package.html
new file mode 100644
index 00000000000..90bf356fb9b
--- /dev/null
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/package.html
@@ -0,0 +1,28 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+
+<!-- not a package-info.java, because we already defined this package in core/ -->
+
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+</head>
+<body>
+This package contains a BKD spatial tree implementation for indexing lat/lon points and fast shape searching.
+</body>
+</html>
diff --git a/lucene/sandbox/src/resources/META-INF/services/org.apache.lucene.codecs.DocValuesFormat b/lucene/sandbox/src/resources/META-INF/services/org.apache.lucene.codecs.DocValuesFormat
new file mode 100644
index 00000000000..49d2b2eb3a0
--- /dev/null
+++ b/lucene/sandbox/src/resources/META-INF/services/org.apache.lucene.codecs.DocValuesFormat
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+
+org.apache.lucene.bkdtree.BKDTreeDocValuesFormat
+
diff --git a/lucene/sandbox/src/test/org/apache/lucene/bkdtree/TestBKDTree.java b/lucene/sandbox/src/test/org/apache/lucene/bkdtree/TestBKDTree.java
new file mode 100644
index 00000000000..71d0aaa08ed
--- /dev/null
+++ b/lucene/sandbox/src/test/org/apache/lucene/bkdtree/TestBKDTree.java
@@ -0,0 +1,581 @@
+package org.apache.lucene.bkdtree;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+
+import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.DocValuesFormat;
+import org.apache.lucene.codecs.lucene50.Lucene50Codec;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.NumericDocValuesField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.MultiDocValues;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.lucene.index.RandomIndexWriter;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.SimpleCollector;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.LuceneTestCase.Nightly;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+import org.junit.BeforeClass;
+
+// TODO: can test framework assert we don't leak temp files?
+
+public class TestBKDTree extends LuceneTestCase {
+
+ private static boolean smallBBox;
+
+ @BeforeClass
+ public static void beforeClass() {
+ smallBBox = random().nextBoolean();
+ }
+
+ public void testAllLatEqual() throws Exception {
+ int numPoints = atLeast(10000);
+ double lat = randomLat();
+ double[] lats = new double[numPoints];
+ double[] lons = new double[numPoints];
+
+ boolean haveRealDoc = false;
+
+ for(int docID=0;docID<numPoints;docID++) {
+ int x = random().nextInt(20);
+ if (x == 17) {
+ // Some docs don't have a point:
+ lats[docID] = Double.NaN;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " is missing");
+ }
+ continue;
+ }
+
+ if (docID > 0 && x == 14 && haveRealDoc) {
+ int oldDocID;
+ while (true) {
+ oldDocID = random().nextInt(docID);
+ if (Double.isNaN(lats[oldDocID]) == false) {
+ break;
+ }
+ }
+
+ // Fully identical point:
+ lons[docID] = lons[oldDocID];
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lat + " lon=" + lons[docID] + " (same lat/lon as doc=" + oldDocID + ")");
+ }
+ } else {
+ lons[docID] = randomLon();
+ haveRealDoc = true;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lat + " lon=" + lons[docID]);
+ }
+ }
+ lats[docID] = lat;
+ }
+
+ verify(lats, lons);
+ }
+
+ public void testAllLonEqual() throws Exception {
+ int numPoints = atLeast(10000);
+ double theLon = randomLon();
+ double[] lats = new double[numPoints];
+ double[] lons = new double[numPoints];
+
+ boolean haveRealDoc = false;
+
+ //System.out.println("theLon=" + theLon);
+
+ for(int docID=0;docID<numPoints;docID++) {
+ int x = random().nextInt(20);
+ if (x == 17) {
+ // Some docs don't have a point:
+ lats[docID] = Double.NaN;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " is missing");
+ }
+ continue;
+ }
+
+ if (docID > 0 && x == 14 && haveRealDoc) {
+ int oldDocID;
+ while (true) {
+ oldDocID = random().nextInt(docID);
+ if (Double.isNaN(lats[oldDocID]) == false) {
+ break;
+ }
+ }
+
+ // Fully identical point:
+ lats[docID] = lats[oldDocID];
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + theLon + " (same lat/lon as doc=" + oldDocID + ")");
+ }
+ } else {
+ lats[docID] = randomLat();
+ haveRealDoc = true;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + theLon);
+ }
+ }
+ lons[docID] = theLon;
+ }
+
+ verify(lats, lons);
+ }
+
+ public void testMultiValued() throws Exception {
+ int numPoints = atLeast(10000);
+ // Every doc has 2 points:
+ double[] lats = new double[2*numPoints];
+ double[] lons = new double[2*numPoints];
+ Directory dir = newDirectory();
+ IndexWriterConfig iwc = newIndexWriterConfig();
+ // We rely on docID order:
+ iwc.setMergePolicy(newLogMergePolicy());
+ int maxPointsInLeaf = TestUtil.nextInt(random(), 16, 2048);
+ int maxPointsSortInHeap = TestUtil.nextInt(random(), 1024, 1024*1024);
+ Codec codec = TestUtil.alwaysDocValuesFormat(new BKDTreeDocValuesFormat(maxPointsInLeaf, maxPointsSortInHeap));
+ iwc.setCodec(codec);
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
+
+ for (int docID=0;docID<numPoints;docID++) {
+ Document doc = new Document();
+ lats[2*docID] = randomLat();
+ lons[2*docID] = randomLon();
+ doc.add(new BKDPointField("point", lats[2*docID], lons[2*docID]));
+ lats[2*docID+1] = randomLat();
+ lons[2*docID+1] = randomLon();
+ doc.add(new BKDPointField("point", lats[2*docID+1], lons[2*docID+1]));
+ w.addDocument(doc);
+ }
+
+ if (random().nextBoolean()) {
+ w.forceMerge(1);
+ }
+ IndexReader r = w.getReader();
+ w.close();
+ // We can't wrap with "exotic" readers because the BKD query must see the BKDDVFormat:
+ IndexSearcher s = newSearcher(r, false);
+
+ int iters = atLeast(100);
+ for (int iter=0;iter<iters;iter++) {
+ double lat0 = randomLat();
+ double lat1 = randomLat();
+ double lon0 = randomLon();
+ double lon1 = randomLon();
+
+ if (lat1 < lat0) {
+ double x = lat0;
+ lat0 = lat1;
+ lat1 = x;
+ }
+
+ if (lon1 < lon0) {
+ double x = lon0;
+ lon0 = lon1;
+ lon1 = x;
+ }
+
+ if (VERBOSE) {
+ System.out.println("\nTEST: iter=" + iter + " lat=" + lat0 + " TO " + lat1 + " lon=" + lon0 + " TO " + lon1);
+ }
+
+ Query query = new BKDPointInBBoxQuery("point", lat0, lat1, lon0, lon1);
+
+ final FixedBitSet hits = new FixedBitSet(r.maxDoc());
+ s.search(query, new SimpleCollector() {
+
+ private int docBase;
+
+ @Override
+ public boolean needsScores() {
+ return false;
+ }
+
+ @Override
+ protected void doSetNextReader(LeafReaderContext context) throws IOException {
+ docBase = context.docBase;
+ }
+
+ @Override
+ public void collect(int doc) {
+ hits.set(docBase+doc);
+ }
+ });
+
+ for(int docID=0;docID<lats.length/2;docID++) {
+ double latDoc1 = lats[2*docID];
+ double lonDoc1 = lons[2*docID];
+ double latDoc2 = lats[2*docID+1];
+ double lonDoc2 = lons[2*docID+1];
+ boolean expected = rectContainsPointEnc(lat0, lat1, lon0, lon1, latDoc1, lonDoc1) ||
+ rectContainsPointEnc(lat0, lat1, lon0, lon1, latDoc2, lonDoc2);
+
+ if (hits.get(docID) != expected) {
+ fail("docID=" + docID + " latDoc1=" + latDoc1 + " lonDoc1=" + lonDoc1 + " latDoc2=" + latDoc2 + " lonDoc2=" + lonDoc2 + " expected " + expected + " but got: " + hits.get(docID));
+ }
+ }
+ }
+ r.close();
+ dir.close();
+ }
+
+ // A particularly tricky adversary:
+ public void testSamePointManyTimes() throws Exception {
+ int numPoints = atLeast(1000);
+
+ // Every doc has 2 points:
+ double theLat = randomLat();
+ double theLon = randomLon();
+
+ double[] lats = new double[numPoints];
+ Arrays.fill(lats, theLat);
+
+ double[] lons = new double[numPoints];
+ Arrays.fill(lons, theLon);
+
+ verify(lats, lons);
+ }
+
+ public void testRandomTiny() throws Exception {
+ // Make sure single-leaf-node case is OK:
+ doTestRandom(10);
+ }
+
+ public void testRandomMedium() throws Exception {
+ doTestRandom(10000);
+ }
+
+ @Nightly
+ public void testRandomBig() throws Exception {
+ doTestRandom(1000000);
+ }
+
+ private void doTestRandom(int count) throws Exception {
+
+ int numPoints = atLeast(count);
+
+ if (VERBOSE) {
+ System.out.println("TEST: numPoints=" + numPoints);
+ }
+
+ double[] lats = new double[numPoints];
+ double[] lons = new double[numPoints];
+
+ boolean haveRealDoc = false;
+
+ for (int docID=0;docID<numPoints;docID++) {
+ int x = random().nextInt(20);
+ if (x == 17) {
+ // Some docs don't have a point:
+ lats[docID] = Double.NaN;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " is missing");
+ }
+ continue;
+ }
+
+ if (docID > 0 && x < 3 && haveRealDoc) {
+ int oldDocID;
+ while (true) {
+ oldDocID = random().nextInt(docID);
+ if (Double.isNaN(lats[oldDocID]) == false) {
+ break;
+ }
+ }
+
+ if (x == 0) {
+ // Identical lat to old point
+ lats[docID] = lats[oldDocID];
+ lons[docID] = randomLon();
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + lons[docID] + " (same lat as doc=" + oldDocID + ")");
+ }
+ } else if (x == 1) {
+ // Identical lon to old point
+ lats[docID] = randomLat();
+ lons[docID] = lons[oldDocID];
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + lons[docID] + " (same lon as doc=" + oldDocID + ")");
+ }
+ } else {
+ assert x == 2;
+ // Fully identical point:
+ lats[docID] = lats[oldDocID];
+ lons[docID] = lons[oldDocID];
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + lons[docID] + " (same lat/lon as doc=" + oldDocID + ")");
+ }
+ }
+ } else {
+ lats[docID] = randomLat();
+ lons[docID] = randomLon();
+ haveRealDoc = true;
+ if (VERBOSE) {
+ System.out.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + lons[docID]);
+ }
+ }
+ }
+
+ verify(lats, lons);
+ }
+
+ private static void verify(double[] lats, double[] lons) throws Exception {
+ int maxPointsInLeaf = TestUtil.nextInt(random(), 16, 2048);
+ int maxPointsSortInHeap = TestUtil.nextInt(random(), maxPointsInLeaf, 1024*1024);
+ IndexWriterConfig iwc = newIndexWriterConfig();
+ // Else we can get O(N^2) merging:
+ int mbd = iwc.getMaxBufferedDocs();
+ if (mbd != -1 && mbd < lats.length/100) {
+ iwc.setMaxBufferedDocs(lats.length/100);
+ }
+ final DocValuesFormat dvFormat = new BKDTreeDocValuesFormat(maxPointsInLeaf, maxPointsSortInHeap);
+ Codec codec = new Lucene50Codec() {
+ @Override
+ public DocValuesFormat getDocValuesFormatForField(String field) {
+ if (field.equals("point")) {
+ return dvFormat;
+ } else {
+ return super.getDocValuesFormatForField(field);
+ }
+ }
+ };
+ iwc.setCodec(codec);
+ Directory dir;
+ if (lats.length > 100000) {
+ dir = newFSDirectory(createTempDir("TestBKDTree"));
+ } else {
+ dir = newDirectory();
+ }
+ Set<Integer> deleted = new HashSet<>();
+ // RandomIndexWriter is too slow here:
+ IndexWriter w = new IndexWriter(dir, iwc);
+ for(int id=0;id<lats.length;id++) {
+ Document doc = new Document();
+ doc.add(newStringField("id", ""+id, Field.Store.NO));
+ doc.add(new NumericDocValuesField("id", id));
+ if (Double.isNaN(lats[id]) == false) {
+ doc.add(new BKDPointField("point", lats[id], lons[id]));
+ }
+ w.addDocument(doc);
+ if (id > 0 && random().nextInt(100) == 42) {
+ int idToDelete = random().nextInt(id);
+ w.deleteDocuments(new Term("id", ""+idToDelete));
+ deleted.add(idToDelete);
+ if (VERBOSE) {
+ System.out.println(" delete id=" + idToDelete);
+ }
+ }
+ }
+ if (random().nextBoolean()) {
+ w.forceMerge(1);
+ }
+ final IndexReader r = DirectoryReader.open(w, true);
+ w.close();
+
+ // We can't wrap with "exotic" readers because the BKD query must see the BKDDVFormat:
+ IndexSearcher s = newSearcher(r, false);
+
+ int numThreads = TestUtil.nextInt(random(), 2, 5);
+
+ List<Thread> threads = new ArrayList<>();
+ final int iters = atLeast(100);
+
+ final CountDownLatch startingGun = new CountDownLatch(1);
+
+ for(int i=0;i<numThreads;i++) {
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ _run();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void _run() throws Exception {
+ startingGun.await();
+
+ NumericDocValues docIDToID = MultiDocValues.getNumericValues(r, "id");
+
+ for (int iter=0;iter<iters;iter++) {
+ double lat0 = randomLat();
+ double lat1 = randomLat();
+ double lon0 = randomLon();
+ double lon1 = randomLon();
+
+ if (lat1 < lat0) {
+ double x = lat0;
+ lat0 = lat1;
+ lat1 = x;
+ }
+
+ if (lon1 < lon0) {
+ double x = lon0;
+ lon0 = lon1;
+ lon1 = x;
+ }
+
+ if (VERBOSE) {
+ System.out.println("\nTEST: iter=" + iter + " lat=" + lat0 + " TO " + lat1 + " lon=" + lon0 + " TO " + lon1);
+ }
+
+ Query query;
+ if (random().nextBoolean()) {
+ query = new BKDPointInBBoxQuery("point", lat0, lat1, lon0, lon1);
+ } else {
+ double[] lats = new double[5];
+ double[] lons = new double[5];
+ lats[0] = lat0;
+ lons[0] = lon0;
+ lats[1] = lat1;
+ lons[1] = lon0;
+ lats[2] = lat1;
+ lons[2] = lon1;
+ lats[3] = lat0;
+ lons[3] = lon1;
+ lats[4] = lat0;
+ lons[4] = lon0;
+ query = new BKDPointInPolygonQuery("point", lats, lons);
+ }
+
+ if (VERBOSE) {
+ System.out.println(" using query: " + query);
+ }
+
+ final FixedBitSet hits = new FixedBitSet(r.maxDoc());
+ s.search(query, new SimpleCollector() {
+
+ private int docBase;
+
+ @Override
+ public boolean needsScores() {
+ return false;
+ }
+
+ @Override
+ protected void doSetNextReader(LeafReaderContext context) throws IOException {
+ docBase = context.docBase;
+ }
+
+ @Override
+ public void collect(int doc) {
+ hits.set(docBase+doc);
+ }
+ });
+
+ if (VERBOSE) {
+ System.out.println(" hitCount: " + hits.cardinality());
+ }
+
+ for(int docID=0;docID<r.maxDoc();docID++) {
+ int id = (int) docIDToID.get(docID);
+ boolean expected = deleted.contains(id) == false && rectContainsPointEnc(lat0, lat1, lon0, lon1, lats[id], lons[id]);
+ if (hits.get(docID) != expected) {
+ fail(Thread.currentThread().getName() + ": iter=" + iter + " id=" + id + " docID=" + docID + " lat=" + lats[id] + " lon=" + lons[id] + " (bbox: lat=" + lat0 + " TO " + lat1 + " lon=" + lon0 + " TO " + lon1 + ") expected " + expected + " but got: " + hits.get(docID) + " deleted?=" + deleted.contains(id) + " query=" + query);
+ }
+ }
+ }
+ }
+ };
+ thread.setName("T" + i);
+ thread.start();
+ threads.add(thread);
+ }
+ startingGun.countDown();
+ for(Thread thread : threads) {
+ thread.join();
+ }
+ IOUtils.close(r, dir);
+ }
+
+ private static boolean rectContainsPointEnc(double rectLatMin, double rectLatMax,
+ double rectLonMin, double rectLonMax,
+ double pointLat, double pointLon) {
+ if (Double.isNaN(pointLat)) {
+ return false;
+ }
+ int rectLatMinEnc = BKDTreeWriter.encodeLat(rectLatMin);
+ int rectLatMaxEnc = BKDTreeWriter.encodeLat(rectLatMax);
+ int rectLonMinEnc = BKDTreeWriter.encodeLon(rectLonMin);
+ int rectLonMaxEnc = BKDTreeWriter.encodeLon(rectLonMax);
+ int pointLatEnc = BKDTreeWriter.encodeLat(pointLat);
+ int pointLonEnc = BKDTreeWriter.encodeLon(pointLon);
+
+ return pointLatEnc >= rectLatMinEnc &&
+ pointLatEnc < rectLatMaxEnc &&
+ pointLonEnc >= rectLonMinEnc &&
+ pointLonEnc < rectLonMaxEnc;
+ }
+
+ private static double randomLat() {
+ if (smallBBox) {
+ return 2.0 * (random().nextDouble()-0.5);
+ } else {
+ return -90 + 180.0 * random().nextDouble();
+ }
+ }
+
+ private static double randomLon() {
+ if (smallBBox) {
+ return 2.0 * (random().nextDouble()-0.5);
+ } else {
+ return -180 + 360.0 * random().nextDouble();
+ }
+ }
+
+ public void testEncodeDecode() throws Exception {
+ int iters = atLeast(10000);
+ for(int iter=0;iter<iters;iter++) {
+ double lat = randomLat();
+ double latQuantized = BKDTreeWriter.decodeLat(BKDTreeWriter.encodeLat(lat));
+ assertEquals(lat, latQuantized, BKDTreeWriter.TOLERANCE);
+
+ double lon = randomLon();
+ double lonQuantized = BKDTreeWriter.decodeLon(BKDTreeWriter.encodeLon(lon));
+ assertEquals(lon, lonQuantized, BKDTreeWriter.TOLERANCE);
+ }
+ }
+
+ public void testEncodeDecodeMax() throws Exception {
+ int x = BKDTreeWriter.encodeLat(Math.nextAfter(90.0, Double.POSITIVE_INFINITY));
+ assertTrue(x < Integer.MAX_VALUE);
+
+ int y = BKDTreeWriter.encodeLon(Math.nextAfter(180.0, Double.POSITIVE_INFINITY));
+ assertTrue(y < Integer.MAX_VALUE);
+ }
+}