Skip to content

Apache Lucene open-source search software

LUCENE-7046: Remove PointInRectQuery, instead using 2-D PointRangeQuery for LatLonPoint

Robert Muir77e62276f99d
diff --git a/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java b/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java
index 8dd39252e0a..6a3cb856704 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
/**
@@ -129,7 +130,7 @@ public final class BinaryPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null or {@code value} is null
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, byte[] value) {
+ public static Query newExactQuery(String field, byte[] value) {
if (value == null) {
throw new IllegalArgumentException("value cannot be null");
}
@@ -156,7 +157,7 @@ public final class BinaryPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, byte[] lowerValue, boolean lowerInclusive, byte[] upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, byte[] lowerValue, boolean lowerInclusive, byte[] upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field, new byte[][] {lowerValue}, new boolean[] {lowerInclusive}, new byte[][] {upperValue}, new boolean[] {upperInclusive});
}
@@ -177,11 +178,11 @@ public final class BinaryPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, byte[][] lowerValue, boolean[] lowerInclusive, byte[][] upperValue, boolean[] upperInclusive) {
+ public static Query newMultiRangeQuery(String field, byte[][] lowerValue, boolean[] lowerInclusive, byte[][] upperValue, boolean[] upperInclusive) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, lowerValue, lowerInclusive, upperValue, upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
assert value != null;
StringBuilder sb = new StringBuilder();
sb.append("binary(");
diff --git a/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java b/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java
index ee0d6f23b1e..2db2d856009 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
@@ -154,7 +155,7 @@ public final class DoublePoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, double value) {
+ public static Query newExactQuery(String field, double value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -178,7 +179,7 @@ public final class DoublePoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, Double lowerValue, boolean lowerInclusive, Double upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, Double lowerValue, boolean lowerInclusive, Double upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field,
new Double[] { lowerValue },
new boolean[] { lowerInclusive },
@@ -203,11 +204,11 @@ public final class DoublePoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, Double[] lowerValue, boolean lowerInclusive[], Double[] upperValue, boolean upperInclusive[]) {
+ public static Query newMultiRangeQuery(String field, Double[] lowerValue, boolean lowerInclusive[], Double[] upperValue, boolean upperInclusive[]) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, DoublePoint.encode(lowerValue), lowerInclusive, DoublePoint.encode(upperValue), upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return DoublePoint.decodeDimension(value, 0).toString();
}
};
diff --git a/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java b/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java
index 34216b46c80..027dc66f3cf 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
@@ -154,7 +155,7 @@ public final class FloatPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, float value) {
+ public static Query newExactQuery(String field, float value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -178,7 +179,7 @@ public final class FloatPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, Float lowerValue, boolean lowerInclusive, Float upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, Float lowerValue, boolean lowerInclusive, Float upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field,
new Float[] { lowerValue },
new boolean[] { lowerInclusive },
@@ -203,11 +204,11 @@ public final class FloatPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, Float[] lowerValue, boolean lowerInclusive[], Float[] upperValue, boolean upperInclusive[]) {
+ public static Query newMultiRangeQuery(String field, Float[] lowerValue, boolean lowerInclusive[], Float[] upperValue, boolean upperInclusive[]) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, FloatPoint.encode(lowerValue), lowerInclusive, FloatPoint.encode(upperValue), upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return FloatPoint.decodeDimension(value, 0).toString();
}
};
diff --git a/lucene/core/src/java/org/apache/lucene/document/IntPoint.java b/lucene/core/src/java/org/apache/lucene/document/IntPoint.java
index 177ae9955d6..2d411e94093 100644
--- a/lucene/core/src/java/org/apache/lucene/document/IntPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/IntPoint.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
@@ -154,7 +155,7 @@ public final class IntPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, int value) {
+ public static Query newExactQuery(String field, int value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -178,7 +179,7 @@ public final class IntPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, Integer lowerValue, boolean lowerInclusive, Integer upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, Integer lowerValue, boolean lowerInclusive, Integer upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field,
new Integer[] { lowerValue },
new boolean[] { lowerInclusive },
@@ -203,11 +204,11 @@ public final class IntPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, Integer[] lowerValue, boolean lowerInclusive[], Integer[] upperValue, boolean upperInclusive[]) {
+ public static Query newMultiRangeQuery(String field, Integer[] lowerValue, boolean lowerInclusive[], Integer[] upperValue, boolean upperInclusive[]) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, IntPoint.encode(lowerValue), lowerInclusive, IntPoint.encode(upperValue), upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return IntPoint.decodeDimension(value, 0).toString();
}
};
diff --git a/lucene/core/src/java/org/apache/lucene/document/LongPoint.java b/lucene/core/src/java/org/apache/lucene/document/LongPoint.java
index d3f8c171d66..69b511d1e48 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongPoint.java
@@ -17,6 +17,7 @@
package org.apache.lucene.document;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
@@ -154,7 +155,7 @@ public final class LongPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, long value) {
+ public static Query newExactQuery(String field, long value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -178,7 +179,7 @@ public final class LongPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, Long lowerValue, boolean lowerInclusive, Long upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, Long lowerValue, boolean lowerInclusive, Long upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field,
new Long[] { lowerValue },
new boolean[] { lowerInclusive },
@@ -203,11 +204,11 @@ public final class LongPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, Long[] lowerValue, boolean lowerInclusive[], Long[] upperValue, boolean upperInclusive[]) {
+ public static Query newMultiRangeQuery(String field, Long[] lowerValue, boolean lowerInclusive[], Long[] upperValue, boolean upperInclusive[]) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, LongPoint.encode(lowerValue), lowerInclusive, LongPoint.encode(upperValue), upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return LongPoint.decodeDimension(value, 0).toString();
}
};
diff --git a/lucene/core/src/java/org/apache/lucene/search/PointRangeQuery.java b/lucene/core/src/java/org/apache/lucene/search/PointRangeQuery.java
index 9db80fc5598..c68715dfdfe 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PointRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PointRangeQuery.java
@@ -328,7 +328,7 @@ public abstract class PointRangeQuery extends Query {
if (lowerPoint[i] == null) {
sb.append('*');
} else {
- sb.append(toString(lowerPoint[i]));
+ sb.append(toString(i, lowerPoint[i]));
}
sb.append(" TO ");
@@ -336,7 +336,7 @@ public abstract class PointRangeQuery extends Query {
if (upperPoint[i] == null) {
sb.append('*');
} else {
- sb.append(toString(upperPoint[i]));
+ sb.append(toString(i, upperPoint[i]));
}
if (upperInclusive[i]) {
@@ -353,8 +353,9 @@ public abstract class PointRangeQuery extends Query {
* Returns a string of a single value in a human-readable format for debugging.
* This is used by {@link #toString()}.
*
+ * @param dimension dimension of the particular value
* @param value single value, never null
* @return human readable value for debugging
*/
- protected abstract String toString(byte[] value);
+ protected abstract String toString(int dimension, byte[] value);
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/document/BigIntegerPoint.java b/lucene/sandbox/src/java/org/apache/lucene/document/BigIntegerPoint.java
index f88c85a9c19..5c36a85f016 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/document/BigIntegerPoint.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/document/BigIntegerPoint.java
@@ -19,6 +19,7 @@ package org.apache.lucene.document;
import java.math.BigInteger;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
@@ -154,7 +155,7 @@ public class BigIntegerPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, BigInteger value) {
+ public static Query newExactQuery(String field, BigInteger value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -178,7 +179,7 @@ public class BigIntegerPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, BigInteger lowerValue, boolean lowerInclusive, BigInteger upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, BigInteger lowerValue, boolean lowerInclusive, BigInteger upperValue, boolean upperInclusive) {
return newMultiRangeQuery(field,
new BigInteger[] { lowerValue },
new boolean[] { lowerInclusive },
@@ -203,11 +204,11 @@ public class BigIntegerPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newMultiRangeQuery(String field, BigInteger[] lowerValue, boolean lowerInclusive[], BigInteger[] upperValue, boolean upperInclusive[]) {
+ public static Query newMultiRangeQuery(String field, BigInteger[] lowerValue, boolean lowerInclusive[], BigInteger[] upperValue, boolean upperInclusive[]) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return new PointRangeQuery(field, BigIntegerPoint.encode(lowerValue), lowerInclusive, BigIntegerPoint.encode(upperValue), upperInclusive) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return BigIntegerPoint.decodeDimension(value, 0).toString();
}
};
diff --git a/lucene/sandbox/src/java/org/apache/lucene/document/InetAddressPoint.java b/lucene/sandbox/src/java/org/apache/lucene/document/InetAddressPoint.java
index 51ada8f3ab3..a6273cf8f3f 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/document/InetAddressPoint.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/document/InetAddressPoint.java
@@ -20,6 +20,7 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
/**
@@ -141,7 +142,7 @@ public class InetAddressPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents with this exact value
*/
- public static PointRangeQuery newExactQuery(String field, InetAddress value) {
+ public static Query newExactQuery(String field, InetAddress value) {
return newRangeQuery(field, value, true, value, true);
}
@@ -154,7 +155,7 @@ public class InetAddressPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null, or prefixLength is invalid.
* @return a query matching documents with addresses contained within this network
*/
- public static PointRangeQuery newPrefixQuery(String field, InetAddress value, int prefixLength) {
+ public static Query newPrefixQuery(String field, InetAddress value, int prefixLength) {
if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) {
throw new IllegalArgumentException("illegal prefixLength '" + prefixLength + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges");
}
@@ -189,7 +190,7 @@ public class InetAddressPoint extends Field {
* @throws IllegalArgumentException if {@code field} is null.
* @return a query matching documents within this range.
*/
- public static PointRangeQuery newRangeQuery(String field, InetAddress lowerValue, boolean lowerInclusive, InetAddress upperValue, boolean upperInclusive) {
+ public static Query newRangeQuery(String field, InetAddress lowerValue, boolean lowerInclusive, InetAddress upperValue, boolean upperInclusive) {
byte[][] lowerBytes = new byte[1][];
if (lowerValue != null) {
lowerBytes[0] = InetAddressPoint.encode(lowerValue);
@@ -200,7 +201,7 @@ public class InetAddressPoint extends Field {
}
return new PointRangeQuery(field, lowerBytes, new boolean[] { lowerInclusive }, upperBytes, new boolean[] { upperInclusive }) {
@Override
- protected String toString(byte[] value) {
+ protected String toString(int dimension, byte[] value) {
return decode(value).getHostAddress(); // for ranges, the range itself is already bracketed
}
};
diff --git a/lucene/sandbox/src/java/org/apache/lucene/document/LatLonPoint.java b/lucene/sandbox/src/java/org/apache/lucene/document/LatLonPoint.java
index 539987ca5a0..0ea9efb41f1 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/document/LatLonPoint.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/document/LatLonPoint.java
@@ -18,9 +18,33 @@ package org.apache.lucene.document;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
+
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.ConstantScoreQuery;
+import org.apache.lucene.search.PointInPolygonQuery;
+import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.spatial.util.GeoUtils;
-/** Add this to a document to index lat/lon point dimensionally */
+/**
+ * A field indexing geographic coordinates dimensionally such that finding
+ * all documents within a range at search time is
+ * efficient. Multiple values for the same field in one document
+ * is allowed.
+ * <p>
+ * This field defines static factory methods for creating common queries:
+ * <ul>
+ * <li>{@link #newBoxQuery newBoxQuery()} for matching points within a bounding box.
+ * <li>{@link #newPolygonQuery newPolygonQuery()} for matching points within an arbitrary polygon.
+ * </ul>
+ * <p>
+ * <b>WARNING</b>: Values are indexed with some loss of precision, incurring up to 1E-7 error from the
+ * original {@code double} values.
+ */
+// TODO ^^^ that is very sandy and hurts the API, usage, and tests tremendously, because what the user passes
+// to the field is not actually what gets indexed. Float would be 1E-5 error vs 1E-7, but it might be
+// a better tradeoff? then it would be completely transparent to the user and lucene would be "lossless".
public class LatLonPoint extends Field {
public static final FieldType TYPE = new FieldType();
static {
@@ -49,12 +73,28 @@ public class LatLonPoint extends Field {
fieldsData = new BytesRef(bytes);
}
- public static final double TOLERANCE = 1E-7;
-
private static final int BITS = 32;
-
private static final double LON_SCALE = (0x1L<<BITS)/360.0D;
private static final double LAT_SCALE = (0x1L<<BITS)/180.0D;
+
+ @Override
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+ result.append(type.toString());
+ result.append('<');
+ result.append(name);
+ result.append(':');
+
+ BytesRef bytes = (BytesRef) fieldsData;
+ result.append(decodeLat(BytesRef.deepCopyOf(bytes).bytes, 0));
+ result.append(',');
+ result.append(decodeLon(BytesRef.deepCopyOf(bytes).bytes, Integer.BYTES));
+
+ result.append('>');
+ return result.toString();
+ }
+
+ // public helper methods (e.g. for queries)
/** Quantizes double (64 bit) latitude into 32 bits */
public static int encodeLat(double lat) {
@@ -78,9 +118,99 @@ public class LatLonPoint extends Field {
public static double decodeLat(int x) {
return x / LAT_SCALE;
}
+
+ /** Turns quantized value from byte array back into a double. */
+ public static double decodeLat(byte[] src, int offset) {
+ return decodeLat(NumericUtils.bytesToInt(src, offset));
+ }
/** Turns quantized value from {@link #encodeLon} back into a double. */
public static double decodeLon(int x) {
return x / LON_SCALE;
}
+
+ /** Turns quantized value from byte array back into a double. */
+ public static double decodeLon(byte[] src, int offset) {
+ return decodeLon(NumericUtils.bytesToInt(src, offset));
+ }
+
+ /** sugar encodes a single point as a 2D byte array */
+ private static byte[][] encode(double lat, double lon) {
+ byte[][] bytes = new byte[2][];
+ bytes[0] = new byte[4];
+ NumericUtils.intToBytes(encodeLat(lat), bytes[0], 0);
+ bytes[1] = new byte[4];
+ NumericUtils.intToBytes(encodeLon(lon), bytes[1], 0);
+ return bytes;
+ }
+
+ // static methods for generating queries
+
+ /**
+ * Create a query for matching a bounding box.
+ * <p>
+ * The box may cross over the dateline.
+ */
+ public static Query newBoxQuery(String field, double minLat, double maxLat, double minLon, double maxLon) {
+ if (GeoUtils.isValidLat(minLat) == false) {
+ throw new IllegalArgumentException("minLat=" + minLat + " is not a valid latitude");
+ }
+ if (GeoUtils.isValidLat(maxLat) == false) {
+ throw new IllegalArgumentException("maxLat=" + maxLat + " is not a valid latitude");
+ }
+ if (GeoUtils.isValidLon(minLon) == false) {
+ throw new IllegalArgumentException("minLon=" + minLon + " is not a valid longitude");
+ }
+ if (GeoUtils.isValidLon(maxLon) == false) {
+ throw new IllegalArgumentException("maxLon=" + maxLon + " is not a valid longitude");
+ }
+
+ byte[][] lower = encode(minLat, minLon);
+ byte[][] upper = encode(maxLat, maxLon);
+ // Crosses date line: we just rewrite into OR of two bboxes, with longitude as an open range:
+ if (maxLon < minLon) {
+ // Disable coord here because a multi-valued doc could match both rects and get unfairly boosted:
+ BooleanQuery.Builder q = new BooleanQuery.Builder();
+ q.setDisableCoord(true);
+
+ // E.g.: maxLon = -179, minLon = 179
+ byte[][] leftOpen = new byte[2][];
+ leftOpen[0] = lower[0];
+ // leave longitude open (null)
+ Query left = newBoxInternal(field, leftOpen, upper);
+ q.add(new BooleanClause(left, BooleanClause.Occur.SHOULD));
+ byte[][] rightOpen = new byte[2][];
+ rightOpen[0] = upper[0];
+ // leave longitude open (null)
+ Query right = newBoxInternal(field, lower, rightOpen);
+ q.add(new BooleanClause(right, BooleanClause.Occur.SHOULD));
+ return new ConstantScoreQuery(q.build());
+ } else {
+ return newBoxInternal(field, lower, upper);
+ }
+ }
+
+ private static Query newBoxInternal(String field, byte[][] min, byte[][] max) {
+ return new PointRangeQuery(field, min, new boolean[] { true, true }, max, new boolean[] { false, false }) {
+ @Override
+ protected String toString(int dimension, byte[] value) {
+ if (dimension == 0) {
+ return Double.toString(decodeLat(value, 0));
+ } else if (dimension == 1) {
+ return Double.toString(decodeLon(value, 0));
+ } else {
+ throw new AssertionError();
+ }
+ }
+ };
+ }
+
+ /**
+ * Create a query for matching a polygon.
+ * <p>
+ * The supplied {@code polyLats}/{@code polyLons} must be clockwise or counter-clockwise.
+ */
+ public static Query newPolygonQuery(String field, double[] polyLats, double[] polyLons) {
+ return new PointInPolygonQuery(field, polyLats, polyLons);
+ }
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/PointInPolygonQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/PointInPolygonQuery.java
index 6a5ae1e816c..dc3675e4ce4 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/PointInPolygonQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/PointInPolygonQuery.java
@@ -64,7 +64,7 @@ public class PointInPolygonQuery extends Query {
this.polyLats = polyLats;
this.polyLons = polyLons;
- // TODO: we could also compute the maximal innner bounding box, to make relations faster to compute?
+ // TODO: we could also compute the maximal inner bounding box, to make relations faster to compute?
double minLon = Double.POSITIVE_INFINITY;
double minLat = Double.POSITIVE_INFINITY;
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/PointInRectQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/PointInRectQuery.java
deleted file mode 100644
index 5292f22d807..00000000000
--- a/lucene/sandbox/src/java/org/apache/lucene/search/PointInRectQuery.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * 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.
- */
-package org.apache.lucene.search;
-
-import java.io.IOException;
-
-import org.apache.lucene.document.LatLonPoint;
-import org.apache.lucene.index.PointValues.IntersectVisitor;
-import org.apache.lucene.index.PointValues.Relation;
-import org.apache.lucene.index.PointValues;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.LeafReader;
-import org.apache.lucene.index.LeafReaderContext;
-import org.apache.lucene.util.DocIdSetBuilder;
-import org.apache.lucene.util.NumericUtils;
-import org.apache.lucene.spatial.util.GeoUtils;
-
-/** Finds all previously indexed points that fall within the specified boundings box.
- *
- * <p>The field must be indexed with using {@link org.apache.lucene.document.LatLonPoint} added per document.
- *
- * @lucene.experimental */
-
-public class PointInRectQuery 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 PointInRectQuery(String field, double minLat, double maxLat, double minLon, double maxLon) {
- this.field = field;
- if (GeoUtils.isValidLat(minLat) == false) {
- throw new IllegalArgumentException("minLat=" + minLat + " is not a valid latitude");
- }
- if (GeoUtils.isValidLat(maxLat) == false) {
- throw new IllegalArgumentException("maxLat=" + maxLat + " is not a valid latitude");
- }
- if (GeoUtils.isValidLon(minLon) == false) {
- throw new IllegalArgumentException("minLon=" + minLon + " is not a valid longitude");
- }
- if (GeoUtils.isValidLon(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 ConstantScoreWeight(this) {
- @Override
- public Scorer scorer(LeafReaderContext context) throws IOException {
- LeafReader reader = context.reader();
- PointValues values = reader.getPointValues();
- if (values == null) {
- // No docs in this segment had any points fields
- return null;
- }
-
- DocIdSetBuilder result = new DocIdSetBuilder(reader.maxDoc());
- int[] hitCount = new int[1];
- values.intersect(field,
- new IntersectVisitor() {
- @Override
- public void grow(int count) {
- result.grow(count);
- }
-
- @Override
- public void visit(int docID) {
- hitCount[0]++;
- result.add(docID);
- }
-
- @Override
- public void visit(int docID, byte[] packedValue) {
- assert packedValue.length == 8;
- double lat = LatLonPoint.decodeLat(NumericUtils.bytesToInt(packedValue, 0));
- double lon = LatLonPoint.decodeLon(NumericUtils.bytesToInt(packedValue, Integer.BYTES));
- if (lat >= minLat && lat <= maxLat && lon >= minLon && lon <= maxLon) {
- hitCount[0]++;
- result.add(docID);
- }
- }
-
- @Override
- public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
- double cellMinLat = LatLonPoint.decodeLat(NumericUtils.bytesToInt(minPackedValue, 0));
- double cellMinLon = LatLonPoint.decodeLon(NumericUtils.bytesToInt(minPackedValue, Integer.BYTES));
- double cellMaxLat = LatLonPoint.decodeLat(NumericUtils.bytesToInt(maxPackedValue, 0));
- double cellMaxLon = LatLonPoint.decodeLon(NumericUtils.bytesToInt(maxPackedValue, Integer.BYTES));
-
- if (minLat <= cellMinLat && maxLat >= cellMaxLat && minLon <= cellMinLon && maxLon >= cellMaxLon) {
- return Relation.CELL_INSIDE_QUERY;
- }
-
- if (cellMaxLat < minLat || cellMinLat > maxLat || cellMaxLon < minLon || cellMinLon > maxLon) {
- return Relation.CELL_OUTSIDE_QUERY;
- }
-
- return Relation.CELL_CROSSES_QUERY;
- }
- });
-
- // NOTE: hitCount[0] will be over-estimate in multi-valued case
- return new ConstantScoreScorer(this, score(), result.build(hitCount[0]).iterator());
- }
- };
- }
-
- @Override
- public Query rewrite(IndexReader reader) throws IOException {
- // Crosses date line: we just rewrite into OR of two bboxes:
- if (maxLon < minLon) {
-
- // Disable coord here because a multi-valued doc could match both rects and get unfairly boosted:
- BooleanQuery.Builder q = new BooleanQuery.Builder();
- q.setDisableCoord(true);
-
- // E.g.: maxLon = -179, minLon = 179
- PointInRectQuery left = new PointInRectQuery(field, minLat, maxLat, GeoUtils.MIN_LON_INCL, maxLon);
- q.add(new BooleanClause(left, BooleanClause.Occur.SHOULD));
- PointInRectQuery right = new PointInRectQuery(field, minLat, maxLat, minLon, GeoUtils.MAX_LON_INCL);
- q.add(new BooleanClause(right, BooleanClause.Occur.SHOULD));
- return new ConstantScoreQuery(q.build());
- } else {
- return super.rewrite(reader);
- }
- }
-
- @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 PointInRectQuery) {
- final PointInRectQuery q = (PointInRectQuery) 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("]")
- .toString();
- }
-}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonPoint.java b/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonPoint.java
new file mode 100644
index 00000000000..fc98c464d19
--- /dev/null
+++ b/lucene/sandbox/src/test/org/apache/lucene/document/TestLatLonPoint.java
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.document;
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.RandomIndexWriter;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.LuceneTestCase;
+
+/** Simple tests for {@link LatLonPoint} */
+public class TestLatLonPoint extends LuceneTestCase {
+
+ /** Add a single address and search for it in a box */
+ // NOTE: we don't currently supply an exact search, only ranges, because of the lossiness...
+ public void testBasics() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
+
+ // add a doc with an address
+ Document document = new Document();
+ document.add(new LatLonPoint("field", 18.313694, -65.227444));
+ writer.addDocument(document);
+
+ // search and verify we found our doc
+ IndexReader reader = writer.getReader();
+ IndexSearcher searcher = newSearcher(reader);
+ assertEquals(1, searcher.count(LatLonPoint.newBoxQuery("field", 18, 19, -66, -65)));
+
+ reader.close();
+ writer.close();
+ dir.close();
+ }
+
+ public void testToString() throws Exception {
+ // looks crazy due to lossiness
+ assertEquals("<field:18.313693958334625,-65.22744392976165>",(new LatLonPoint("field", 18.313694, -65.227444)).toString());
+
+ // looks crazy due to lossiness
+ assertEquals("field:[17.99999997485429 TO 18.999999999068677},[-65.9999999217689 TO -64.99999998137355}", LatLonPoint.newBoxQuery("field", 18, 19, -66, -65).toString());
+ }
+}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestLatLonPointQueries.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestLatLonPointQueries.java
index 5ae9503fd56..5c12a5411e0 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestLatLonPointQueries.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestLatLonPointQueries.java
@@ -25,6 +25,7 @@ import org.apache.lucene.spatial.util.GeoRect;
public class TestLatLonPointQueries extends BaseGeoPointTestCase {
// todo deconflict GeoPoint and BKD encoding methods and error tolerance
public static final double BKD_TOLERANCE = 1e-7;
+ public static final double ENCODING_TOLERANCE = 1e-7;
@Override
protected void addPointToDoc(String field, Document doc, double lat, double lon) {
@@ -33,7 +34,7 @@ public class TestLatLonPointQueries extends BaseGeoPointTestCase {
@Override
protected Query newRectQuery(String field, GeoRect rect) {
- return new PointInRectQuery(field, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
+ return LatLonPoint.newBoxQuery(field, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
}
@Override
@@ -49,7 +50,7 @@ public class TestLatLonPointQueries extends BaseGeoPointTestCase {
@Override
protected Query newPolygonQuery(String field, double[] lats, double[] lons) {
- return new PointInPolygonQuery(FIELD_NAME, lats, lons);
+ return LatLonPoint.newPolygonQuery(FIELD_NAME, lats, lons);
}
@Override
@@ -119,11 +120,11 @@ public class TestLatLonPointQueries extends BaseGeoPointTestCase {
for(int iter=0;iter<iters;iter++) {
double lat = randomLat(small);
double latEnc = LatLonPoint.decodeLat(LatLonPoint.encodeLat(lat));
- assertEquals("lat=" + lat + " latEnc=" + latEnc + " diff=" + (lat - latEnc), lat, latEnc, LatLonPoint.TOLERANCE);
+ assertEquals("lat=" + lat + " latEnc=" + latEnc + " diff=" + (lat - latEnc), lat, latEnc, ENCODING_TOLERANCE);
double lon = randomLon(small);
double lonEnc = LatLonPoint.decodeLon(LatLonPoint.encodeLon(lon));
- assertEquals("lon=" + lon + " lonEnc=" + lonEnc + " diff=" + (lon - lonEnc), lon, lonEnc, LatLonPoint.TOLERANCE);
+ assertEquals("lon=" + lon + " lonEnc=" + lonEnc + " diff=" + (lon - lonEnc), lon, lonEnc, ENCODING_TOLERANCE);
}
}