You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by dw...@apache.org on 2020/12/23 11:44:31 UTC
[lucene-solr] 02/11: :lucene:core -
src/**/org/apache/lucene/document/**
This is an automated email from the ASF dual-hosted git repository.
dweiss pushed a commit to branch jira/LUCENE-9570
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git
commit c405405defa3b6d36d7907d7b8e20d3007d470b9
Author: Dawid Weiss <da...@carrotsearch.com>
AuthorDate: Wed Dec 23 10:25:09 2020 +0100
:lucene:core - src/**/org/apache/lucene/document/**
---
gradle/validation/spotless.gradle | 4 +-
.../lucene/document/BinaryDocValuesField.java | 33 +-
.../org/apache/lucene/document/BinaryPoint.java | 167 ++++----
.../lucene/document/BinaryRangeDocValues.java | 7 +-
.../lucene/document/BinaryRangeDocValuesField.java | 5 +-
.../document/BinaryRangeFieldRangeQuery.java | 41 +-
.../java/org/apache/lucene/document/DateTools.java | 166 ++++----
.../java/org/apache/lucene/document/Document.java | 172 ++++----
.../document/DocumentStoredFieldVisitor.java | 39 +-
.../lucene/document/DoubleDocValuesField.java | 25 +-
.../org/apache/lucene/document/DoublePoint.java | 182 ++++----
.../org/apache/lucene/document/DoubleRange.java | 121 +++---
.../lucene/document/DoubleRangeDocValuesField.java | 23 +-
.../lucene/document/DoubleRangeSlowRangeQuery.java | 10 +-
.../lucene/document/FeatureDoubleValuesSource.java | 25 +-
.../org/apache/lucene/document/FeatureField.java | 353 +++++++++-------
.../org/apache/lucene/document/FeatureQuery.java | 20 +-
.../apache/lucene/document/FeatureSortField.java | 24 +-
.../src/java/org/apache/lucene/document/Field.java | 308 +++++++-------
.../java/org/apache/lucene/document/FieldType.java | 229 +++++-----
.../lucene/document/FloatDocValuesField.java | 26 +-
.../org/apache/lucene/document/FloatPoint.java | 176 ++++----
.../org/apache/lucene/document/FloatRange.java | 121 +++---
.../lucene/document/FloatRangeDocValuesField.java | 23 +-
.../lucene/document/FloatRangeSlowRangeQuery.java | 7 +-
.../apache/lucene/document/InetAddressPoint.java | 172 ++++----
.../apache/lucene/document/InetAddressRange.java | 61 ++-
.../java/org/apache/lucene/document/IntPoint.java | 159 ++++---
.../java/org/apache/lucene/document/IntRange.java | 121 +++---
.../lucene/document/IntRangeDocValuesField.java | 26 +-
.../lucene/document/IntRangeSlowRangeQuery.java | 6 +-
.../lucene/document/LatLonDocValuesBoxQuery.java | 88 ++--
.../lucene/document/LatLonDocValuesField.java | 167 +++++---
.../LatLonDocValuesPointInGeometryQuery.java | 60 +--
.../org/apache/lucene/document/LatLonPoint.java | 180 ++++----
.../document/LatLonPointDistanceComparator.java | 72 ++--
.../document/LatLonPointDistanceFeatureQuery.java | 321 +++++++++-----
.../lucene/document/LatLonPointDistanceQuery.java | 119 ++++--
.../document/LatLonPointInGeometryQuery.java | 158 ++++---
.../lucene/document/LatLonPointSortField.java | 15 +-
.../org/apache/lucene/document/LatLonShape.java | 140 +++---
.../document/LatLonShapeBoundingBoxQuery.java | 459 +++++++++++---------
.../apache/lucene/document/LatLonShapeQuery.java | 200 +++++----
.../lucene/document/LongDistanceFeatureQuery.java | 163 ++++---
.../java/org/apache/lucene/document/LongPoint.java | 186 ++++----
.../java/org/apache/lucene/document/LongRange.java | 117 +++--
.../lucene/document/LongRangeDocValuesField.java | 23 +-
.../lucene/document/LongRangeSlowRangeQuery.java | 7 +-
.../lucene/document/NumericDocValuesField.java | 66 ++-
.../apache/lucene/document/RangeFieldQuery.java | 319 +++++++++++---
.../org/apache/lucene/document/ShapeField.java | 147 ++++---
.../org/apache/lucene/document/ShapeQuery.java | 310 +++++++++-----
.../lucene/document/SortedDocValuesField.java | 68 ++-
.../document/SortedNumericDocValuesField.java | 79 ++--
.../document/SortedNumericDocValuesRangeQuery.java | 68 +--
.../lucene/document/SortedSetDocValuesField.java | 72 ++--
.../document/SortedSetDocValuesRangeQuery.java | 80 ++--
.../org/apache/lucene/document/StoredField.java | 88 ++--
.../org/apache/lucene/document/StringField.java | 46 +-
.../java/org/apache/lucene/document/TextField.java | 24 +-
.../org/apache/lucene/document/VectorField.java | 57 +--
.../apache/lucene/document/XYDocValuesField.java | 141 ++++---
.../document/XYDocValuesPointInGeometryQuery.java | 44 +-
.../lucene/document/XYPointDistanceComparator.java | 43 +-
.../org/apache/lucene/document/XYPointField.java | 89 ++--
.../lucene/document/XYPointInGeometryQuery.java | 94 ++---
.../apache/lucene/document/XYPointSortField.java | 12 +-
.../java/org/apache/lucene/document/XYShape.java | 105 +++--
.../org/apache/lucene/document/XYShapeQuery.java | 177 ++++----
.../org/apache/lucene/document/package-info.java | 55 ++-
.../lucene/document/BaseLatLonShapeTestCase.java | 144 +++++--
.../lucene/document/BaseShapeEncodingTestCase.java | 169 ++++++--
.../apache/lucene/document/BaseShapeTestCase.java | 275 +++++++-----
.../lucene/document/BaseXYShapeTestCase.java | 47 ++-
.../apache/lucene/document/TestBinaryDocument.java | 37 +-
.../org/apache/lucene/document/TestDateTools.java | 104 ++---
.../org/apache/lucene/document/TestDocument.java | 164 +++----
.../apache/lucene/document/TestDoubleRange.java | 6 +-
.../lucene/document/TestFeatureDoubleValues.java | 109 ++---
.../apache/lucene/document/TestFeatureField.java | 77 ++--
.../apache/lucene/document/TestFeatureSort.java | 48 ++-
.../test/org/apache/lucene/document/TestField.java | 251 ++++++-----
.../org/apache/lucene/document/TestFieldType.java | 40 +-
.../org/apache/lucene/document/TestFloatRange.java | 8 +-
.../lucene/document/TestInetAddressPoint.java | 177 +++++---
.../org/apache/lucene/document/TestIntRange.java | 2 +-
.../lucene/document/TestLatLonDocValuesField.java | 10 +-
.../document/TestLatLonLineShapeQueries.java | 13 +-
.../document/TestLatLonMultiLineShapeQueries.java | 11 +-
.../document/TestLatLonMultiPointShapeQueries.java | 11 +-
.../TestLatLonMultiPolygonShapeQueries.java | 16 +-
.../apache/lucene/document/TestLatLonPoint.java | 21 +-
.../TestLatLonPointDistanceFeatureQuery.java | 226 +++++++---
.../document/TestLatLonPointDistanceSort.java | 87 ++--
.../document/TestLatLonPointShapeQueries.java | 21 +-
.../document/TestLatLonPolygonShapeQueries.java | 5 +-
.../apache/lucene/document/TestLatLonShape.java | 469 ++++++++++++---------
.../lucene/document/TestLatLonShapeEncoding.java | 2 +-
.../document/TestLongDistanceFeatureQuery.java | 117 +++--
.../org/apache/lucene/document/TestLongRange.java | 2 +-
.../lucene/document/TestXYLineShapeQueries.java | 19 +-
.../document/TestXYMultiLineShapeQueries.java | 14 +-
.../document/TestXYMultiPointShapeQueries.java | 9 +-
.../document/TestXYMultiPolygonShapeQueries.java | 15 +-
.../lucene/document/TestXYPointShapeQueries.java | 23 +-
.../lucene/document/TestXYPolygonShapeQueries.java | 13 +-
.../org/apache/lucene/document/TestXYShape.java | 54 ++-
.../lucene/document/TestXYShapeEncoding.java | 2 +-
108 files changed, 6036 insertions(+), 4293 deletions(-)
diff --git a/gradle/validation/spotless.gradle b/gradle/validation/spotless.gradle
index 084b3e5..6e35970 100644
--- a/gradle/validation/spotless.gradle
+++ b/gradle/validation/spotless.gradle
@@ -25,8 +25,6 @@ allprojects { prj ->
plugins.withType(JavaPlugin) {
prj.apply plugin: 'com.diffplug.spotless'
- println "case \"" + prj.path + '"'
-
spotless {
java {
// TODO: work out how to have multiple different header files (we have
@@ -49,7 +47,7 @@ allprojects { prj ->
target "src/**/org/apache/lucene/*.java",
"src/**/org/apache/lucene/analysis/**",
// "src/**/org/apache/lucene/codecs/**",
- // "src/**/org/apache/lucene/document/**",
+ "src/**/org/apache/lucene/document/**",
"src/**/org/apache/lucene/geo/**",
"src/**/org/apache/lucene/index/**",
// "src/**/org/apache/lucene/search/**",
diff --git a/lucene/core/src/java/org/apache/lucene/document/BinaryDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/BinaryDocValuesField.java
index 94093b2..ffebe97 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryDocValuesField.java
@@ -21,36 +21,33 @@ import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.util.BytesRef;
/**
- * Field that stores a per-document {@link BytesRef} value.
- * <p>
- * The values are stored directly with no sharing, which is a good fit when
- * the fields don't share (many) values, such as a title field. If values
- * may be shared and sorted it's better to use {@link SortedDocValuesField}.
- * Here's an example usage:
- *
+ * Field that stores a per-document {@link BytesRef} value.
+ *
+ * <p>The values are stored directly with no sharing, which is a good fit when the fields don't
+ * share (many) values, such as a title field. If values may be shared and sorted it's better to use
+ * {@link SortedDocValuesField}. Here's an example usage:
+ *
* <pre class="prettyprint">
* document.add(new BinaryDocValuesField(name, new BytesRef("hello")));
* </pre>
- *
- * <p>
- * If you also need to store the value, you should add a
- * separate {@link StoredField} instance.
- *
+ *
+ * <p>If you also need to store the value, you should add a separate {@link StoredField} instance.
+ *
* @see BinaryDocValues
- * */
+ */
public class BinaryDocValuesField extends Field {
-
- /**
- * Type for straight bytes DocValues.
- */
+
+ /** Type for straight bytes DocValues. */
public static final FieldType TYPE = new FieldType();
+
static {
TYPE.setDocValuesType(DocValuesType.BINARY);
TYPE.freeze();
}
-
+
/**
* Create a new binary DocValues field.
+ *
* @param name field name
* @param value binary content
* @throws IllegalArgumentException if the field name is null
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 dd47f59..cede07c 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryPoint.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.util.Arrays;
import java.util.Comparator;
-
import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.MatchNoDocsQuery;
@@ -27,21 +26,24 @@ import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
-/**
- * An indexed binary field for fast range filters. If you also
- * need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * Finding all documents within an N-dimensional shape or 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:
+/**
+ * An indexed binary field for fast range filters. If you also need to store the value, you should
+ * add a separate {@link StoredField} instance.
+ *
+ * <p>Finding all documents within an N-dimensional shape or 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 #newExactQuery(String, byte[])} for matching an exact 1D point.
- * <li>{@link #newSetQuery(String, byte[][]) newSetQuery(String, byte[]...)} for matching a set of 1D values.
+ * <li>{@link #newSetQuery(String, byte[][]) newSetQuery(String, byte[]...)} for matching a set of
+ * 1D values.
* <li>{@link #newRangeQuery(String, byte[], byte[])} for matching a 1D range.
- * <li>{@link #newRangeQuery(String, byte[][], byte[][])} for matching points/ranges in n-dimensional space.
- * </ul>
+ * <li>{@link #newRangeQuery(String, byte[][], byte[][])} for matching points/ranges in
+ * n-dimensional space.
+ * </ul>
+ *
* @see PointValues
*/
public final class BinaryPoint extends Field {
@@ -54,7 +56,7 @@ public final class BinaryPoint extends Field {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
int bytesPerDim = -1;
- for(int i=0;i<point.length;i++) {
+ for (int i = 0; i < point.length; i++) {
byte[] oneDim = point[i];
if (oneDim == null) {
throw new IllegalArgumentException("point must not have null values");
@@ -65,7 +67,11 @@ public final class BinaryPoint extends Field {
if (bytesPerDim == -1) {
bytesPerDim = oneDim.length;
} else if (bytesPerDim != oneDim.length) {
- throw new IllegalArgumentException("all dimensions must have same bytes length; got " + bytesPerDim + " and " + oneDim.length);
+ throw new IllegalArgumentException(
+ "all dimensions must have same bytes length; got "
+ + bytesPerDim
+ + " and "
+ + oneDim.length);
}
}
return getType(point.length, bytesPerDim);
@@ -89,7 +95,7 @@ public final class BinaryPoint extends Field {
return new BytesRef(point[0]);
}
int bytesPerDim = -1;
- for(byte[] dim : point) {
+ for (byte[] dim : point) {
if (dim == null) {
throw new IllegalArgumentException("point must not have null values");
}
@@ -99,22 +105,27 @@ public final class BinaryPoint extends Field {
}
bytesPerDim = dim.length;
} else if (dim.length != bytesPerDim) {
- throw new IllegalArgumentException("all dimensions must have same bytes length; got " + bytesPerDim + " and " + dim.length);
+ throw new IllegalArgumentException(
+ "all dimensions must have same bytes length; got "
+ + bytesPerDim
+ + " and "
+ + dim.length);
}
}
- byte[] packed = new byte[bytesPerDim*point.length];
- for(int i=0;i<point.length;i++) {
- System.arraycopy(point[i], 0, packed, i*bytesPerDim, bytesPerDim);
+ byte[] packed = new byte[bytesPerDim * point.length];
+ for (int i = 0; i < point.length; i++) {
+ System.arraycopy(point[i], 0, packed, i * bytesPerDim, bytesPerDim);
}
return new BytesRef(packed);
}
- /** General purpose API: creates a new BinaryPoint, indexing the
- * provided N-dimensional binary point.
+ /**
+ * General purpose API: creates a new BinaryPoint, indexing the provided N-dimensional binary
+ * point.
*
- * @param name field name
- * @param point byte[][] value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point byte[][] value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public BinaryPoint(String name, byte[]... point) {
super(name, pack(point), getType(point));
@@ -124,17 +135,23 @@ public final class BinaryPoint extends Field {
public BinaryPoint(String name, byte[] packedPoint, IndexableFieldType type) {
super(name, packedPoint, type);
if (packedPoint.length != type.pointDimensionCount() * type.pointNumBytes()) {
- throw new IllegalArgumentException("packedPoint is length=" + packedPoint.length + " but type.pointDimensionCount()=" + type.pointDimensionCount() + " and type.pointNumBytes()=" + type.pointNumBytes());
+ throw new IllegalArgumentException(
+ "packedPoint is length="
+ + packedPoint.length
+ + " but type.pointDimensionCount()="
+ + type.pointDimensionCount()
+ + " and type.pointNumBytes()="
+ + type.pointNumBytes());
}
}
-
+
// static methods for generating queries
- /**
+ /**
* Create a query for matching an exact binary value.
- * <p>
- * This is for simple one-dimension points, for multidimensional points use
- * {@link #newRangeQuery(String, byte[][], byte[][])} instead.
+ *
+ * <p>This is for simple one-dimension points, for multidimensional points use {@link
+ * #newRangeQuery(String, byte[][], byte[][])} instead.
*
* @param field field name. must not be {@code null}.
* @param value binary value
@@ -145,36 +162,37 @@ public final class BinaryPoint extends Field {
return newRangeQuery(field, value, value);
}
- /**
+ /**
* Create a range query for binary values.
- * <p>
- * This is for simple one-dimension ranges, for multidimensional ranges use
- * {@link #newRangeQuery(String, byte[][], byte[][])} instead.
+ *
+ * <p>This is for simple one-dimension ranges, for multidimensional ranges use {@link
+ * #newRangeQuery(String, byte[][], byte[][])} instead.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be {@code null}
* @param upperValue upper portion of the range (inclusive). must not be {@code null}
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null,
- * or if {@code upperValue} is null
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, or if
+ * {@code upperValue} is null
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, byte[] lowerValue, byte[] upperValue) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
return newRangeQuery(field, new byte[][] {lowerValue}, new byte[][] {upperValue});
}
-
- /**
+
+ /**
* Create a range query for n-dimensional binary values.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be null.
* @param upperValue upper portion of the range (inclusive). must not be null.
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if {@code upperValue} is null,
- * or if {@code lowerValue.length != upperValue.length}
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if
+ * {@code upperValue} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, byte[][] lowerValue, byte[][] upperValue) {
- return new PointRangeQuery(field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
+ return new PointRangeQuery(
+ field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
@Override
protected String toString(int dimension, byte[] value) {
assert value != null;
@@ -193,8 +211,9 @@ public final class BinaryPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -202,47 +221,53 @@ public final class BinaryPoint extends Field {
// Make sure all byte[] have the same length
int bytesPerDim = -1;
- for(byte[] value : values) {
+ for (byte[] value : values) {
if (bytesPerDim == -1) {
bytesPerDim = value.length;
} else if (value.length != bytesPerDim) {
- throw new IllegalArgumentException("all byte[] must be the same length, but saw " + bytesPerDim + " and " + value.length);
+ throw new IllegalArgumentException(
+ "all byte[] must be the same length, but saw " + bytesPerDim + " and " + value.length);
}
}
if (bytesPerDim == -1) {
- // There are no points, and we cannot guess the bytesPerDim here, so we return an equivalent query:
+ // There are no points, and we cannot guess the bytesPerDim here, so we return an equivalent
+ // query:
return new MatchNoDocsQuery("empty BinaryPoint.newSetQuery");
}
// Don't unexpectedly change the user's incoming values array:
byte[][] sortedValues = values.clone();
- Arrays.sort(sortedValues,
- new Comparator<byte[]>() {
- @Override
- public int compare(byte[] a, byte[] b) {
- return Arrays.compareUnsigned(a, 0, a.length, b, 0, b.length);
- }
- });
+ Arrays.sort(
+ sortedValues,
+ new Comparator<byte[]>() {
+ @Override
+ public int compare(byte[] a, byte[] b) {
+ return Arrays.compareUnsigned(a, 0, a.length, b, 0, b.length);
+ }
+ });
final BytesRef encoded = new BytesRef(new byte[bytesPerDim]);
-
- return new PointInSetQuery(field, 1, bytesPerDim,
- new PointInSetQuery.Stream() {
-
- int upto;
-
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encoded.bytes = sortedValues[upto];
- upto++;
- return encoded;
- }
- }
- }) {
+
+ return new PointInSetQuery(
+ field,
+ 1,
+ bytesPerDim,
+ new PointInSetQuery.Stream() {
+
+ int upto;
+
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encoded.bytes = sortedValues[upto];
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
return new BytesRef(value).toString();
diff --git a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValues.java b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValues.java
index d5e511f..e057e1d 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValues.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValues.java
@@ -18,7 +18,6 @@
package org.apache.lucene.document;
import java.io.IOException;
-
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.util.BytesRef;
@@ -90,7 +89,9 @@ class BinaryRangeDocValues extends BinaryDocValues {
BytesRef bytesRef = in.binaryValue();
// We reuse the existing allocated memory for packed values since all docvalues in this iterator
- // should be exactly same in indexed structure, hence the byte representations in length should be identical
- System.arraycopy(bytesRef.bytes, bytesRef.offset, packedValue, 0, 2 * numDims * numBytesPerDimension);
+ // should be exactly same in indexed structure, hence the byte representations in length should
+ // be identical
+ System.arraycopy(
+ bytesRef.bytes, bytesRef.offset, packedValue, 0, 2 * numDims * numBytesPerDimension);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValuesField.java
index 1d0504a..999aa8d 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeDocValuesField.java
@@ -20,13 +20,14 @@ package org.apache.lucene.document;
import org.apache.lucene.util.BytesRef;
abstract class BinaryRangeDocValuesField extends BinaryDocValuesField {
-
+
final String field;
final byte[] packedValue;
final int numDims;
final int numBytesPerDimension;
- BinaryRangeDocValuesField(String field, byte[] packedValue, int numDims, int numBytesPerDimension) {
+ BinaryRangeDocValuesField(
+ String field, byte[] packedValue, int numDims, int numBytesPerDimension) {
super(field, new BytesRef(packedValue));
this.field = field;
this.packedValue = packedValue;
diff --git a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeFieldRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeFieldRangeQuery.java
index 9134bb0..f5ceb64 100644
--- a/lucene/core/src/java/org/apache/lucene/document/BinaryRangeFieldRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/BinaryRangeFieldRangeQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.IndexReader;
@@ -43,15 +42,20 @@ abstract class BinaryRangeFieldRangeQuery extends Query {
private final int numDims;
private final RangeFieldQuery.QueryType queryType;
- BinaryRangeFieldRangeQuery(String field, byte[] queryPackedValue, int numBytesPerDimension, int numDims,
- RangeFieldQuery.QueryType queryType) {
+ BinaryRangeFieldRangeQuery(
+ String field,
+ byte[] queryPackedValue,
+ int numBytesPerDimension,
+ int numDims,
+ RangeFieldQuery.QueryType queryType) {
this.field = field;
this.queryPackedValue = queryPackedValue;
this.numBytesPerDimension = numBytesPerDimension;
this.numDims = numDims;
if (!(queryType == RangeFieldQuery.QueryType.INTERSECTS)) {
- throw new UnsupportedOperationException("INTERSECTS is the only query type supported for this field type right now");
+ throw new UnsupportedOperationException(
+ "INTERSECTS is the only query type supported for this field type right now");
}
this.queryType = queryType;
@@ -93,9 +97,9 @@ abstract class BinaryRangeFieldRangeQuery extends Query {
return new BinaryRangeDocValues(binaryDocValues, numDims, numBytesPerDimension);
}
-
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
return new ConstantScoreWeight(this, boost) {
@Override
@@ -106,17 +110,19 @@ abstract class BinaryRangeFieldRangeQuery extends Query {
}
final TwoPhaseIterator iterator;
- iterator = new TwoPhaseIterator(values) {
- @Override
- public boolean matches() {
- return queryType.matches(queryPackedValue, values.getPackedValue(), numDims, numBytesPerDimension);
- }
-
- @Override
- public float matchCost() {
- return queryPackedValue.length;
- }
- };
+ iterator =
+ new TwoPhaseIterator(values) {
+ @Override
+ public boolean matches() {
+ return queryType.matches(
+ queryPackedValue, values.getPackedValue(), numDims, numBytesPerDimension);
+ }
+
+ @Override
+ public float matchCost() {
+ return queryPackedValue.length;
+ }
+ };
return new ConstantScoreScorer(this, score(), scoreMode, iterator);
}
@@ -125,7 +131,6 @@ abstract class BinaryRangeFieldRangeQuery extends Query {
public boolean isCacheable(LeafReaderContext ctx) {
return DocValues.isCacheable(ctx, field);
}
-
};
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/DateTools.java b/lucene/core/src/java/org/apache/lucene/document/DateTools.java
index e7ac4c5..49e404b 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DateTools.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DateTools.java
@@ -16,69 +16,64 @@
*/
package org.apache.lucene.document;
-
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
-
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.TermRangeQuery;
/**
- * Provides support for converting dates to strings and vice-versa.
- * The strings are structured so that lexicographic sorting orders
- * them by date, which makes them suitable for use as field values
+ * Provides support for converting dates to strings and vice-versa. The strings are structured so
+ * that lexicographic sorting orders them by date, which makes them suitable for use as field values
* and search terms.
- *
- * <P>This class also helps you to limit the resolution of your dates. Do not
- * save dates with a finer resolution than you really need, as then
- * {@link TermRangeQuery} and {@link PrefixQuery} will require more memory and become slower.
- *
- * <P>
- * Another approach is {@link LongPoint}, which indexes the
- * values in sorted order.
- * For indexing a {@link Date} or {@link Calendar}, just get the unix timestamp as
- * <code>long</code> using {@link Date#getTime} or {@link Calendar#getTimeInMillis} and
- * index this as a numeric value with {@link LongPoint}
- * and use {@link org.apache.lucene.search.PointRangeQuery} to query it.
+ *
+ * <p>This class also helps you to limit the resolution of your dates. Do not save dates with a
+ * finer resolution than you really need, as then {@link TermRangeQuery} and {@link PrefixQuery}
+ * will require more memory and become slower.
+ *
+ * <p>Another approach is {@link LongPoint}, which indexes the values in sorted order. For indexing
+ * a {@link Date} or {@link Calendar}, just get the unix timestamp as <code>long</code> using {@link
+ * Date#getTime} or {@link Calendar#getTimeInMillis} and index this as a numeric value with {@link
+ * LongPoint} and use {@link org.apache.lucene.search.PointRangeQuery} to query it.
*/
public class DateTools {
-
- final static TimeZone GMT = TimeZone.getTimeZone("GMT");
- private static final ThreadLocal<Calendar> TL_CAL = new ThreadLocal<Calendar>() {
- @Override
- protected Calendar initialValue() {
- return Calendar.getInstance(GMT, Locale.ROOT);
- }
- };
-
- //indexed by format length
- private static final ThreadLocal<SimpleDateFormat[]> TL_FORMATS = new ThreadLocal<SimpleDateFormat[]>() {
- @Override
- protected SimpleDateFormat[] initialValue() {
- SimpleDateFormat[] arr = new SimpleDateFormat[Resolution.MILLISECOND.formatLen+1];
- for (Resolution resolution : Resolution.values()) {
- arr[resolution.formatLen] = (SimpleDateFormat)resolution.format.clone();
- }
- return arr;
- }
- };
+ static final TimeZone GMT = TimeZone.getTimeZone("GMT");
+
+ private static final ThreadLocal<Calendar> TL_CAL =
+ new ThreadLocal<Calendar>() {
+ @Override
+ protected Calendar initialValue() {
+ return Calendar.getInstance(GMT, Locale.ROOT);
+ }
+ };
+
+ // indexed by format length
+ private static final ThreadLocal<SimpleDateFormat[]> TL_FORMATS =
+ new ThreadLocal<SimpleDateFormat[]>() {
+ @Override
+ protected SimpleDateFormat[] initialValue() {
+ SimpleDateFormat[] arr = new SimpleDateFormat[Resolution.MILLISECOND.formatLen + 1];
+ for (Resolution resolution : Resolution.values()) {
+ arr[resolution.formatLen] = (SimpleDateFormat) resolution.format.clone();
+ }
+ return arr;
+ }
+ };
// cannot create, the class has static methods only
private DateTools() {}
/**
* Converts a Date to a string suitable for indexing.
- *
+ *
* @param date the date to be converted
- * @param resolution the desired resolution, see
- * {@link #round(Date, DateTools.Resolution)}
- * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
- * depending on <code>resolution</code>; using GMT as timezone
+ * @param resolution the desired resolution, see {@link #round(Date, DateTools.Resolution)}
+ * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter, depending on <code>
+ * resolution</code>; using GMT as timezone
*/
public static String dateToString(Date date, Resolution resolution) {
return timeToString(date.getTime(), resolution);
@@ -86,41 +81,36 @@ public class DateTools {
/**
* Converts a millisecond time to a string suitable for indexing.
- *
+ *
* @param time the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT
- * @param resolution the desired resolution, see
- * {@link #round(long, DateTools.Resolution)}
- * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
- * depending on <code>resolution</code>; using GMT as timezone
+ * @param resolution the desired resolution, see {@link #round(long, DateTools.Resolution)}
+ * @return a string in format <code>yyyyMMddHHmmssSSS</code> or shorter, depending on <code>
+ * resolution</code>; using GMT as timezone
*/
public static String timeToString(long time, Resolution resolution) {
final Date date = new Date(round(time, resolution));
return TL_FORMATS.get()[resolution.formatLen].format(date);
}
-
+
/**
- * Converts a string produced by <code>timeToString</code> or
- * <code>dateToString</code> back to a time, represented as the
- * number of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
+ * Converts a string produced by <code>timeToString</code> or <code>dateToString</code> back to a
+ * time, represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT.
+ *
* @param dateString the date string to be converted
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
- * @throws ParseException if <code>dateString</code> is not in the
- * expected format
+ * @throws ParseException if <code>dateString</code> is not in the expected format
*/
public static long stringToTime(String dateString) throws ParseException {
return stringToDate(dateString).getTime();
}
/**
- * Converts a string produced by <code>timeToString</code> or
- * <code>dateToString</code> back to a time, represented as a
- * Date object.
- *
+ * Converts a string produced by <code>timeToString</code> or <code>dateToString</code> back to a
+ * time, represented as a Date object.
+ *
* @param dateString the date string to be converted
- * @return the parsed time as a Date object
- * @throws ParseException if <code>dateString</code> is not in the
- * expected format
+ * @return the parsed time as a Date object
+ * @throws ParseException if <code>dateString</code> is not in the expected format
*/
public static Date stringToDate(String dateString) throws ParseException {
try {
@@ -129,37 +119,34 @@ public class DateTools {
throw new ParseException("Input is not a valid date string: " + dateString, 0);
}
}
-
+
/**
- * Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code>
- * will be changed to <code>2004-09-01 00:00:00</code> when using
- * <code>Resolution.MONTH</code>.
- *
+ * Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code> will be
+ * changed to <code>2004-09-01 00:00:00</code> when using <code>Resolution.MONTH</code>.
+ *
* @param resolution The desired resolution of the date to be returned
- * @return the date with all values more precise than <code>resolution</code>
- * set to 0 or 1
+ * @return the date with all values more precise than <code>resolution</code> set to 0 or 1
*/
public static Date round(Date date, Resolution resolution) {
return new Date(round(date.getTime(), resolution));
}
-
+
/**
- * Limit a date's resolution. For example, the date <code>1095767411000</code>
- * (which represents 2004-09-21 13:50:11) will be changed to
- * <code>1093989600000</code> (2004-09-01 00:00:00) when using
- * <code>Resolution.MONTH</code>.
- *
+ * Limit a date's resolution. For example, the date <code>1095767411000</code> (which represents
+ * 2004-09-21 13:50:11) will be changed to <code>1093989600000</code> (2004-09-01 00:00:00) when
+ * using <code>Resolution.MONTH</code>.
+ *
* @param resolution The desired resolution of the date to be returned
- * @return the date with all values more precise than <code>resolution</code>
- * set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
+ * @return the date with all values more precise than <code>resolution</code> set to 0 or 1,
+ * expressed as milliseconds since January 1, 1970, 00:00:00 GMT
*/
@SuppressWarnings("fallthrough")
public static long round(long time, Resolution resolution) {
final Calendar calInstance = TL_CAL.get();
calInstance.setTimeInMillis(time);
-
+
switch (resolution) {
- //NOTE: switch statement fall-through is deliberate
+ // NOTE: switch statement fall-through is deliberate
case YEAR:
calInstance.set(Calendar.MONTH, 0);
case MONTH:
@@ -183,40 +170,37 @@ public class DateTools {
/** Specifies the time granularity. */
public static enum Resolution {
-
+
/** Limit a date's resolution to year granularity. */
- YEAR(4),
+ YEAR(4),
/** Limit a date's resolution to month granularity. */
- MONTH(6),
+ MONTH(6),
/** Limit a date's resolution to day granularity. */
- DAY(8),
+ DAY(8),
/** Limit a date's resolution to hour granularity. */
- HOUR(10),
+ HOUR(10),
/** Limit a date's resolution to minute granularity. */
- MINUTE(12),
+ MINUTE(12),
/** Limit a date's resolution to second granularity. */
- SECOND(14),
+ SECOND(14),
/** Limit a date's resolution to millisecond granularity. */
MILLISECOND(17);
final int formatLen;
- final SimpleDateFormat format;//should be cloned before use, since it's not threadsafe
+ final SimpleDateFormat format; // should be cloned before use, since it's not threadsafe
Resolution(int formatLen) {
this.formatLen = formatLen;
// formatLen 10's place: 11111111
// formatLen 1's place: 12345678901234567
- this.format = new SimpleDateFormat("yyyyMMddHHmmssSSS".substring(0,formatLen),Locale.ROOT);
+ this.format = new SimpleDateFormat("yyyyMMddHHmmssSSS".substring(0, formatLen), Locale.ROOT);
this.format.setTimeZone(GMT);
}
- /** this method returns the name of the resolution
- * in lowercase (for backwards compatibility) */
+ /** this method returns the name of the resolution in lowercase (for backwards compatibility) */
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ROOT);
}
-
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/Document.java b/lucene/core/src/java/org/apache/lucene/document/Document.java
index 2f44444..57061e2 100644
--- a/lucene/core/src/java/org/apache/lucene/document/Document.java
+++ b/lucene/core/src/java/org/apache/lucene/document/Document.java
@@ -16,63 +16,59 @@
*/
package org.apache.lucene.document;
-
import java.util.*;
-
-import org.apache.lucene.index.IndexReader; // for javadoc
+import org.apache.lucene.index.IndexReader; // for javadoc
import org.apache.lucene.index.IndexableField;
-import org.apache.lucene.search.IndexSearcher; // for javadoc
+import org.apache.lucene.search.IndexSearcher; // for javadoc
import org.apache.lucene.search.ScoreDoc; // for javadoc
import org.apache.lucene.util.BytesRef;
-/** Documents are the unit of indexing and search.
+/**
+ * Documents are the unit of indexing and search.
*
- * A Document is a set of fields. Each field has a name and a textual value.
- * A field may be {@link org.apache.lucene.index.IndexableFieldType#stored() stored} with the document, in which
- * case it is returned with search hits on the document. Thus each document
- * should typically contain one or more stored fields which uniquely identify
- * it.
+ * <p>A Document is a set of fields. Each field has a name and a textual value. A field may be
+ * {@link org.apache.lucene.index.IndexableFieldType#stored() stored} with the document, in which
+ * case it is returned with search hits on the document. Thus each document should typically contain
+ * one or more stored fields which uniquely identify it.
*
- * <p>Note that fields which are <i>not</i> {@link org.apache.lucene.index.IndexableFieldType#stored() stored} are
- * <i>not</i> available in documents retrieved from the index, e.g. with {@link
- * ScoreDoc#doc} or {@link IndexReader#document(int)}.
+ * <p>Note that fields which are <i>not</i> {@link
+ * org.apache.lucene.index.IndexableFieldType#stored() stored} are <i>not</i> available in documents
+ * retrieved from the index, e.g. with {@link ScoreDoc#doc} or {@link IndexReader#document(int)}.
*/
-
public final class Document implements Iterable<IndexableField> {
private final List<IndexableField> fields = new ArrayList<>();
/** Constructs a new document with no fields. */
public Document() {}
-
+
@Override
public Iterator<IndexableField> iterator() {
return fields.iterator();
}
/**
- * <p>Adds a field to a document. Several fields may be added with
- * the same name. In this case, if the fields are indexed, their text is
- * treated as though appended for the purposes of search.</p>
- * <p> Note that add like the removeField(s) methods only makes sense
- * prior to adding a document to an index. These methods cannot
- * be used to change the content of an existing index! In order to achieve this,
- * a document has to be deleted from an index and a new changed version of that
- * document has to be added.</p>
+ * Adds a field to a document. Several fields may be added with the same name. In this case, if
+ * the fields are indexed, their text is treated as though appended for the purposes of search.
+ *
+ * <p>Note that add like the removeField(s) methods only makes sense prior to adding a document to
+ * an index. These methods cannot be used to change the content of an existing index! In order to
+ * achieve this, a document has to be deleted from an index and a new changed version of that
+ * document has to be added.
*/
public final void add(IndexableField field) {
fields.add(field);
}
-
+
/**
- * <p>Removes field with the specified name from the document.
- * If multiple fields exist with this name, this method removes the first field that has been added.
- * If there is no field with the specified name, the document remains unchanged.</p>
- * <p> Note that the removeField(s) methods like the add method only make sense
- * prior to adding a document to an index. These methods cannot
- * be used to change the content of an existing index! In order to achieve this,
- * a document has to be deleted from an index and a new changed version of that
- * document has to be added.</p>
+ * Removes field with the specified name from the document. If multiple fields exist with this
+ * name, this method removes the first field that has been added. If there is no field with the
+ * specified name, the document remains unchanged.
+ *
+ * <p>Note that the removeField(s) methods like the add method only make sense prior to adding a
+ * document to an index. These methods cannot be used to change the content of an existing index!
+ * In order to achieve this, a document has to be deleted from an index and a new changed version
+ * of that document has to be added.
*/
public final void removeField(String name) {
Iterator<IndexableField> it = fields.iterator();
@@ -84,15 +80,15 @@ public final class Document implements Iterable<IndexableField> {
}
}
}
-
+
/**
- * <p>Removes all fields with the given name from the document.
- * If there is no field with the specified name, the document remains unchanged.</p>
- * <p> Note that the removeField(s) methods like the add method only make sense
- * prior to adding a document to an index. These methods cannot
- * be used to change the content of an existing index! In order to achieve this,
- * a document has to be deleted from an index and a new changed version of that
- * document has to be added.</p>
+ * Removes all fields with the given name from the document. If there is no field with the
+ * specified name, the document remains unchanged.
+ *
+ * <p>Note that the removeField(s) methods like the add method only make sense prior to adding a
+ * document to an index. These methods cannot be used to change the content of an existing index!
+ * In order to achieve this, a document has to be deleted from an index and a new changed version
+ * of that document has to be added.
*/
public final void removeFields(String name) {
Iterator<IndexableField> it = fields.iterator();
@@ -104,16 +100,14 @@ public final class Document implements Iterable<IndexableField> {
}
}
-
/**
- * Returns an array of byte arrays for of the fields that have the name specified
- * as the method parameter. This method returns an empty
- * array when there are no matching fields. It never
- * returns null.
- *
- * @param name the name of the field
- * @return a <code>BytesRef[]</code> of binary field values
- */
+ * Returns an array of byte arrays for of the fields that have the name specified as the method
+ * parameter. This method returns an empty array when there are no matching fields. It never
+ * returns null.
+ *
+ * @param name the name of the field
+ * @return a <code>BytesRef[]</code> of binary field values
+ */
public final BytesRef[] getBinaryValues(String name) {
final List<BytesRef> result = new ArrayList<>();
for (IndexableField field : fields) {
@@ -124,19 +118,18 @@ public final class Document implements Iterable<IndexableField> {
}
}
}
-
+
return result.toArray(new BytesRef[result.size()]);
}
-
+
/**
- * Returns an array of bytes for the first (or only) field that has the name
- * specified as the method parameter. This method will return <code>null</code>
- * if no binary fields with the specified name are available.
- * There may be non-binary fields with the same name.
- *
- * @param name the name of the field.
- * @return a <code>BytesRef</code> containing the binary field value or <code>null</code>
- */
+ * Returns an array of bytes for the first (or only) field that has the name specified as the
+ * method parameter. This method will return <code>null</code> if no binary fields with the
+ * specified name are available. There may be non-binary fields with the same name.
+ *
+ * @param name the name of the field.
+ * @return a <code>BytesRef</code> containing the binary field value or <code>null</code>
+ */
public final BytesRef getBinaryValue(String name) {
for (IndexableField field : fields) {
if (field.name().equals(name)) {
@@ -149,9 +142,9 @@ public final class Document implements Iterable<IndexableField> {
return null;
}
- /** Returns a field with the given name if any exist in this document, or
- * null. If multiple fields exists with this name, this method returns the
- * first value added.
+ /**
+ * Returns a field with the given name if any exist in this document, or null. If multiple fields
+ * exists with this name, this method returns the first value added.
*/
public final IndexableField getField(String name) {
for (IndexableField field : fields) {
@@ -163,9 +156,8 @@ public final class Document implements Iterable<IndexableField> {
}
/**
- * Returns an array of {@link IndexableField}s with the given name.
- * This method returns an empty array when there are no
- * matching fields. It never returns null.
+ * Returns an array of {@link IndexableField}s with the given name. This method returns an empty
+ * array when there are no matching fields. It never returns null.
*
* @param name the name of the field
* @return a <code>Field[]</code> array
@@ -180,27 +172,27 @@ public final class Document implements Iterable<IndexableField> {
return result.toArray(new IndexableField[result.size()]);
}
-
- /** Returns a List of all the fields in a document.
- * <p>Note that fields which are <i>not</i> stored are
- * <i>not</i> available in documents retrieved from the
- * index, e.g. {@link IndexSearcher#doc(int)} or {@link
- * IndexReader#document(int)}.
- *
- * @return an immutable <code>List<Field></code>
+
+ /**
+ * Returns a List of all the fields in a document.
+ *
+ * <p>Note that fields which are <i>not</i> stored are <i>not</i> available in documents retrieved
+ * from the index, e.g. {@link IndexSearcher#doc(int)} or {@link IndexReader#document(int)}.
+ *
+ * @return an immutable <code>List<Field></code>
*/
public final List<IndexableField> getFields() {
return Collections.unmodifiableList(fields);
}
-
- private final static String[] NO_STRINGS = new String[0];
+
+ private static final String[] NO_STRINGS = new String[0];
/**
- * Returns an array of values of the field specified as the method parameter.
- * This method returns an empty array when there are no
- * matching fields. It never returns null.
- * For a numeric {@link StoredField} it returns the string value of the number. If you want
- * the actual numeric field instances back, use {@link #getFields}.
+ * Returns an array of values of the field specified as the method parameter. This method returns
+ * an empty array when there are no matching fields. It never returns null. For a numeric {@link
+ * StoredField} it returns the string value of the number. If you want the actual numeric field
+ * instances back, use {@link #getFields}.
+ *
* @param name the name of the field
* @return a <code>String[]</code> of field values
*/
@@ -211,20 +203,20 @@ public final class Document implements Iterable<IndexableField> {
result.add(field.stringValue());
}
}
-
+
if (result.size() == 0) {
return NO_STRINGS;
}
-
+
return result.toArray(new String[result.size()]);
}
- /** Returns the string value of the field with the given name if any exist in
- * this document, or null. If multiple fields exist with this name, this
- * method returns the first value added. If only binary fields with this name
- * exist, returns null.
- * For a numeric {@link StoredField} it returns the string value of the number. If you want
- * the actual numeric field instance back, use {@link #getField}.
+ /**
+ * Returns the string value of the field with the given name if any exist in this document, or
+ * null. If multiple fields exist with this name, this method returns the first value added. If
+ * only binary fields with this name exist, returns null. For a numeric {@link StoredField} it
+ * returns the string value of the number. If you want the actual numeric field instance back, use
+ * {@link #getField}.
*/
public final String get(String name) {
for (IndexableField field : fields) {
@@ -234,7 +226,7 @@ public final class Document implements Iterable<IndexableField> {
}
return null;
}
-
+
/** Prints the fields of a document for human consumption. */
@Override
public final String toString() {
@@ -243,7 +235,7 @@ public final class Document implements Iterable<IndexableField> {
for (int i = 0; i < fields.size(); i++) {
IndexableField field = fields.get(i);
buffer.append(field.toString());
- if (i != fields.size()-1) {
+ if (i != fields.size() - 1) {
buffer.append(" ");
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/DocumentStoredFieldVisitor.java b/lucene/core/src/java/org/apache/lucene/document/DocumentStoredFieldVisitor.java
index 1a9b9e7..39aa5e9 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DocumentStoredFieldVisitor.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DocumentStoredFieldVisitor.java
@@ -20,28 +20,27 @@ import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
-
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.StoredFieldVisitor;
-/** A {@link StoredFieldVisitor} that creates a {@link
- * Document} from stored fields.
- * <p>
- * This visitor supports loading all stored fields, or only specific
- * requested fields provided from a {@link Set}.
- * <p>
- * This is used by {@link IndexReader#document(int)} to load a
- * document.
+/**
+ * A {@link StoredFieldVisitor} that creates a {@link Document} from stored fields.
*
- * @lucene.experimental */
-
+ * <p>This visitor supports loading all stored fields, or only specific requested fields provided
+ * from a {@link Set}.
+ *
+ * <p>This is used by {@link IndexReader#document(int)} to load a document.
+ *
+ * @lucene.experimental
+ */
public class DocumentStoredFieldVisitor extends StoredFieldVisitor {
private final Document doc = new Document();
private final Set<String> fieldsToAdd;
- /**
- * Load only fields named in the provided <code>Set<String></code>.
+ /**
+ * Load only fields named in the provided <code>Set<String></code>.
+ *
* @param fieldsToAdd Set of fields to load, or <code>null</code> (all fields).
*/
public DocumentStoredFieldVisitor(Set<String> fieldsToAdd) {
@@ -51,7 +50,7 @@ public class DocumentStoredFieldVisitor extends StoredFieldVisitor {
/** Load only fields named in the provided fields. */
public DocumentStoredFieldVisitor(String... fields) {
fieldsToAdd = new HashSet<>(fields.length);
- for(String field : fields) {
+ for (String field : fields) {
fieldsToAdd.add(field);
}
}
@@ -72,7 +71,9 @@ public class DocumentStoredFieldVisitor extends StoredFieldVisitor {
ft.setStoreTermVectors(fieldInfo.hasVectors());
ft.setOmitNorms(fieldInfo.omitsNorms());
ft.setIndexOptions(fieldInfo.getIndexOptions());
- doc.add(new StoredField(fieldInfo.name, Objects.requireNonNull(value, "String value should not be null"), ft));
+ doc.add(
+ new StoredField(
+ fieldInfo.name, Objects.requireNonNull(value, "String value should not be null"), ft));
}
@Override
@@ -102,10 +103,10 @@ public class DocumentStoredFieldVisitor extends StoredFieldVisitor {
/**
* Retrieve the visited document.
- * @return {@link Document} populated with stored fields. Note that only
- * the stored information in the field instances is valid,
- * data such as indexing options, term vector options,
- * etc is not set.
+ *
+ * @return {@link Document} populated with stored fields. Note that only the stored information in
+ * the field instances is valid, data such as indexing options, term vector options, etc is
+ * not set.
*/
public Document getDocument() {
return doc;
diff --git a/lucene/core/src/java/org/apache/lucene/document/DoubleDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/DoubleDocValuesField.java
index 3c24ca4..3103c86 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoubleDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoubleDocValuesField.java
@@ -16,22 +16,21 @@
*/
package org.apache.lucene.document;
-
/**
- * Syntactic sugar for encoding doubles as NumericDocValues
- * via {@link Double#doubleToRawLongBits(double)}.
- * <p>
- * Per-document double values can be retrieved via
- * {@link org.apache.lucene.index.LeafReader#getNumericDocValues(String)}.
- * <p>
- * <b>NOTE</b>: In most all cases this will be rather inefficient,
- * requiring eight bytes per document. Consider encoding double
- * values yourself with only as much precision as you require.
+ * Syntactic sugar for encoding doubles as NumericDocValues via {@link
+ * Double#doubleToRawLongBits(double)}.
+ *
+ * <p>Per-document double values can be retrieved via {@link
+ * org.apache.lucene.index.LeafReader#getNumericDocValues(String)}.
+ *
+ * <p><b>NOTE</b>: In most all cases this will be rather inefficient, requiring eight bytes per
+ * document. Consider encoding double values yourself with only as much precision as you require.
*/
public class DoubleDocValuesField extends NumericDocValuesField {
- /**
- * Creates a new DocValues field with the specified 64-bit double value
+ /**
+ * Creates a new DocValues field with the specified 64-bit double value
+ *
* @param name field name
* @param value 64-bit double value
* @throws IllegalArgumentException if the field name is null
@@ -44,7 +43,7 @@ public class DoubleDocValuesField extends NumericDocValuesField {
public void setDoubleValue(double value) {
super.setLongValue(Double.doubleToRawLongBits(value));
}
-
+
@Override
public void setLongValue(long value) {
throw new IllegalArgumentException("cannot change value type from Double to Long");
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 9b8be22..b20638d 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoublePoint.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.util.Arrays;
import java.util.Collection;
-
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.PointInSetQuery;
import org.apache.lucene.search.PointRangeQuery;
@@ -26,29 +25,30 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-/**
- * An indexed {@code double} field for fast range filters. If you also
- * need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * Finding all documents within an N-dimensional shape or 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:
+/**
+ * An indexed {@code double} field for fast range filters. If you also need to store the value, you
+ * should add a separate {@link StoredField} instance.
+ *
+ * <p>Finding all documents within an N-dimensional shape or 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 #newExactQuery(String, double)} for matching an exact 1D point.
* <li>{@link #newSetQuery(String, double...)} for matching a set of 1D values.
* <li>{@link #newRangeQuery(String, double, double)} for matching a 1D range.
- * <li>{@link #newRangeQuery(String, double[], double[])} for matching points/ranges in n-dimensional space.
- * </ul>
+ * <li>{@link #newRangeQuery(String, double[], double[])} for matching points/ranges in
+ * n-dimensional space.
+ * </ul>
+ *
* @see PointValues
*/
public final class DoublePoint extends Field {
/**
- * Return the least double that compares greater than {@code d} consistently
- * with {@link Double#compare}. The only difference with
- * {@link Math#nextUp(double)} is that this method returns {@code +0d} when
- * the argument is {@code -0d}.
+ * Return the least double that compares greater than {@code d} consistently with {@link
+ * Double#compare}. The only difference with {@link Math#nextUp(double)} is that this method
+ * returns {@code +0d} when the argument is {@code -0d}.
*/
public static double nextUp(double d) {
if (Double.doubleToLongBits(d) == 0x8000_0000_0000_0000L) { // -0d
@@ -58,10 +58,9 @@ public final class DoublePoint extends Field {
}
/**
- * Return the greatest double that compares less than {@code d} consistently
- * with {@link Double#compare}. The only difference with
- * {@link Math#nextDown(double)} is that this method returns {@code -0d} when
- * the argument is {@code +0d}.
+ * Return the greatest double that compares less than {@code d} consistently with {@link
+ * Double#compare}. The only difference with {@link Math#nextDown(double)} is that this method
+ * returns {@code -0d} when the argument is {@code +0d}.
*/
public static double nextDown(double d) {
if (Double.doubleToLongBits(d) == 0L) { // +0d
@@ -85,7 +84,14 @@ public final class DoublePoint extends Field {
/** Change the values of this field */
public void setDoubleValues(double... point) {
if (type.pointDimensionCount() != point.length) {
- throw new IllegalArgumentException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot change to (incoming) " + point.length + " dimensions");
+ throw new IllegalArgumentException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot change to (incoming) "
+ + point.length
+ + " dimensions");
}
fieldsData = pack(point);
}
@@ -98,7 +104,12 @@ public final class DoublePoint extends Field {
@Override
public Number numericValue() {
if (type.pointDimensionCount() != 1) {
- throw new IllegalStateException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot convert to a single numeric value");
+ throw new IllegalStateException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot convert to a single numeric value");
}
BytesRef bytes = (BytesRef) fieldsData;
assert bytes.length == Double.BYTES;
@@ -106,7 +117,7 @@ public final class DoublePoint extends Field {
}
/**
- * Pack a double point into a BytesRef
+ * Pack a double point into a BytesRef
*
* @param point double[] value
* @throws IllegalArgumentException is the value is null or of zero length
@@ -119,25 +130,25 @@ public final class DoublePoint extends Field {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
byte[] packed = new byte[point.length * Double.BYTES];
-
- for (int dim = 0; dim < point.length ; dim++) {
+
+ for (int dim = 0; dim < point.length; dim++) {
encodeDimension(point[dim], packed, dim * Double.BYTES);
}
return new BytesRef(packed);
}
- /** Creates a new DoublePoint, indexing the
- * provided N-dimensional double point.
+ /**
+ * Creates a new DoublePoint, indexing the provided N-dimensional double point.
*
- * @param name field name
- * @param point double[] value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point double[] value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public DoublePoint(String name, double... point) {
super(name, pack(point), getType(point.length));
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -157,26 +168,26 @@ public final class DoublePoint extends Field {
result.append('>');
return result.toString();
}
-
+
// public helper methods (e.g. for queries)
-
+
/** Encode single double dimension */
public static void encodeDimension(double value, byte dest[], int offset) {
NumericUtils.longToSortableBytes(NumericUtils.doubleToSortableLong(value), dest, offset);
}
-
+
/** Decode single double dimension */
public static double decodeDimension(byte value[], int offset) {
return NumericUtils.sortableLongToDouble(NumericUtils.sortableBytesToLong(value, offset));
}
-
+
// static methods for generating queries
- /**
+ /**
* Create a query for matching an exact double value.
- * <p>
- * This is for simple one-dimension points, for multidimensional points use
- * {@link #newRangeQuery(String, double[], double[])} instead.
+ *
+ * <p>This is for simple one-dimension points, for multidimensional points use {@link
+ * #newRangeQuery(String, double[], double[])} instead.
*
* @param field field name. must not be {@code null}.
* @param value double value
@@ -186,19 +197,20 @@ public final class DoublePoint extends Field {
public static Query newExactQuery(String field, double value) {
return newRangeQuery(field, value, value);
}
-
- /**
+
+ /**
* Create a range query for double values.
- * <p>
- * This is for simple one-dimension ranges, for multidimensional ranges use
- * {@link #newRangeQuery(String, double[], double[])} instead.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = Double.NEGATIVE_INFINITY} or {@code upperValue = Double.POSITIVE_INFINITY}.
- * <p> Ranges are inclusive. For exclusive ranges, pass {@link #nextUp(double) nextUp(lowerValue)}
+ *
+ * <p>This is for simple one-dimension ranges, for multidimensional ranges use {@link
+ * #newRangeQuery(String, double[], double[])} instead.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = Double.NEGATIVE_INFINITY} or {@code upperValue = Double.POSITIVE_INFINITY}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@link #nextUp(double) nextUp(lowerValue)}
* or {@link #nextUp(double) nextDown(upperValue)}.
- * <p>
- * Range comparisons are consistent with {@link Double#compareTo(Double)}.
+ *
+ * <p>Range comparisons are consistent with {@link Double#compareTo(Double)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive).
@@ -207,29 +219,32 @@ public final class DoublePoint extends Field {
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, double lowerValue, double upperValue) {
- return newRangeQuery(field, new double[] { lowerValue }, new double[] { upperValue });
+ return newRangeQuery(field, new double[] {lowerValue}, new double[] {upperValue});
}
- /**
+ /**
* Create a range query for n-dimensional double values.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue[i] = Double.NEGATIVE_INFINITY} or {@code upperValue[i] = Double.POSITIVE_INFINITY}.
- * <p> Ranges are inclusive. For exclusive ranges, pass {@code Math#nextUp(lowerValue[i])}
- * or {@code Math.nextDown(upperValue[i])}.
- * <p>
- * Range comparisons are consistent with {@link Double#compareTo(Double)}.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue[i] = Double.NEGATIVE_INFINITY} or {@code upperValue[i] =
+ * Double.POSITIVE_INFINITY}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math#nextUp(lowerValue[i])} or
+ * {@code Math.nextDown(upperValue[i])}.
+ *
+ * <p>Range comparisons are consistent with {@link Double#compareTo(Double)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be {@code null}.
* @param upperValue upper portion of the range (inclusive). must not be {@code null}.
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if {@code upperValue} is null,
- * or if {@code lowerValue.length != upperValue.length}
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if
+ * {@code upperValue} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, double[] lowerValue, double[] upperValue) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
- return new PointRangeQuery(field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
+ return new PointRangeQuery(
+ field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
@Override
protected String toString(int dimension, byte[] value) {
return Double.toString(decodeDimension(value, 0));
@@ -238,8 +253,9 @@ public final class DoublePoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -251,22 +267,25 @@ public final class DoublePoint extends Field {
final BytesRef encoded = new BytesRef(new byte[Double.BYTES]);
- return new PointInSetQuery(field, 1, Double.BYTES,
- new PointInSetQuery.Stream() {
+ return new PointInSetQuery(
+ field,
+ 1,
+ Double.BYTES,
+ new PointInSetQuery.Stream() {
- int upto;
+ int upto;
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encodeDimension(sortedValues[upto], encoded.bytes, 0);
- upto++;
- return encoded;
- }
- }
- }) {
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encodeDimension(sortedValues[upto], encoded.bytes, 0);
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
assert value.length == Double.BYTES;
@@ -274,10 +293,11 @@ public final class DoublePoint extends Field {
}
};
}
-
+
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
diff --git a/lucene/core/src/java/org/apache/lucene/document/DoubleRange.java b/lucene/core/src/java/org/apache/lucene/document/DoubleRange.java
index a540943..79aa731 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoubleRange.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoubleRange.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.util.Objects;
-
import org.apache.lucene.document.RangeFieldQuery.QueryType;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
@@ -25,20 +24,25 @@ import org.apache.lucene.util.NumericUtils;
/**
* An indexed Double Range field.
- * <p>
- * This field indexes dimensional ranges defined as min/max pairs. It supports
- * up to a maximum of 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single double range,
- * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a tesseract.
- * <p>
- * Multiple values for the same field in one document is supported, and open ended ranges can be defined using
- * {@code Double.NEGATIVE_INFINITY} and {@code Double.POSITIVE_INFINITY}.
*
- * <p>
- * This field defines the following static factory methods for common search operations over double ranges:
+ * <p>This field indexes dimensional ranges defined as min/max pairs. It supports up to a maximum of
+ * 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single double range,
+ * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a
+ * tesseract.
+ *
+ * <p>Multiple values for the same field in one document is supported, and open ended ranges can be
+ * defined using {@code Double.NEGATIVE_INFINITY} and {@code Double.POSITIVE_INFINITY}.
+ *
+ * <p>This field defines the following static factory methods for common search operations over
+ * double ranges:
+ *
* <ul>
- * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined search range.
- * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search range.
- * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search range.
+ * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined
+ * search range.
+ * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search
+ * range.
+ * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search
+ * range.
* </ul>
*/
public class DoubleRange extends Field {
@@ -65,30 +69,38 @@ public class DoubleRange extends Field {
FieldType ft = new FieldType();
// dimensions is set as 2*dimension size (min/max per dimension)
- ft.setDimensions(dimensions*2, BYTES);
+ ft.setDimensions(dimensions * 2, BYTES);
ft.freeze();
return ft;
}
/**
* Changes the values of the field.
+ *
* @param min array of min values. (accepts {@code Double.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Double.POSITIVE_INFINITY})
* @throws IllegalArgumentException if {@code min} or {@code max} is invalid
*/
public void setRangeValues(double[] min, double[] max) {
checkArgs(min, max);
- if (min.length*2 != type.pointDimensionCount() || max.length*2 != type.pointDimensionCount()) {
- throw new IllegalArgumentException("field (name=" + name + ") uses " + type.pointDimensionCount()/2
- + " dimensions; cannot change to (incoming) " + min.length + " dimensions");
+ if (min.length * 2 != type.pointDimensionCount()
+ || max.length * 2 != type.pointDimensionCount()) {
+ throw new IllegalArgumentException(
+ "field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount() / 2
+ + " dimensions; cannot change to (incoming) "
+ + min.length
+ + " dimensions");
}
final byte[] bytes;
if (fieldsData == null) {
- bytes = new byte[BYTES*2*min.length];
+ bytes = new byte[BYTES * 2 * min.length];
fieldsData = new BytesRef(bytes);
} else {
- bytes = ((BytesRef)fieldsData).bytes;
+ bytes = ((BytesRef) fieldsData).bytes;
}
verifyAndEncode(min, max, bytes);
}
@@ -106,32 +118,32 @@ public class DoubleRange extends Field {
}
}
- /**
- * Encodes the min, max ranges into a byte array
- */
+ /** Encodes the min, max ranges into a byte array */
static byte[] encode(double[] min, double[] max) {
checkArgs(min, max);
- byte[] b = new byte[BYTES*2*min.length];
+ byte[] b = new byte[BYTES * 2 * min.length];
verifyAndEncode(min, max, b);
return b;
}
/**
* encode the ranges into a sortable byte array ({@code Double.NaN} not allowed)
- * <p>
- * example for 4 dimensions (8 bytes per dimension value):
- * minD1 ... minD4 | maxD1 ... maxD4
+ *
+ * <p>example for 4 dimensions (8 bytes per dimension value): minD1 ... minD4 | maxD1 ... maxD4
*/
static void verifyAndEncode(double[] min, double[] max, byte[] bytes) {
- for (int d=0,i=0,j=min.length*BYTES; d<min.length; ++d, i+=BYTES, j+=BYTES) {
+ for (int d = 0, i = 0, j = min.length * BYTES; d < min.length; ++d, i += BYTES, j += BYTES) {
if (Double.isNaN(min[d])) {
- throw new IllegalArgumentException("invalid min value (" + Double.NaN + ")" + " in DoubleRange");
+ throw new IllegalArgumentException(
+ "invalid min value (" + Double.NaN + ")" + " in DoubleRange");
}
if (Double.isNaN(max[d])) {
- throw new IllegalArgumentException("invalid max value (" + Double.NaN + ")" + " in DoubleRange");
+ throw new IllegalArgumentException(
+ "invalid max value (" + Double.NaN + ")" + " in DoubleRange");
}
if (min[d] > max[d]) {
- throw new IllegalArgumentException("min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
+ throw new IllegalArgumentException(
+ "min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
}
encode(min[d], bytes, i);
encode(max[d], bytes, j);
@@ -145,43 +157,47 @@ public class DoubleRange extends Field {
/**
* Get the min value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded min value
*/
public double getMin(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMin(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMin(((BytesRef) fieldsData).bytes, dimension);
}
/**
* Get the max value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded max value
*/
public double getMax(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMax(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMax(((BytesRef) fieldsData).bytes, dimension);
}
/** decodes the min value (for the defined dimension) from the encoded input byte array */
static double decodeMin(byte[] b, int dimension) {
- int offset = dimension*BYTES;
+ int offset = dimension * BYTES;
return NumericUtils.sortableLongToDouble(NumericUtils.sortableBytesToLong(b, offset));
}
/** decodes the max value (for the defined dimension) from the encoded input byte array */
static double decodeMax(byte[] b, int dimension) {
- int offset = b.length/2 + dimension*BYTES;
+ int offset = b.length / 2 + dimension * BYTES;
return NumericUtils.sortableLongToDouble(NumericUtils.sortableBytesToLong(b, offset));
}
/**
* Create a query for matching indexed ranges that intersect the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Double.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Double.POSITIVE_INFINITY})
* @return query for matching intersecting ranges (overlap, within, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newIntersectsQuery(String field, final double[] min, final double[] max) {
return newRelationQuery(field, min, max, QueryType.INTERSECTS);
@@ -189,11 +205,13 @@ public class DoubleRange extends Field {
/**
* Create a query for matching indexed ranges that contain the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Double.MIN_VALUE})
* @param max array of max values. (accepts {@code Double.MAX_VALUE})
* @return query for matching ranges that contain the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newContainsQuery(String field, final double[] min, final double[] max) {
return newRelationQuery(field, min, max, QueryType.CONTAINS);
@@ -201,32 +219,37 @@ public class DoubleRange extends Field {
/**
* Create a query for matching indexed ranges that are within the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Double.MIN_VALUE})
* @param max array of max values. (accepts {@code Double.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newWithinQuery(String field, final double[] min, final double[] max) {
return newRelationQuery(field, min, max, QueryType.WITHIN);
}
/**
- * Create a query for matching indexed ranges that cross the defined range.
- * A CROSSES is defined as any set of ranges that are not disjoint and not wholly contained by
- * the query. Effectively, its the complement of union(WITHIN, DISJOINT).
+ * Create a query for matching indexed ranges that cross the defined range. A CROSSES is defined
+ * as any set of ranges that are not disjoint and not wholly contained by the query. Effectively,
+ * its the complement of union(WITHIN, DISJOINT).
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Double.MIN_VALUE})
* @param max array of max values. (accepts {@code Double.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newCrossesQuery(String field, final double[] min, final double[] max) {
return newRelationQuery(field, min, max, QueryType.CROSSES);
}
/** helper method for creating the desired relational query */
- private static Query newRelationQuery(String field, final double[] min, final double[] max, QueryType relation) {
+ private static Query newRelationQuery(
+ String field, final double[] min, final double[] max, QueryType relation) {
checkArgs(min, max);
return new RangeFieldQuery(field, encode(min, max), min.length, relation) {
@Override
@@ -243,7 +266,7 @@ public class DoubleRange extends Field {
sb.append(" <");
sb.append(name);
sb.append(':');
- byte[] b = ((BytesRef)fieldsData).bytes;
+ byte[] b = ((BytesRef) fieldsData).bytes;
toString(b, 0);
for (int d = 0; d < type.pointDimensionCount() / 2; ++d) {
sb.append(' ');
@@ -256,12 +279,16 @@ public class DoubleRange extends Field {
/**
* Returns the String representation for the range at the given dimension
+ *
* @param ranges the encoded ranges, never null
* @param dimension the dimension of interest
* @return The string representation for the range at the provided dimension
*/
private static String toString(byte[] ranges, int dimension) {
- return "[" + Double.toString(decodeMin(ranges, dimension)) + " : "
- + Double.toString(decodeMax(ranges, dimension)) + "]";
+ return "["
+ + Double.toString(decodeMin(ranges, dimension))
+ + " : "
+ + Double.toString(decodeMax(ranges, dimension))
+ + "]";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/DoubleRangeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/DoubleRangeDocValuesField.java
index 629e33c..08d6bb5 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoubleRangeDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoubleRangeDocValuesField.java
@@ -20,10 +20,10 @@ package org.apache.lucene.document;
import org.apache.lucene.search.Query;
/**
- * DocValues field for DoubleRange. This is a single valued field i.e. can have only one
- * value per document due to being an extension of BinaryDocValuesField.
+ * DocValues field for DoubleRange. This is a single valued field i.e. can have only one value per
+ * document due to being an extension of BinaryDocValuesField.
*/
-public class DoubleRangeDocValuesField extends BinaryRangeDocValuesField{
+public class DoubleRangeDocValuesField extends BinaryRangeDocValuesField {
final String field;
final double[] min;
final double[] max;
@@ -55,22 +55,23 @@ public class DoubleRangeDocValuesField extends BinaryRangeDocValuesField{
return max[dimension];
}
- private static Query newSlowRangeQuery(String field, final double[] min, final double[] max,
- RangeFieldQuery.QueryType queryType) {
+ private static Query newSlowRangeQuery(
+ String field, final double[] min, final double[] max, RangeFieldQuery.QueryType queryType) {
checkArgs(min, max);
return new DoubleRangeSlowRangeQuery(field, min, max, queryType);
}
- /** Create a new range query that finds all ranges that intersect using doc values.
- * NOTE: This doesn't leverage indexing and may be slow.
- * @see DoubleRange#newIntersectsQuery */
+ /**
+ * Create a new range query that finds all ranges that intersect using doc values. NOTE: This
+ * doesn't leverage indexing and may be slow.
+ *
+ * @see DoubleRange#newIntersectsQuery
+ */
public static Query newSlowIntersectsQuery(String field, final double[] min, final double[] max) {
return newSlowRangeQuery(field, min, max, RangeFieldQuery.QueryType.INTERSECTS);
}
- /**
- * validate the arguments
- */
+ /** validate the arguments */
private static void checkArgs(final double[] min, final double[] max) {
if (min == null || max == null || min.length == 0 || max.length == 0) {
throw new IllegalArgumentException("min/max range values cannot be null or empty");
diff --git a/lucene/core/src/java/org/apache/lucene/document/DoubleRangeSlowRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/DoubleRangeSlowRangeQuery.java
index 5f506e2..6406b1b 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DoubleRangeSlowRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DoubleRangeSlowRangeQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryVisitor;
@@ -30,9 +29,9 @@ class DoubleRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
private final double[] min;
private final double[] max;
- DoubleRangeSlowRangeQuery(String field, double[] min, double[] max, RangeFieldQuery.QueryType queryType) {
- super(field, encodeRanges(min, max), DoubleRange.BYTES, min.length,
- queryType);
+ DoubleRangeSlowRangeQuery(
+ String field, double[] min, double[] max, RangeFieldQuery.QueryType queryType) {
+ super(field, encodeRanges(min, max), DoubleRange.BYTES, min.length, queryType);
this.field = field;
this.min = min;
this.max = max;
@@ -71,8 +70,7 @@ class DoubleRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
if (this.field.equals(field) == false) {
b.append(this.field).append(":");
}
- return b
- .append("[")
+ return b.append("[")
.append(Arrays.toString(min))
.append(" TO ")
.append(Arrays.toString(max))
diff --git a/lucene/core/src/java/org/apache/lucene/document/FeatureDoubleValuesSource.java b/lucene/core/src/java/org/apache/lucene/document/FeatureDoubleValuesSource.java
index 41af9f8..452577a 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FeatureDoubleValuesSource.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FeatureDoubleValuesSource.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Objects;
-
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
@@ -29,18 +28,18 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.util.BytesRef;
/**
- * A {@link DoubleValuesSource} instance which can be used to read the values of a feature from a
+ * A {@link DoubleValuesSource} instance which can be used to read the values of a feature from a
* {@link FeatureField} for documents.
*/
class FeatureDoubleValuesSource extends DoubleValuesSource {
-
+
private final BytesRef featureName;
private final String field;
/**
- * Creates a {@link DoubleValuesSource} instance which can be used to read the values of a feature from the a
- * {@link FeatureField} for documents.
- *
+ * Creates a {@link DoubleValuesSource} instance which can be used to read the values of a feature
+ * from the a {@link FeatureField} for documents.
+ *
* @param field field name. Must not be null.
* @param featureName feature name. Must not be null.
* @throws NullPointerException if {@code field} or {@code featureName} is null.
@@ -95,17 +94,16 @@ class FeatureDoubleValuesSource extends DoubleValuesSource {
return false;
}
FeatureDoubleValuesSource other = (FeatureDoubleValuesSource) obj;
- return Objects.equals(field, other.field) &&
- Objects.equals(featureName, other.featureName);
+ return Objects.equals(field, other.field) && Objects.equals(featureName, other.featureName);
}
@Override
public String toString() {
- return "FeatureDoubleValuesSource("+field+", "+featureName.utf8ToString()+")";
+ return "FeatureDoubleValuesSource(" + field + ", " + featureName.utf8ToString() + ")";
}
-
+
static class FeatureDoubleValues extends DoubleValues {
-
+
private final PostingsEnum currentReaderPostingsValues;
public FeatureDoubleValues(PostingsEnum currentReaderPostingsValues) throws IOException {
@@ -120,13 +118,12 @@ class FeatureDoubleValuesSource extends DoubleValuesSource {
@Override
public boolean advanceExact(int doc) throws IOException {
if (doc >= currentReaderPostingsValues.docID()
- && (currentReaderPostingsValues.docID() == doc || currentReaderPostingsValues.advance(doc) == doc)) {
+ && (currentReaderPostingsValues.docID() == doc
+ || currentReaderPostingsValues.advance(doc) == doc)) {
return true;
} else {
return false;
}
}
-
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/FeatureField.java b/lucene/core/src/java/org/apache/lucene/document/FeatureField.java
index dafcbf4..22e6d9d 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FeatureField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FeatureField.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Objects;
-
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
@@ -38,66 +37,56 @@ import org.apache.lucene.search.similarities.BM25Similarity;
import org.apache.lucene.search.similarities.Similarity.SimScorer;
/**
- * {@link Field} that can be used to store static scoring factors into
- * documents. This is mostly inspired from the work from Nick Craswell,
- * Stephen Robertson, Hugo Zaragoza and Michael Taylor. Relevance weighting
- * for query independent evidence. Proceedings of the 28th annual international
- * ACM SIGIR conference on Research and development in information retrieval.
- * August 15-19, 2005, Salvador, Brazil.
- * <p>
- * Feature values are internally encoded as term frequencies. Putting
- * feature queries as
- * {@link org.apache.lucene.search.BooleanClause.Occur#SHOULD} clauses of a
- * {@link BooleanQuery} allows to combine query-dependent scores (eg. BM25)
- * with query-independent scores using a linear combination. The fact that
- * feature values are stored as frequencies also allows search logic to
- * efficiently skip documents that can't be competitive when total hit counts
- * are not requested. This makes it a compelling option compared to storing
- * such factors eg. in a doc-value field.
- * <p>
- * This field may only store factors that are positively correlated with the
- * final score, like pagerank. In case of factors that are inversely correlated
- * with the score like url length, the inverse of the scoring factor should be
- * stored, ie. {@code 1/urlLength}.
- * <p>
- * This field only considers the top 9 significant bits for storage efficiency
- * which allows to store them on 16 bits internally. In practice this limitation
- * means that values are stored with a relative precision of
- * 2<sup>-8</sup> = 0.00390625.
- * <p>
- * Given a scoring factor {@code S > 0} and its weight {@code w > 0}, there
- * are four ways that S can be turned into a score:
+ * {@link Field} that can be used to store static scoring factors into documents. This is mostly
+ * inspired from the work from Nick Craswell, Stephen Robertson, Hugo Zaragoza and Michael Taylor.
+ * Relevance weighting for query independent evidence. Proceedings of the 28th annual international
+ * ACM SIGIR conference on Research and development in information retrieval. August 15-19, 2005,
+ * Salvador, Brazil.
+ *
+ * <p>Feature values are internally encoded as term frequencies. Putting feature queries as {@link
+ * org.apache.lucene.search.BooleanClause.Occur#SHOULD} clauses of a {@link BooleanQuery} allows to
+ * combine query-dependent scores (eg. BM25) with query-independent scores using a linear
+ * combination. The fact that feature values are stored as frequencies also allows search logic to
+ * efficiently skip documents that can't be competitive when total hit counts are not requested.
+ * This makes it a compelling option compared to storing such factors eg. in a doc-value field.
+ *
+ * <p>This field may only store factors that are positively correlated with the final score, like
+ * pagerank. In case of factors that are inversely correlated with the score like url length, the
+ * inverse of the scoring factor should be stored, ie. {@code 1/urlLength}.
+ *
+ * <p>This field only considers the top 9 significant bits for storage efficiency which allows to
+ * store them on 16 bits internally. In practice this limitation means that values are stored with a
+ * relative precision of 2<sup>-8</sup> = 0.00390625.
+ *
+ * <p>Given a scoring factor {@code S > 0} and its weight {@code w > 0}, there are four ways that S
+ * can be turned into a score:
+ *
* <ul>
- * <li>{@link #newLogQuery w * log(a + S)}, with a ≥ 1. This function
- * usually makes sense because the distribution of scoring factors
- * often follows a power law. This is typically the case for pagerank for
- * instance. However the paper suggested that the {@code satu} and
+ * <li>{@link #newLogQuery w * log(a + S)}, with a ≥ 1. This function usually makes sense
+ * because the distribution of scoring factors often follows a power law. This is typically
+ * the case for pagerank for instance. However the paper suggested that the {@code satu} and
* {@code sigm} functions give even better results.
- * <li>{@link #newSaturationQuery satu(S) = w * S / (S + k)}, with k > 0. This
- * function is similar to the one used by {@link BM25Similarity} in order
- * to incorporate term frequency into the final score and produces values
- * between 0 and 1. A value of 0.5 is obtained when S and k are equal.
+ * <li>{@link #newSaturationQuery satu(S) = w * S / (S + k)}, with k > 0. This function is
+ * similar to the one used by {@link BM25Similarity} in order to incorporate term frequency
+ * into the final score and produces values between 0 and 1. A value of 0.5 is obtained when S
+ * and k are equal.
* <li>{@link #newSigmoidQuery sigm(S) = w * S<sup>a</sup> / (S<sup>a</sup> + k<sup>a</sup>)},
- * with k > 0, a > 0. This function provided even better results
- * than the two above but is also harder to tune due to the fact it has
- * 2 parameters. Like with {@code satu}, values are in the 0..1 range and
- * 0.5 is obtained when S and k are equal.
- * <li>{@link #newLinearQuery w * S}. Expert: This function doesn't apply
- * any transformation to an indexed feature value, and the indexed value itself,
- * multiplied by weight, determines the score. Thus, there is an expectation
- * that a feature value is encoded in the index in a way that makes
- * sense for scoring.
- *
+ * with k > 0, a > 0. This function provided even better results than the two above but
+ * is also harder to tune due to the fact it has 2 parameters. Like with {@code satu}, values
+ * are in the 0..1 range and 0.5 is obtained when S and k are equal.
+ * <li>{@link #newLinearQuery w * S}. Expert: This function doesn't apply any transformation to an
+ * indexed feature value, and the indexed value itself, multiplied by weight, determines the
+ * score. Thus, there is an expectation that a feature value is encoded in the index in a way
+ * that makes sense for scoring.
* </ul>
- * <p>
- * The constants in the above formulas typically need training in order to
- * compute optimal values. If you don't know where to start, the
- * {@link #newSaturationQuery(String, String)} method uses
- * {@code 1f} as a weight and tries to guess a sensible value for the
- * {@code pivot} parameter of the saturation function based on index
- * statistics, which shouldn't perform too bad. Here is an example, assuming
- * that documents have a {@link FeatureField} called 'features' with values for
+ *
+ * <p>The constants in the above formulas typically need training in order to compute optimal
+ * values. If you don't know where to start, the {@link #newSaturationQuery(String, String)} method
+ * uses {@code 1f} as a weight and tries to guess a sensible value for the {@code pivot} parameter
+ * of the saturation function based on index statistics, which shouldn't perform too bad. Here is an
+ * example, assuming that documents have a {@link FeatureField} called 'features' with values for
* the 'pagerank' feature.
+ *
* <pre class="prettyprint">
* Query query = new BooleanQuery.Builder()
* .add(new TermQuery(new Term("body", "apache")), Occur.SHOULD)
@@ -110,11 +99,13 @@ import org.apache.lucene.search.similarities.Similarity.SimScorer;
* .build();
* TopDocs topDocs = searcher.search(boostedQuery, 10);
* </pre>
+ *
* @lucene.experimental
*/
public final class FeatureField extends Field {
private static final FieldType FIELD_TYPE = new FieldType();
+
static {
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setOmitNorms(true);
@@ -125,7 +116,9 @@ public final class FeatureField extends Field {
/**
* Create a feature.
- * @param fieldName The name of the field to store the information into. All features may be stored in the same field.
+ *
+ * @param fieldName The name of the field to store the information into. All features may be
+ * stored in the same field.
* @param featureName The name of the feature, eg. 'pagerank`. It will be indexed as a term.
* @param featureValue The value of the feature, must be a positive, finite, normal float.
*/
@@ -134,18 +127,27 @@ public final class FeatureField extends Field {
setFeatureValue(featureValue);
}
- /**
- * Update the feature value of this field.
- */
+ /** Update the feature value of this field. */
public void setFeatureValue(float featureValue) {
if (Float.isFinite(featureValue) == false) {
- throw new IllegalArgumentException("featureValue must be finite, got: " + featureValue +
- " for feature " + fieldsData + " on field " + name);
+ throw new IllegalArgumentException(
+ "featureValue must be finite, got: "
+ + featureValue
+ + " for feature "
+ + fieldsData
+ + " on field "
+ + name);
}
if (featureValue < Float.MIN_NORMAL) {
- throw new IllegalArgumentException("featureValue must be a positive normal float, got: " +
- featureValue + " for feature " + fieldsData + " on field " + name +
- " which is less than the minimum positive normal float: " + Float.MIN_NORMAL);
+ throw new IllegalArgumentException(
+ "featureValue must be a positive normal float, got: "
+ + featureValue
+ + " for feature "
+ + fieldsData
+ + " on field "
+ + name
+ + " which is less than the minimum positive normal float: "
+ + Float.MIN_NORMAL);
}
this.featureValue = featureValue;
}
@@ -171,8 +173,7 @@ public final class FeatureField extends Field {
private String value = null;
private int freq = 0;
- private FeatureTokenStream() {
- }
+ private FeatureTokenStream() {}
/** Sets the values */
void setValues(String value, int freq) {
@@ -217,10 +218,14 @@ public final class FeatureField extends Field {
return Float.intBitsToFloat(featureBits);
}
- static abstract class FeatureFunction {
+ abstract static class FeatureFunction {
abstract SimScorer scorer(float w);
+
abstract Explanation explain(String field, String feature, float w, int freq);
- FeatureFunction rewrite(IndexReader reader) throws IOException { return this; }
+
+ FeatureFunction rewrite(IndexReader reader) throws IOException {
+ return this;
+ }
}
static final class LinearFunction extends FeatureFunction {
@@ -238,8 +243,13 @@ public final class FeatureField extends Field {
Explanation explain(String field, String feature, float w, int freq) {
float featureValue = decodeFeatureValue(freq);
float score = scorer(w).score(freq, 1L);
- return Explanation.match(score,
- "Linear function on the " + field + " field for the " + feature + " feature, computed as w * S from:",
+ return Explanation.match(
+ score,
+ "Linear function on the "
+ + field
+ + " field for the "
+ + feature
+ + " feature, computed as w * S from:",
Explanation.match(w, "w, weight of this function"),
Explanation.match(featureValue, "S, feature value"));
}
@@ -261,7 +271,8 @@ public final class FeatureField extends Field {
}
return true;
}
- };
+ }
+ ;
static final class LogFunction extends FeatureFunction {
@@ -304,8 +315,13 @@ public final class FeatureField extends Field {
Explanation explain(String field, String feature, float w, int freq) {
float featureValue = decodeFeatureValue(freq);
float score = scorer(w).score(freq, 1L);
- return Explanation.match(score,
- "Log function on the " + field + " field for the " + feature + " feature, computed as w * log(a + S) from:",
+ return Explanation.match(
+ score,
+ "Log function on the "
+ + field
+ + " field for the "
+ + feature
+ + " feature, computed as w * log(a + S) from:",
Explanation.match(w, "w, weight of this function"),
Explanation.match(scalingFactor, "a, scaling factor"),
Explanation.match(featureValue, "S, feature value"));
@@ -338,9 +354,9 @@ public final class FeatureField extends Field {
return false;
}
SaturationFunction that = (SaturationFunction) obj;
- return Objects.equals(field, that.field) &&
- Objects.equals(feature, that.feature) &&
- Objects.equals(pivot, that.pivot);
+ return Objects.equals(field, that.field)
+ && Objects.equals(feature, that.feature)
+ && Objects.equals(pivot, that.pivot);
}
@Override
@@ -375,10 +391,16 @@ public final class FeatureField extends Field {
Explanation explain(String field, String feature, float weight, int freq) {
float featureValue = decodeFeatureValue(freq);
float score = scorer(weight).score(freq, 1L);
- return Explanation.match(score,
- "Saturation function on the " + field + " field for the " + feature + " feature, computed as w * S / (S + k) from:",
+ return Explanation.match(
+ score,
+ "Saturation function on the "
+ + field
+ + " field for the "
+ + feature
+ + " feature, computed as w * S / (S + k) from:",
Explanation.match(weight, "w, weight of this function"),
- Explanation.match(pivot, "k, pivot feature value that would give a score contribution equal to w/2"),
+ Explanation.match(
+ pivot, "k, pivot feature value that would give a score contribution equal to w/2"),
Explanation.match(featureValue, "S, feature value"));
}
}
@@ -400,8 +422,7 @@ public final class FeatureField extends Field {
return false;
}
SigmoidFunction that = (SigmoidFunction) obj;
- return pivot == that.pivot
- && a == that.a;
+ return pivot == that.pivot && a == that.a;
}
@Override
@@ -434,36 +455,44 @@ public final class FeatureField extends Field {
Explanation explain(String field, String feature, float weight, int freq) {
float featureValue = decodeFeatureValue(freq);
float score = scorer(weight).score(freq, 1L);
- return Explanation.match(score,
- "Sigmoid function on the " + field + " field for the " + feature + " feature, computed as w * S^a / (S^a + k^a) from:",
+ return Explanation.match(
+ score,
+ "Sigmoid function on the "
+ + field
+ + " field for the "
+ + feature
+ + " feature, computed as w * S^a / (S^a + k^a) from:",
Explanation.match(weight, "w, weight of this function"),
- Explanation.match(pivot, "k, pivot feature value that would give a score contribution equal to w/2"),
- Explanation.match(pivot, "a, exponent, higher values make the function grow slower before k and faster after k"),
+ Explanation.match(
+ pivot, "k, pivot feature value that would give a score contribution equal to w/2"),
+ Explanation.match(
+ pivot,
+ "a, exponent, higher values make the function grow slower before k and faster after k"),
Explanation.match(featureValue, "S, feature value"));
}
}
/**
- * Given that IDFs are logs, similarities that incorporate term freq and
- * document length in sane (ie. saturated) ways should have their score
- * bounded by a log. So we reject weights that are too high as it would mean
- * that this clause would completely dominate ranking, removing the need for
- * query-dependent scores.
+ * Given that IDFs are logs, similarities that incorporate term freq and document length in sane
+ * (ie. saturated) ways should have their score bounded by a log. So we reject weights that are
+ * too high as it would mean that this clause would completely dominate ranking, removing the need
+ * for query-dependent scores.
*/
private static final float MAX_WEIGHT = Long.SIZE;
-
/**
- * Return a new {@link Query} that will score documents as
- * {@code weight * S} where S is the value of the static feature.
- * @param fieldName field that stores features
- * @param featureName name of the feature
- * @param weight weight to give to this feature, must be in (0,64]
+ * Return a new {@link Query} that will score documents as {@code weight * S} where S is the value
+ * of the static feature.
+ *
+ * @param fieldName field that stores features
+ * @param featureName name of the feature
+ * @param weight weight to give to this feature, must be in (0,64]
* @throws IllegalArgumentException if weight is not in (0,64]
*/
public static Query newLinearQuery(String fieldName, String featureName, float weight) {
if (weight <= 0 || weight > MAX_WEIGHT) {
- throw new IllegalArgumentException("weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
+ throw new IllegalArgumentException(
+ "weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
}
Query q = new FeatureQuery(fieldName, featureName, new LinearFunction());
if (weight != 1f) {
@@ -473,17 +502,22 @@ public final class FeatureField extends Field {
}
/**
- * Return a new {@link Query} that will score documents as
- * {@code weight * Math.log(scalingFactor + S)} where S is the value of the static feature.
- * @param fieldName field that stores features
- * @param featureName name of the feature
- * @param weight weight to give to this feature, must be in (0,64]
- * @param scalingFactor scaling factor applied before taking the logarithm, must be in [1, +Infinity)
- * @throws IllegalArgumentException if weight is not in (0,64] or scalingFactor is not in [1, +Infinity)
+ * Return a new {@link Query} that will score documents as {@code weight * Math.log(scalingFactor
+ * + S)} where S is the value of the static feature.
+ *
+ * @param fieldName field that stores features
+ * @param featureName name of the feature
+ * @param weight weight to give to this feature, must be in (0,64]
+ * @param scalingFactor scaling factor applied before taking the logarithm, must be in [1,
+ * +Infinity)
+ * @throws IllegalArgumentException if weight is not in (0,64] or scalingFactor is not in [1,
+ * +Infinity)
*/
- public static Query newLogQuery(String fieldName, String featureName, float weight, float scalingFactor) {
+ public static Query newLogQuery(
+ String fieldName, String featureName, float weight, float scalingFactor) {
if (weight <= 0 || weight > MAX_WEIGHT) {
- throw new IllegalArgumentException("weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
+ throw new IllegalArgumentException(
+ "weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
}
if (scalingFactor < 1 || Float.isFinite(scalingFactor) == false) {
throw new IllegalArgumentException("scalingFactor must be >= 1, got: " + scalingFactor);
@@ -496,24 +530,27 @@ public final class FeatureField extends Field {
}
/**
- * Return a new {@link Query} that will score documents as
- * {@code weight * S / (S + pivot)} where S is the value of the static feature.
- * @param fieldName field that stores features
+ * Return a new {@link Query} that will score documents as {@code weight * S / (S + pivot)} where
+ * S is the value of the static feature.
+ *
+ * @param fieldName field that stores features
* @param featureName name of the feature
- * @param weight weight to give to this feature, must be in (0,64]
- * @param pivot feature value that would give a score contribution equal to weight/2, must be in (0, +Infinity)
+ * @param weight weight to give to this feature, must be in (0,64]
+ * @param pivot feature value that would give a score contribution equal to weight/2, must be in
+ * (0, +Infinity)
* @throws IllegalArgumentException if weight is not in (0,64] or pivot is not in (0, +Infinity)
*/
- public static Query newSaturationQuery(String fieldName, String featureName, float weight, float pivot) {
+ public static Query newSaturationQuery(
+ String fieldName, String featureName, float weight, float pivot) {
return newSaturationQuery(fieldName, featureName, weight, Float.valueOf(pivot));
}
/**
- * Same as {@link #newSaturationQuery(String, String, float, float)} but
- * {@code 1f} is used as a weight and a reasonably good default pivot value
- * is computed based on index statistics and is approximately equal to the
- * geometric mean of all values that exist in the index.
- * @param fieldName field that stores features
+ * Same as {@link #newSaturationQuery(String, String, float, float)} but {@code 1f} is used as a
+ * weight and a reasonably good default pivot value is computed based on index statistics and is
+ * approximately equal to the geometric mean of all values that exist in the index.
+ *
+ * @param fieldName field that stores features
* @param featureName name of the feature
* @throws IllegalArgumentException if weight is not in (0,64] or pivot is not in (0, +Infinity)
*/
@@ -521,14 +558,18 @@ public final class FeatureField extends Field {
return newSaturationQuery(fieldName, featureName, 1f, null);
}
- private static Query newSaturationQuery(String fieldName, String featureName, float weight, Float pivot) {
+ private static Query newSaturationQuery(
+ String fieldName, String featureName, float weight, Float pivot) {
if (weight <= 0 || weight > MAX_WEIGHT) {
- throw new IllegalArgumentException("weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
+ throw new IllegalArgumentException(
+ "weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
}
if (pivot != null && (pivot <= 0 || Float.isFinite(pivot) == false)) {
throw new IllegalArgumentException("pivot must be > 0, got: " + pivot);
}
- Query q = new FeatureQuery(fieldName, featureName, new SaturationFunction(fieldName, featureName, pivot));
+ Query q =
+ new FeatureQuery(
+ fieldName, featureName, new SaturationFunction(fieldName, featureName, pivot));
if (weight != 1f) {
q = new BoostQuery(q, weight);
}
@@ -536,18 +577,24 @@ public final class FeatureField extends Field {
}
/**
- * Return a new {@link Query} that will score documents as
- * {@code weight * S^a / (S^a + pivot^a)} where S is the value of the static feature.
- * @param fieldName field that stores features
+ * Return a new {@link Query} that will score documents as {@code weight * S^a / (S^a + pivot^a)}
+ * where S is the value of the static feature.
+ *
+ * @param fieldName field that stores features
* @param featureName name of the feature
- * @param weight weight to give to this feature, must be in (0,64]
- * @param pivot feature value that would give a score contribution equal to weight/2, must be in (0, +Infinity)
- * @param exp exponent, higher values make the function grow slower before 'pivot' and faster after 'pivot', must be in (0, +Infinity)
- * @throws IllegalArgumentException if w is not in (0,64] or either k or a are not in (0, +Infinity)
+ * @param weight weight to give to this feature, must be in (0,64]
+ * @param pivot feature value that would give a score contribution equal to weight/2, must be in
+ * (0, +Infinity)
+ * @param exp exponent, higher values make the function grow slower before 'pivot' and faster
+ * after 'pivot', must be in (0, +Infinity)
+ * @throws IllegalArgumentException if w is not in (0,64] or either k or a are not in (0,
+ * +Infinity)
*/
- public static Query newSigmoidQuery(String fieldName, String featureName, float weight, float pivot, float exp) {
+ public static Query newSigmoidQuery(
+ String fieldName, String featureName, float weight, float pivot, float exp) {
if (weight <= 0 || weight > MAX_WEIGHT) {
- throw new IllegalArgumentException("weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
+ throw new IllegalArgumentException(
+ "weight must be in (0, " + MAX_WEIGHT + "], got: " + weight);
}
if (pivot <= 0 || Float.isFinite(pivot) == false) {
throw new IllegalArgumentException("pivot must be > 0, got: " + pivot);
@@ -563,18 +610,19 @@ public final class FeatureField extends Field {
}
/**
- * Compute a feature value that may be used as the {@code pivot} parameter of
- * the {@link #newSaturationQuery(String, String, float, float)} and
- * {@link #newSigmoidQuery(String, String, float, float, float)} factory
- * methods. The implementation takes the average of the int bits of the float
- * representation in practice before converting it back to a float. Given that
- * floats store the exponent in the higher bits, it means that the result will
- * be an approximation of the geometric mean of all feature values.
- * @param reader the {@link IndexReader} to search against
+ * Compute a feature value that may be used as the {@code pivot} parameter of the {@link
+ * #newSaturationQuery(String, String, float, float)} and {@link #newSigmoidQuery(String, String,
+ * float, float, float)} factory methods. The implementation takes the average of the int bits of
+ * the float representation in practice before converting it back to a float. Given that floats
+ * store the exponent in the higher bits, it means that the result will be an approximation of the
+ * geometric mean of all feature values.
+ *
+ * @param reader the {@link IndexReader} to search against
* @param featureField the field that stores features
- * @param featureName the name of the feature
+ * @param featureName the name of the feature
*/
- static float computePivotFeatureValue(IndexReader reader, String featureField, String featureName) throws IOException {
+ static float computePivotFeatureValue(IndexReader reader, String featureField, String featureName)
+ throws IOException {
Term term = new Term(featureField, featureName);
TermStates states = TermStates.build(reader.getContext(), term, true);
if (states.docFreq() == 0) {
@@ -590,13 +638,15 @@ public final class FeatureField extends Field {
/**
* Creates a SortField for sorting by the value of a feature.
+ *
+ * <p>This sort orders documents by descending value of a feature. The value returned in {@link
+ * FieldDoc} for the hits contains a Float instance with the feature value.
+ *
+ * <p>If a document is missing the field, then it is treated as having a vaue of <code>0.0f</code>
+ * .
+ *
* <p>
- * This sort orders documents by descending value of a feature. The value returned in {@link FieldDoc} for
- * the hits contains a Float instance with the feature value.
- * <p>
- * If a document is missing the field, then it is treated as having a vaue of <code>0.0f</code>.
- * <p>
- *
+ *
* @param field field name. Must not be null.
* @param featureName feature name. Must not be null.
* @return SortField ordering documents by the value of the feature
@@ -605,14 +655,15 @@ public final class FeatureField extends Field {
public static SortField newFeatureSort(String field, String featureName) {
return new FeatureSortField(field, featureName);
}
-
+
/**
- * Creates a {@link DoubleValuesSource} instance which can be used to read the values of a feature from the a
- * {@link FeatureField} for documents.
- *
+ * Creates a {@link DoubleValuesSource} instance which can be used to read the values of a feature
+ * from the a {@link FeatureField} for documents.
+ *
* @param field field name. Must not be null.
* @param featureName feature name. Must not be null.
- * @return a {@link DoubleValuesSource} which can be used to access the values of the feature for documents
+ * @return a {@link DoubleValuesSource} which can be used to access the values of the feature for
+ * documents
* @throws NullPointerException if {@code field} or {@code featureName} is null.
*/
public static DoubleValuesSource newDoubleValues(String field, String featureName) {
diff --git a/lucene/core/src/java/org/apache/lucene/document/FeatureQuery.java b/lucene/core/src/java/org/apache/lucene/document/FeatureQuery.java
index bc69344..bdd00ef 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FeatureQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FeatureQuery.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Objects;
-
import org.apache.lucene.document.FeatureField.FeatureFunction;
import org.apache.lucene.index.ImpactsEnum;
import org.apache.lucene.index.IndexReader;
@@ -65,9 +64,9 @@ final class FeatureQuery extends Query {
return false;
}
FeatureQuery that = (FeatureQuery) obj;
- return Objects.equals(fieldName, that.fieldName) &&
- Objects.equals(featureName, that.featureName) &&
- Objects.equals(function, that.function);
+ return Objects.equals(fieldName, that.fieldName)
+ && Objects.equals(featureName, that.featureName)
+ && Objects.equals(function, that.function);
}
@Override
@@ -80,7 +79,8 @@ final class FeatureQuery extends Query {
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
return new Weight(this) {
@Override
@@ -157,7 +157,6 @@ final class FeatureQuery extends Query {
}
};
}
-
};
}
@@ -170,7 +169,12 @@ final class FeatureQuery extends Query {
@Override
public String toString(String field) {
- return "FeatureQuery(field=" + fieldName + ", feature=" + featureName + ", function=" + function + ")";
+ return "FeatureQuery(field="
+ + fieldName
+ + ", feature="
+ + featureName
+ + ", function="
+ + function
+ + ")";
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/FeatureSortField.java b/lucene/core/src/java/org/apache/lucene/document/FeatureSortField.java
index 1e73f8c..f06ead5 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FeatureSortField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FeatureSortField.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Objects;
-
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
@@ -28,16 +27,14 @@ import org.apache.lucene.search.SimpleFieldComparator;
import org.apache.lucene.search.SortField;
import org.apache.lucene.util.BytesRef;
-/**
- * Sorts using the value of a specified feature name from a {@link FeatureField}.
- */
+/** Sorts using the value of a specified feature name from a {@link FeatureField}. */
final class FeatureSortField extends SortField {
private final String featureName;
/**
- * Creates a {@link FeatureSortField} that can be used to sort hits by
- * the value of a particular feature in a {@link FeatureField}.
+ * Creates a {@link FeatureSortField} that can be used to sort hits by the value of a particular
+ * feature in a {@link FeatureField}.
*
* @param featureName The name of the feature to use for the sort value
*/
@@ -45,17 +42,17 @@ final class FeatureSortField extends SortField {
super(Objects.requireNonNull(field), SortField.Type.CUSTOM, true);
this.featureName = Objects.requireNonNull(featureName);
}
-
+
@Override
public FieldComparator<?> getComparator(int numHits, int sortPos) {
return new FeatureComparator(numHits, getField(), featureName);
}
-
+
@Override
public void setMissingValue(Object missingValue) {
throw new IllegalArgumentException("Missing value not supported for FeatureSortField");
}
-
+
@Override
public int hashCode() {
final int prime = 31;
@@ -112,14 +109,17 @@ final class FeatureSortField extends SortField {
if (termsEnum.seekExact(featureName) == false) {
currentReaderPostingsValues = null;
} else {
- currentReaderPostingsValues = termsEnum.postings(currentReaderPostingsValues, PostingsEnum.FREQS);
+ currentReaderPostingsValues =
+ termsEnum.postings(currentReaderPostingsValues, PostingsEnum.FREQS);
}
}
}
private float getValueForDoc(int doc) throws IOException {
- if (currentReaderPostingsValues != null && doc >= currentReaderPostingsValues.docID()
- && (currentReaderPostingsValues.docID() == doc || currentReaderPostingsValues.advance(doc) == doc)) {
+ if (currentReaderPostingsValues != null
+ && doc >= currentReaderPostingsValues.docID()
+ && (currentReaderPostingsValues.docID() == doc
+ || currentReaderPostingsValues.advance(doc) == doc)) {
return FeatureField.decodeFeatureValue(currentReaderPostingsValues.freq());
} else {
return 0.0f;
diff --git a/lucene/core/src/java/org/apache/lucene/document/Field.java b/lucene/core/src/java/org/apache/lucene/document/Field.java
index 2f0f13b..ef66bef 100644
--- a/lucene/core/src/java/org/apache/lucene/document/Field.java
+++ b/lucene/core/src/java/org/apache/lucene/document/Field.java
@@ -16,10 +16,8 @@
*/
package org.apache.lucene.document;
-
import java.io.IOException;
import java.io.Reader;
-
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.BytesTermAttribute;
@@ -31,62 +29,57 @@ import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.util.BytesRef;
/**
- * Expert: directly create a field for a document. Most
- * users should use one of the sugar subclasses:
+ * Expert: directly create a field for a document. Most users should use one of the sugar
+ * subclasses:
+ *
* <ul>
- * <li>{@link TextField}: {@link Reader} or {@link String} indexed for full-text search
- * <li>{@link StringField}: {@link String} indexed verbatim as a single token
- * <li>{@link IntPoint}: {@code int} indexed for exact/range queries.
- * <li>{@link LongPoint}: {@code long} indexed for exact/range queries.
- * <li>{@link FloatPoint}: {@code float} indexed for exact/range queries.
- * <li>{@link DoublePoint}: {@code double} indexed for exact/range queries.
- * <li>{@link SortedDocValuesField}: {@code byte[]} indexed column-wise for sorting/faceting
- * <li>{@link SortedSetDocValuesField}: {@code SortedSet<byte[]>} indexed column-wise for sorting/faceting
- * <li>{@link NumericDocValuesField}: {@code long} indexed column-wise for sorting/faceting
- * <li>{@link SortedNumericDocValuesField}: {@code SortedSet<long>} indexed column-wise for sorting/faceting
- * <li>{@link StoredField}: Stored-only value for retrieving in summary results
+ * <li>{@link TextField}: {@link Reader} or {@link String} indexed for full-text search
+ * <li>{@link StringField}: {@link String} indexed verbatim as a single token
+ * <li>{@link IntPoint}: {@code int} indexed for exact/range queries.
+ * <li>{@link LongPoint}: {@code long} indexed for exact/range queries.
+ * <li>{@link FloatPoint}: {@code float} indexed for exact/range queries.
+ * <li>{@link DoublePoint}: {@code double} indexed for exact/range queries.
+ * <li>{@link SortedDocValuesField}: {@code byte[]} indexed column-wise for sorting/faceting
+ * <li>{@link SortedSetDocValuesField}: {@code SortedSet<byte[]>} indexed column-wise for
+ * sorting/faceting
+ * <li>{@link NumericDocValuesField}: {@code long} indexed column-wise for sorting/faceting
+ * <li>{@link SortedNumericDocValuesField}: {@code SortedSet<long>} indexed column-wise for
+ * sorting/faceting
+ * <li>{@link StoredField}: Stored-only value for retrieving in summary results
* </ul>
*
- * <p> A field is a section of a Document. Each field has three
- * parts: name, type and value. Values may be text
- * (String, Reader or pre-analyzed TokenStream), binary
- * (byte[]), or numeric (a Number). Fields are optionally stored in the
- * index, so that they may be returned with hits on the document.
+ * <p>A field is a section of a Document. Each field has three parts: name, type and value. Values
+ * may be text (String, Reader or pre-analyzed TokenStream), binary (byte[]), or numeric (a Number).
+ * Fields are optionally stored in the index, so that they may be returned with hits on the
+ * document.
*
- * <p>
- * NOTE: the field type is an {@link IndexableFieldType}. Making changes
- * to the state of the IndexableFieldType will impact any
- * Field it is used in. It is strongly recommended that no
+ * <p>NOTE: the field type is an {@link IndexableFieldType}. Making changes to the state of the
+ * IndexableFieldType will impact any Field it is used in. It is strongly recommended that no
* changes be made after Field instantiation.
*/
public class Field implements IndexableField {
- /**
- * Field's type
- */
+ /** Field's type */
protected final IndexableFieldType type;
- /**
- * Field's name
- */
+ /** Field's name */
protected final String name;
/** Field's value */
protected Object fieldsData;
- /** Pre-analyzed tokenStream for indexed fields; this is
- * separate from fieldsData because you are allowed to
- * have both; eg maybe field has a String value but you
- * customize how it's tokenized */
+ /**
+ * Pre-analyzed tokenStream for indexed fields; this is separate from fieldsData because you are
+ * allowed to have both; eg maybe field has a String value but you customize how it's tokenized
+ */
protected TokenStream tokenStream;
/**
- * Expert: creates a field with no initial value.
- * Intended only for custom Field subclasses.
+ * Expert: creates a field with no initial value. Intended only for custom Field subclasses.
+ *
* @param name field name
* @param type field type
- * @throws IllegalArgumentException if either the name or type
- * is null.
+ * @throws IllegalArgumentException if either the name or type is null.
*/
protected Field(String name, IndexableFieldType type) {
if (name == null) {
@@ -101,12 +94,12 @@ public class Field implements IndexableField {
/**
* Create field with Reader value.
+ *
* @param name field name
* @param reader reader value
* @param type field type
- * @throws IllegalArgumentException if either the name or type
- * is null, or if the field's type is stored(), or
- * if tokenized() is false.
+ * @throws IllegalArgumentException if either the name or type is null, or if the field's type is
+ * stored(), or if tokenized() is false.
* @throws NullPointerException if the reader is null
*/
public Field(String name, Reader reader, IndexableFieldType type) {
@@ -125,7 +118,7 @@ public class Field implements IndexableField {
if (type.indexOptions() != IndexOptions.NONE && !type.tokenized()) {
throw new IllegalArgumentException("non-tokenized fields must use String values");
}
-
+
this.name = name;
this.fieldsData = reader;
this.type = type;
@@ -133,12 +126,12 @@ public class Field implements IndexableField {
/**
* Create field with TokenStream value.
+ *
* @param name field name
* @param tokenStream TokenStream value
* @param type field type
- * @throws IllegalArgumentException if either the name or type
- * is null, or if the field's type is stored(), or
- * if tokenized() is false, or if indexed() is false.
+ * @throws IllegalArgumentException if either the name or type is null, or if the field's type is
+ * stored(), or if tokenized() is false, or if indexed() is false.
* @throws NullPointerException if the tokenStream is null
*/
public Field(String name, TokenStream tokenStream, IndexableFieldType type) {
@@ -154,23 +147,24 @@ public class Field implements IndexableField {
if (type.stored()) {
throw new IllegalArgumentException("TokenStream fields cannot be stored");
}
-
+
this.name = name;
this.fieldsData = null;
this.tokenStream = tokenStream;
this.type = type;
}
-
+
/**
* Create field with binary value.
- *
- * <p>NOTE: the provided byte[] is not copied so be sure
- * not to change it until you're done with this field.
+ *
+ * <p>NOTE: the provided byte[] is not copied so be sure not to change it until you're done with
+ * this field.
+ *
* @param name field name
* @param value byte array pointing to binary content (not copied)
* @param type field type
- * @throws IllegalArgumentException if the field name, value or type
- * is null, or the field's type is indexed().
+ * @throws IllegalArgumentException if the field name, value or type is null, or the field's type
+ * is indexed().
*/
public Field(String name, byte[] value, IndexableFieldType type) {
this(name, value, 0, value.length, type);
@@ -178,16 +172,17 @@ public class Field implements IndexableField {
/**
* Create field with binary value.
- *
- * <p>NOTE: the provided byte[] is not copied so be sure
- * not to change it until you're done with this field.
+ *
+ * <p>NOTE: the provided byte[] is not copied so be sure not to change it until you're done with
+ * this field.
+ *
* @param name field name
* @param value byte array pointing to binary content (not copied)
* @param offset starting position of the byte array
* @param length valid length of the byte array
* @param type field type
- * @throws IllegalArgumentException if the field name, value or type
- * is null, or the field's type is indexed().
+ * @throws IllegalArgumentException if the field name, value or type is null, or the field's type
+ * is indexed().
*/
public Field(String name, byte[] value, int offset, int length, IndexableFieldType type) {
this(name, value != null ? new BytesRef(value, offset, length) : null, type);
@@ -196,13 +191,14 @@ public class Field implements IndexableField {
/**
* Create field with binary value.
*
- * <p>NOTE: the provided BytesRef is not copied so be sure
- * not to change it until you're done with this field.
+ * <p>NOTE: the provided BytesRef is not copied so be sure not to change it until you're done with
+ * this field.
+ *
* @param name field name
* @param bytes BytesRef pointing to binary content (not copied)
* @param type field type
- * @throws IllegalArgumentException if the field name, bytes or type
- * is null, or the field's type is indexed().
+ * @throws IllegalArgumentException if the field name, bytes or type is null, or the field's type
+ * is indexed().
*/
public Field(String name, BytesRef bytes, IndexableFieldType type) {
if (name == null) {
@@ -223,12 +219,13 @@ public class Field implements IndexableField {
/**
* Create field with String value.
+ *
* @param name field name
* @param value string value
* @param type field type
- * @throws IllegalArgumentException if either the name, value or type
- * is null, or if the field's type is neither indexed() nor stored(),
- * or if indexed() is false but storeTermVectors() is true.
+ * @throws IllegalArgumentException if either the name, value or type is null, or if the field's
+ * type is neither indexed() nor stored(), or if indexed() is false but storeTermVectors() is
+ * true.
*/
public Field(String name, CharSequence value, IndexableFieldType type) {
if (name == null) {
@@ -241,8 +238,8 @@ public class Field implements IndexableField {
throw new IllegalArgumentException("type must not be null");
}
if (!type.stored() && type.indexOptions() == IndexOptions.NONE) {
- throw new IllegalArgumentException("it doesn't make sense to have a field that "
- + "is neither indexed nor stored");
+ throw new IllegalArgumentException(
+ "it doesn't make sense to have a field that " + "is neither indexed nor stored");
}
this.name = name;
this.fieldsData = value;
@@ -250,9 +247,8 @@ public class Field implements IndexableField {
}
/**
- * The value of the field as a String, or null. If null, the Reader value or
- * binary value is used. Exactly one of stringValue(), readerValue(), and
- * binaryValue() must be set.
+ * The value of the field as a String, or null. If null, the Reader value or binary value is used.
+ * Exactly one of stringValue(), readerValue(), and binaryValue() must be set.
*/
@Override
public String stringValue() {
@@ -265,83 +261,73 @@ public class Field implements IndexableField {
@Override
public CharSequence getCharSequenceValue() {
- return fieldsData instanceof CharSequence ?
- (CharSequence) fieldsData : stringValue();
+ return fieldsData instanceof CharSequence ? (CharSequence) fieldsData : stringValue();
}
/**
- * The value of the field as a Reader, or null. If null, the String value or
- * binary value is used. Exactly one of stringValue(), readerValue(), and
- * binaryValue() must be set.
+ * The value of the field as a Reader, or null. If null, the String value or binary value is used.
+ * Exactly one of stringValue(), readerValue(), and binaryValue() must be set.
*/
@Override
public Reader readerValue() {
return fieldsData instanceof Reader ? (Reader) fieldsData : null;
}
-
+
/**
- * The TokenStream for this field to be used when indexing, or null. If null,
- * the Reader value or String value is analyzed to produce the indexed tokens.
+ * The TokenStream for this field to be used when indexing, or null. If null, the Reader value or
+ * String value is analyzed to produce the indexed tokens.
*/
public TokenStream tokenStreamValue() {
return tokenStream;
}
-
+
/**
- * <p>
- * Expert: change the value of this field. This can be used during indexing to
- * re-use a single Field instance to improve indexing speed by avoiding GC
- * cost of new'ing and reclaiming Field instances. Typically a single
- * {@link Document} instance is re-used as well. This helps most on small
- * documents.
- * </p>
- *
- * <p>
- * Each Field instance should only be used once within a single
- * {@link Document} instance. See <a
- * href="http://wiki.apache.org/lucene-java/ImproveIndexingSpeed"
- * >ImproveIndexingSpeed</a> for details.
- * </p>
+ * Expert: change the value of this field. This can be used during indexing to re-use a single
+ * Field instance to improve indexing speed by avoiding GC cost of new'ing and reclaiming Field
+ * instances. Typically a single {@link Document} instance is re-used as well. This helps most on
+ * small documents.
+ *
+ * <p>Each Field instance should only be used once within a single {@link Document} instance. See
+ * <a href="http://wiki.apache.org/lucene-java/ImproveIndexingSpeed" >ImproveIndexingSpeed</a> for
+ * details.
*/
public void setStringValue(String value) {
if (!(fieldsData instanceof String)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to String");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to String");
}
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
fieldsData = value;
}
-
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setReaderValue(Reader value) {
if (!(fieldsData instanceof Reader)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Reader");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Reader");
}
fieldsData = value;
}
-
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setBytesValue(byte[] value) {
setBytesValue(new BytesRef(value));
}
/**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
+ * Expert: change the value of this field. See {@link #setStringValue(String)}.
*
- * <p>NOTE: the provided BytesRef is not copied so be sure
- * not to change it until you're done with this field.
+ * <p>NOTE: the provided BytesRef is not copied so be sure not to change it until you're done with
+ * this field.
*/
public void setBytesValue(BytesRef value) {
if (!(fieldsData instanceof BytesRef)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to BytesRef");
+ throw new IllegalArgumentException(
+ "cannot change value type from "
+ + fieldsData.getClass().getSimpleName()
+ + " to BytesRef");
}
if (type.indexOptions() != IndexOptions.NONE) {
throw new IllegalArgumentException("cannot set a BytesRef value on an indexed field");
@@ -352,76 +338,63 @@ public class Field implements IndexableField {
fieldsData = value;
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setByteValue(byte value) {
if (!(fieldsData instanceof Byte)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Byte");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Byte");
}
fieldsData = Byte.valueOf(value);
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setShortValue(short value) {
if (!(fieldsData instanceof Short)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Short");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Short");
}
fieldsData = Short.valueOf(value);
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setIntValue(int value) {
if (!(fieldsData instanceof Integer)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Integer");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Integer");
}
fieldsData = Integer.valueOf(value);
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setLongValue(long value) {
if (!(fieldsData instanceof Long)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Long");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Long");
}
fieldsData = Long.valueOf(value);
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setFloatValue(float value) {
if (!(fieldsData instanceof Float)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Float");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Float");
}
fieldsData = Float.valueOf(value);
}
- /**
- * Expert: change the value of this field. See
- * {@link #setStringValue(String)}.
- */
+ /** Expert: change the value of this field. See {@link #setStringValue(String)}. */
public void setDoubleValue(double value) {
if (!(fieldsData instanceof Double)) {
- throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Double");
+ throw new IllegalArgumentException(
+ "cannot change value type from " + fieldsData.getClass().getSimpleName() + " to Double");
}
fieldsData = Double.valueOf(value);
}
/**
- * Expert: sets the token stream to be used for indexing and causes
- * isIndexed() and isTokenized() to return true. May be combined with stored
- * values from stringValue() or binaryValue()
+ * Expert: sets the token stream to be used for indexing and causes isIndexed() and isTokenized()
+ * to return true. May be combined with stored values from stringValue() or binaryValue()
*/
public void setTokenStream(TokenStream tokenStream) {
if (type.indexOptions() == IndexOptions.NONE || !type.tokenized()) {
@@ -429,7 +402,7 @@ public class Field implements IndexableField {
}
this.tokenStream = tokenStream;
}
-
+
@Override
public String name() {
return name;
@@ -469,7 +442,7 @@ public class Field implements IndexableField {
result.append('>');
return result.toString();
}
-
+
/** Returns the {@link FieldType} for this field. */
@Override
public IndexableFieldType fieldType() {
@@ -513,25 +486,27 @@ public class Field implements IndexableField {
return analyzer.tokenStream(name(), stringValue());
}
- throw new IllegalArgumentException("Field must have either TokenStream, String, Reader or Number value; got " + this);
+ throw new IllegalArgumentException(
+ "Field must have either TokenStream, String, Reader or Number value; got " + this);
}
-
+
private static final class BinaryTokenStream extends TokenStream {
private final BytesTermAttribute bytesAtt = addAttribute(BytesTermAttribute.class);
private boolean used = true;
private BytesRef value;
-
- /** Creates a new TokenStream that returns a BytesRef as single token.
- * <p>Warning: Does not initialize the value, you must call
- * {@link #setValue(BytesRef)} afterwards!
+
+ /**
+ * Creates a new TokenStream that returns a BytesRef as single token.
+ *
+ * <p>Warning: Does not initialize the value, you must call {@link #setValue(BytesRef)}
+ * afterwards!
*/
- BinaryTokenStream() {
- }
+ BinaryTokenStream() {}
public void setValue(BytesRef value) {
this.value = value;
}
-
+
@Override
public boolean incrementToken() {
if (used) {
@@ -542,7 +517,7 @@ public class Field implements IndexableField {
used = true;
return true;
}
-
+
@Override
public void reset() {
used = false;
@@ -559,14 +534,15 @@ public class Field implements IndexableField {
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private boolean used = true;
private String value = null;
-
- /** Creates a new TokenStream that returns a String as single token.
- * <p>Warning: Does not initialize the value, you must call
- * {@link #setValue(String)} afterwards!
+
+ /**
+ * Creates a new TokenStream that returns a String as single token.
+ *
+ * <p>Warning: Does not initialize the value, you must call {@link #setValue(String)}
+ * afterwards!
*/
- StringTokenStream() {
- }
-
+ StringTokenStream() {}
+
/** Sets the string value. */
void setValue(String value) {
this.value = value;
@@ -590,7 +566,7 @@ public class Field implements IndexableField {
final int finalOffset = value.length();
offsetAttribute.setOffset(finalOffset, finalOffset);
}
-
+
@Override
public void reset() {
used = false;
@@ -605,10 +581,10 @@ public class Field implements IndexableField {
/** Specifies whether and how a field should be stored. */
public static enum Store {
- /** Store the original field value in the index. This is useful for short texts
- * like a document's title which should be displayed with the results. The
- * value is stored in its original form, i.e. no analyzer is used before it is
- * stored.
+ /**
+ * Store the original field value in the index. This is useful for short texts like a document's
+ * title which should be displayed with the results. The value is stored in its original form,
+ * i.e. no analyzer is used before it is stored.
*/
YES,
diff --git a/lucene/core/src/java/org/apache/lucene/document/FieldType.java b/lucene/core/src/java/org/apache/lucene/document/FieldType.java
index b89be8b..b04b2f6 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FieldType.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FieldType.java
@@ -16,10 +16,8 @@
*/
package org.apache.lucene.document;
-
import java.util.HashMap;
import java.util.Map;
-
import org.apache.lucene.analysis.Analyzer; // javadocs
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.IndexOptions;
@@ -27,10 +25,8 @@ import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.index.VectorValues;
-/**
- * Describes the properties of a field.
- */
-public class FieldType implements IndexableFieldType {
+/** Describes the properties of a field. */
+public class FieldType implements IndexableFieldType {
private boolean stored;
private boolean tokenized = true;
@@ -49,9 +45,7 @@ public class FieldType implements IndexableFieldType {
private VectorValues.SearchStrategy vectorSearchStrategy = VectorValues.SearchStrategy.NONE;
private Map<String, String> attributes;
- /**
- * Create a new mutable FieldType with all of the properties from <code>ref</code>
- */
+ /** Create a new mutable FieldType with all of the properties from <code>ref</code> */
public FieldType(IndexableFieldType ref) {
this.stored = ref.stored();
this.tokenized = ref.tokenized();
@@ -72,16 +66,13 @@ public class FieldType implements IndexableFieldType {
}
// Do not copy frozen!
}
-
- /**
- * Create a new FieldType with default properties.
- */
- public FieldType() {
- }
+
+ /** Create a new FieldType with default properties. */
+ public FieldType() {}
/**
- * Throws an exception if this FieldType is frozen. Subclasses should
- * call this within setters for additional state.
+ * Throws an exception if this FieldType is frozen. Subclasses should call this within setters for
+ * additional state.
*/
protected void checkIfFrozen() {
if (frozen) {
@@ -90,30 +81,30 @@ public class FieldType implements IndexableFieldType {
}
/**
- * Prevents future changes. Note, it is recommended that this is called once
- * the FieldTypes's properties have been set, to prevent unintentional state
- * changes.
+ * Prevents future changes. Note, it is recommended that this is called once the FieldTypes's
+ * properties have been set, to prevent unintentional state changes.
*/
public void freeze() {
this.frozen = true;
}
-
+
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
+ *
+ * <p>The default is <code>false</code>.
+ *
* @see #setStored(boolean)
*/
@Override
public boolean stored() {
return this.stored;
}
-
+
/**
* Set to <code>true</code> to store this field.
+ *
* @param value true if this field should be stored.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #stored()
*/
public void setStored(boolean value) {
@@ -123,20 +114,20 @@ public class FieldType implements IndexableFieldType {
/**
* {@inheritDoc}
- * <p>
- * The default is <code>true</code>.
+ *
+ * <p>The default is <code>true</code>.
+ *
* @see #setTokenized(boolean)
*/
public boolean tokenized() {
return this.tokenized;
}
-
+
/**
- * Set to <code>true</code> to tokenize this field's contents via the
- * configured {@link Analyzer}.
+ * Set to <code>true</code> to tokenize this field's contents via the configured {@link Analyzer}.
+ *
* @param value true if this field should be tokenized.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #tokenized()
*/
public void setTokenized(boolean value) {
@@ -146,21 +137,21 @@ public class FieldType implements IndexableFieldType {
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
+ *
+ * <p>The default is <code>false</code>.
+ *
* @see #setStoreTermVectors(boolean)
*/
@Override
public boolean storeTermVectors() {
return this.storeTermVectors;
}
-
+
/**
- * Set to <code>true</code> if this field's indexed form should be also stored
- * into term vectors.
+ * Set to <code>true</code> if this field's indexed form should be also stored into term vectors.
+ *
* @param value true if this field should store term vectors.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #storeTermVectors()
*/
public void setStoreTermVectors(boolean value) {
@@ -170,21 +161,22 @@ public class FieldType implements IndexableFieldType {
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
+ *
+ * <p>The default is <code>false</code>.
+ *
* @see #setStoreTermVectorOffsets(boolean)
*/
@Override
public boolean storeTermVectorOffsets() {
return this.storeTermVectorOffsets;
}
-
+
/**
- * Set to <code>true</code> to also store token character offsets into the term
- * vector for this field.
+ * Set to <code>true</code> to also store token character offsets into the term vector for this
+ * field.
+ *
* @param value true if this field should store term vector offsets.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #storeTermVectorOffsets()
*/
public void setStoreTermVectorOffsets(boolean value) {
@@ -194,68 +186,69 @@ public class FieldType implements IndexableFieldType {
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
+ *
+ * <p>The default is <code>false</code>.
+ *
* @see #setStoreTermVectorPositions(boolean)
*/
@Override
public boolean storeTermVectorPositions() {
return this.storeTermVectorPositions;
}
-
+
/**
- * Set to <code>true</code> to also store token positions into the term
- * vector for this field.
+ * Set to <code>true</code> to also store token positions into the term vector for this field.
+ *
* @param value true if this field should store term vector positions.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #storeTermVectorPositions()
*/
public void setStoreTermVectorPositions(boolean value) {
checkIfFrozen();
this.storeTermVectorPositions = value;
}
-
+
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
- * @see #setStoreTermVectorPayloads(boolean)
+ *
+ * <p>The default is <code>false</code>.
+ *
+ * @see #setStoreTermVectorPayloads(boolean)
*/
@Override
public boolean storeTermVectorPayloads() {
return this.storeTermVectorPayloads;
}
-
+
/**
- * Set to <code>true</code> to also store token payloads into the term
- * vector for this field.
+ * Set to <code>true</code> to also store token payloads into the term vector for this field.
+ *
* @param value true if this field should store term vector payloads.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #storeTermVectorPayloads()
*/
public void setStoreTermVectorPayloads(boolean value) {
checkIfFrozen();
this.storeTermVectorPayloads = value;
}
-
+
/**
* {@inheritDoc}
- * <p>
- * The default is <code>false</code>.
+ *
+ * <p>The default is <code>false</code>.
+ *
* @see #setOmitNorms(boolean)
*/
@Override
public boolean omitNorms() {
return this.omitNorms;
}
-
+
/**
* Set to <code>true</code> to omit normalization values for the field.
+ *
* @param value true if this field should omit norms.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #omitNorms()
*/
public void setOmitNorms(boolean value) {
@@ -265,20 +258,21 @@ public class FieldType implements IndexableFieldType {
/**
* {@inheritDoc}
- * <p>
- * The default is {@link IndexOptions#DOCS_AND_FREQS_AND_POSITIONS}.
+ *
+ * <p>The default is {@link IndexOptions#DOCS_AND_FREQS_AND_POSITIONS}.
+ *
* @see #setIndexOptions(IndexOptions)
*/
@Override
public IndexOptions indexOptions() {
return this.indexOptions;
}
-
+
/**
* Sets the indexing options for the field:
+ *
* @param value indexing options
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #indexOptions()
*/
public void setIndexOptions(IndexOptions value) {
@@ -289,51 +283,67 @@ public class FieldType implements IndexableFieldType {
this.indexOptions = value;
}
- /**
- * Enables points indexing.
- */
+ /** Enables points indexing. */
public void setDimensions(int dimensionCount, int dimensionNumBytes) {
this.setDimensions(dimensionCount, dimensionCount, dimensionNumBytes);
}
- /**
- * Enables points indexing with selectable dimension indexing.
- */
+ /** Enables points indexing with selectable dimension indexing. */
public void setDimensions(int dimensionCount, int indexDimensionCount, int dimensionNumBytes) {
checkIfFrozen();
if (dimensionCount < 0) {
throw new IllegalArgumentException("dimensionCount must be >= 0; got " + dimensionCount);
}
if (dimensionCount > PointValues.MAX_DIMENSIONS) {
- throw new IllegalArgumentException("dimensionCount must be <= " + PointValues.MAX_DIMENSIONS + "; got " + dimensionCount);
+ throw new IllegalArgumentException(
+ "dimensionCount must be <= " + PointValues.MAX_DIMENSIONS + "; got " + dimensionCount);
}
if (indexDimensionCount < 0) {
- throw new IllegalArgumentException("indexDimensionCount must be >= 0; got " + indexDimensionCount);
+ throw new IllegalArgumentException(
+ "indexDimensionCount must be >= 0; got " + indexDimensionCount);
}
if (indexDimensionCount > dimensionCount) {
- throw new IllegalArgumentException("indexDimensionCount must be <= dimensionCount: " + dimensionCount + "; got " + indexDimensionCount);
+ throw new IllegalArgumentException(
+ "indexDimensionCount must be <= dimensionCount: "
+ + dimensionCount
+ + "; got "
+ + indexDimensionCount);
}
if (indexDimensionCount > PointValues.MAX_INDEX_DIMENSIONS) {
- throw new IllegalArgumentException("indexDimensionCount must be <= " + PointValues.MAX_INDEX_DIMENSIONS + "; got " + indexDimensionCount);
+ throw new IllegalArgumentException(
+ "indexDimensionCount must be <= "
+ + PointValues.MAX_INDEX_DIMENSIONS
+ + "; got "
+ + indexDimensionCount);
}
if (dimensionNumBytes < 0) {
- throw new IllegalArgumentException("dimensionNumBytes must be >= 0; got " + dimensionNumBytes);
+ throw new IllegalArgumentException(
+ "dimensionNumBytes must be >= 0; got " + dimensionNumBytes);
}
if (dimensionNumBytes > PointValues.MAX_NUM_BYTES) {
- throw new IllegalArgumentException("dimensionNumBytes must be <= " + PointValues.MAX_NUM_BYTES + "; got " + dimensionNumBytes);
+ throw new IllegalArgumentException(
+ "dimensionNumBytes must be <= "
+ + PointValues.MAX_NUM_BYTES
+ + "; got "
+ + dimensionNumBytes);
}
if (dimensionCount == 0) {
if (indexDimensionCount != 0) {
- throw new IllegalArgumentException("when dimensionCount is 0, indexDimensionCount must be 0; got " + indexDimensionCount);
+ throw new IllegalArgumentException(
+ "when dimensionCount is 0, indexDimensionCount must be 0; got " + indexDimensionCount);
}
if (dimensionNumBytes != 0) {
- throw new IllegalArgumentException("when dimensionCount is 0, dimensionNumBytes must be 0; got " + dimensionNumBytes);
+ throw new IllegalArgumentException(
+ "when dimensionCount is 0, dimensionNumBytes must be 0; got " + dimensionNumBytes);
}
} else if (indexDimensionCount == 0) {
- throw new IllegalArgumentException("when dimensionCount is > 0, indexDimensionCount must be > 0; got " + indexDimensionCount);
+ throw new IllegalArgumentException(
+ "when dimensionCount is > 0, indexDimensionCount must be > 0; got "
+ + indexDimensionCount);
} else if (dimensionNumBytes == 0) {
if (dimensionCount != 0) {
- throw new IllegalArgumentException("when dimensionNumBytes is 0, dimensionCount must be 0; got " + dimensionCount);
+ throw new IllegalArgumentException(
+ "when dimensionNumBytes is 0, dimensionCount must be 0; got " + dimensionCount);
}
}
@@ -357,13 +367,18 @@ public class FieldType implements IndexableFieldType {
return dimensionNumBytes;
}
- void setVectorDimensionsAndSearchStrategy(int numDimensions, VectorValues.SearchStrategy distFunc) {
+ void setVectorDimensionsAndSearchStrategy(
+ int numDimensions, VectorValues.SearchStrategy distFunc) {
checkIfFrozen();
if (numDimensions <= 0) {
throw new IllegalArgumentException("vector numDimensions must be > 0; got " + numDimensions);
}
if (numDimensions > VectorValues.MAX_DIMENSIONS) {
- throw new IllegalArgumentException("vector numDimensions must be <= VectorValues.MAX_DIMENSIONS (=" + VectorValues.MAX_DIMENSIONS + "); got " + numDimensions);
+ throw new IllegalArgumentException(
+ "vector numDimensions must be <= VectorValues.MAX_DIMENSIONS (="
+ + VectorValues.MAX_DIMENSIONS
+ + "); got "
+ + numDimensions);
}
this.vectorDimension = numDimensions;
this.vectorSearchStrategy = distFunc;
@@ -381,13 +396,13 @@ public class FieldType implements IndexableFieldType {
/**
* Puts an attribute value.
- * <p>
- * This is a key-value mapping for the field that the codec can use
- * to store additional metadata.
- * <p>
- * If a value already exists for the field, it will be replaced with
- * the new value. This method is not thread-safe, user must not add attributes
- * while other threads are indexing documents with this field type.
+ *
+ * <p>This is a key-value mapping for the field that the codec can use to store additional
+ * metadata.
+ *
+ * <p>If a value already exists for the field, it will be replaced with the new value. This method
+ * is not thread-safe, user must not add attributes while other threads are indexing documents
+ * with this field type.
*
* @lucene.experimental
*/
@@ -412,8 +427,7 @@ public class FieldType implements IndexableFieldType {
result.append("stored");
}
if (indexOptions != IndexOptions.NONE) {
- if (result.length() > 0)
- result.append(",");
+ if (result.length() > 0) result.append(",");
result.append("indexed");
if (tokenized()) {
result.append(",tokenized");
@@ -456,14 +470,15 @@ public class FieldType implements IndexableFieldType {
result.append("docValuesType=");
result.append(docValuesType);
}
-
+
return result.toString();
}
-
+
/**
* {@inheritDoc}
- * <p>
- * The default is <code>null</code> (no docValues)
+ *
+ * <p>The default is <code>null</code> (no docValues)
+ *
* @see #setDocValuesType(DocValuesType)
*/
@Override
@@ -473,9 +488,9 @@ public class FieldType implements IndexableFieldType {
/**
* Sets the field's DocValuesType
+ *
* @param type DocValues type, or null if no DocValues should be stored.
- * @throws IllegalStateException if this FieldType is frozen against
- * future modifications.
+ * @throws IllegalStateException if this FieldType is frozen against future modifications.
* @see #docValuesType()
*/
public void setDocValuesType(DocValuesType type) {
diff --git a/lucene/core/src/java/org/apache/lucene/document/FloatDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/FloatDocValuesField.java
index 3a8bdea..c375cc6 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatDocValuesField.java
@@ -16,22 +16,22 @@
*/
package org.apache.lucene.document;
-
/**
- * Syntactic sugar for encoding floats as NumericDocValues
- * via {@link Float#floatToRawIntBits(float)}.
- * <p>
- * Per-document floating point values can be retrieved via
- * {@link org.apache.lucene.index.LeafReader#getNumericDocValues(String)}.
- * <p>
- * <b>NOTE</b>: In most all cases this will be rather inefficient,
- * requiring four bytes per document. Consider encoding floating
- * point values yourself with only as much precision as you require.
+ * Syntactic sugar for encoding floats as NumericDocValues via {@link
+ * Float#floatToRawIntBits(float)}.
+ *
+ * <p>Per-document floating point values can be retrieved via {@link
+ * org.apache.lucene.index.LeafReader#getNumericDocValues(String)}.
+ *
+ * <p><b>NOTE</b>: In most all cases this will be rather inefficient, requiring four bytes per
+ * document. Consider encoding floating point values yourself with only as much precision as you
+ * require.
*/
public class FloatDocValuesField extends NumericDocValuesField {
- /**
- * Creates a new DocValues field with the specified 32-bit float value
+ /**
+ * Creates a new DocValues field with the specified 32-bit float value
+ *
* @param name field name
* @param value 32-bit float value
* @throws IllegalArgumentException if the field name is null
@@ -44,7 +44,7 @@ public class FloatDocValuesField extends NumericDocValuesField {
public void setFloatValue(float value) {
super.setLongValue(Float.floatToRawIntBits(value));
}
-
+
@Override
public void setLongValue(long value) {
throw new IllegalArgumentException("cannot change value type from Float to Long");
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 92efa5e..bc8feb78 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatPoint.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.util.Arrays;
import java.util.Collection;
-
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.PointInSetQuery;
import org.apache.lucene.search.PointRangeQuery;
@@ -26,29 +25,30 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-/**
- * An indexed {@code float} field for fast range filters. If you also
- * need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * Finding all documents within an N-dimensional 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:
+/**
+ * An indexed {@code float} field for fast range filters. If you also need to store the value, you
+ * should add a separate {@link StoredField} instance.
+ *
+ * <p>Finding all documents within an N-dimensional 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 #newExactQuery(String, float)} for matching an exact 1D point.
* <li>{@link #newSetQuery(String, float...)} for matching a set of 1D values.
* <li>{@link #newRangeQuery(String, float, float)} for matching a 1D range.
- * <li>{@link #newRangeQuery(String, float[], float[])} for matching points/ranges in n-dimensional space.
+ * <li>{@link #newRangeQuery(String, float[], float[])} for matching points/ranges in
+ * n-dimensional space.
* </ul>
+ *
* @see PointValues
*/
public final class FloatPoint extends Field {
/**
- * Return the least float that compares greater than {@code f} consistently
- * with {@link Float#compare}. The only difference with
- * {@link Math#nextUp(float)} is that this method returns {@code +0f} when
- * the argument is {@code -0f}.
+ * Return the least float that compares greater than {@code f} consistently with {@link
+ * Float#compare}. The only difference with {@link Math#nextUp(float)} is that this method returns
+ * {@code +0f} when the argument is {@code -0f}.
*/
public static float nextUp(float f) {
if (Float.floatToIntBits(f) == 0x8000_0000) { // -0f
@@ -58,10 +58,9 @@ public final class FloatPoint extends Field {
}
/**
- * Return the greatest float that compares less than {@code f} consistently
- * with {@link Float#compare}. The only difference with
- * {@link Math#nextDown(float)} is that this method returns {@code -0f} when
- * the argument is {@code +0f}.
+ * Return the greatest float that compares less than {@code f} consistently with {@link
+ * Float#compare}. The only difference with {@link Math#nextDown(float)} is that this method
+ * returns {@code -0f} when the argument is {@code +0f}.
*/
public static float nextDown(float f) {
if (Float.floatToIntBits(f) == 0) { // +0f
@@ -85,7 +84,14 @@ public final class FloatPoint extends Field {
/** Change the values of this field */
public void setFloatValues(float... point) {
if (type.pointDimensionCount() != point.length) {
- throw new IllegalArgumentException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot change to (incoming) " + point.length + " dimensions");
+ throw new IllegalArgumentException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot change to (incoming) "
+ + point.length
+ + " dimensions");
}
fieldsData = pack(point);
}
@@ -98,7 +104,12 @@ public final class FloatPoint extends Field {
@Override
public Number numericValue() {
if (type.pointDimensionCount() != 1) {
- throw new IllegalStateException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot convert to a single numeric value");
+ throw new IllegalStateException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot convert to a single numeric value");
}
BytesRef bytes = (BytesRef) fieldsData;
assert bytes.length == Float.BYTES;
@@ -106,7 +117,7 @@ public final class FloatPoint extends Field {
}
/**
- * Pack a float point into a BytesRef
+ * Pack a float point into a BytesRef
*
* @param point float[] value
* @throws IllegalArgumentException is the value is null or of zero length
@@ -119,7 +130,7 @@ public final class FloatPoint extends Field {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
byte[] packed = new byte[point.length * Float.BYTES];
-
+
for (int dim = 0; dim < point.length; dim++) {
encodeDimension(point[dim], packed, dim * Float.BYTES);
}
@@ -127,17 +138,17 @@ public final class FloatPoint extends Field {
return new BytesRef(packed);
}
- /** Creates a new FloatPoint, indexing the
- * provided N-dimensional float point.
+ /**
+ * Creates a new FloatPoint, indexing the provided N-dimensional float point.
*
- * @param name field name
- * @param point float[] value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point float[] value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public FloatPoint(String name, float... point) {
super(name, pack(point), getType(point.length));
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -157,26 +168,26 @@ public final class FloatPoint extends Field {
result.append('>');
return result.toString();
}
-
+
// public helper methods (e.g. for queries)
-
+
/** Encode single float dimension */
public static void encodeDimension(float value, byte dest[], int offset) {
NumericUtils.intToSortableBytes(NumericUtils.floatToSortableInt(value), dest, offset);
}
-
+
/** Decode single float dimension */
public static float decodeDimension(byte value[], int offset) {
return NumericUtils.sortableIntToFloat(NumericUtils.sortableBytesToInt(value, offset));
}
-
+
// static methods for generating queries
- /**
+ /**
* Create a query for matching an exact float value.
- * <p>
- * This is for simple one-dimension points, for multidimensional points use
- * {@link #newRangeQuery(String, float[], float[])} instead.
+ *
+ * <p>This is for simple one-dimension points, for multidimensional points use {@link
+ * #newRangeQuery(String, float[], float[])} instead.
*
* @param field field name. must not be {@code null}.
* @param value float value
@@ -186,19 +197,20 @@ public final class FloatPoint extends Field {
public static Query newExactQuery(String field, float value) {
return newRangeQuery(field, value, value);
}
-
- /**
+
+ /**
* Create a range query for float values.
- * <p>
- * This is for simple one-dimension ranges, for multidimensional ranges use
- * {@link #newRangeQuery(String, float[], float[])} instead.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = Float.NEGATIVE_INFINITY} or {@code upperValue = Float.POSITIVE_INFINITY}.
- * <p> Ranges are inclusive. For exclusive ranges, pass {@link #nextUp(float) nextUp(lowerValue)}
+ *
+ * <p>This is for simple one-dimension ranges, for multidimensional ranges use {@link
+ * #newRangeQuery(String, float[], float[])} instead.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = Float.NEGATIVE_INFINITY} or {@code upperValue = Float.POSITIVE_INFINITY}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@link #nextUp(float) nextUp(lowerValue)}
* or {@link #nextUp(float) nextDown(upperValue)}.
- * <p>
- * Range comparisons are consistent with {@link Float#compareTo(Float)}.
+ *
+ * <p>Range comparisons are consistent with {@link Float#compareTo(Float)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive).
@@ -207,29 +219,32 @@ public final class FloatPoint extends Field {
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, float lowerValue, float upperValue) {
- return newRangeQuery(field, new float[] { lowerValue }, new float[] { upperValue });
+ return newRangeQuery(field, new float[] {lowerValue}, new float[] {upperValue});
}
- /**
+ /**
* Create a range query for n-dimensional float values.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue[i] = Float.NEGATIVE_INFINITY} or {@code upperValue[i] = Float.POSITIVE_INFINITY}.
- * <p> Ranges are inclusive. For exclusive ranges, pass {@code Math#nextUp(lowerValue[i])}
- * or {@code Math.nextDown(upperValue[i])}.
- * <p>
- * Range comparisons are consistent with {@link Float#compareTo(Float)}.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue[i] = Float.NEGATIVE_INFINITY} or {@code upperValue[i] =
+ * Float.POSITIVE_INFINITY}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math#nextUp(lowerValue[i])} or
+ * {@code Math.nextDown(upperValue[i])}.
+ *
+ * <p>Range comparisons are consistent with {@link Float#compareTo(Float)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be {@code null}.
* @param upperValue upper portion of the range (inclusive). must not be {@code null}.
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if {@code upperValue} is null,
- * or if {@code lowerValue.length != upperValue.length}
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if
+ * {@code upperValue} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, float[] lowerValue, float[] upperValue) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
- return new PointRangeQuery(field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
+ return new PointRangeQuery(
+ field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
@Override
protected String toString(int dimension, byte[] value) {
return Float.toString(decodeDimension(value, 0));
@@ -238,8 +253,9 @@ public final class FloatPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -251,22 +267,25 @@ public final class FloatPoint extends Field {
final BytesRef encoded = new BytesRef(new byte[Float.BYTES]);
- return new PointInSetQuery(field, 1, Float.BYTES,
- new PointInSetQuery.Stream() {
+ return new PointInSetQuery(
+ field,
+ 1,
+ Float.BYTES,
+ new PointInSetQuery.Stream() {
- int upto;
+ int upto;
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encodeDimension(sortedValues[upto], encoded.bytes, 0);
- upto++;
- return encoded;
- }
- }
- }) {
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encodeDimension(sortedValues[upto], encoded.bytes, 0);
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
assert value.length == Float.BYTES;
@@ -276,8 +295,9 @@ public final class FloatPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
diff --git a/lucene/core/src/java/org/apache/lucene/document/FloatRange.java b/lucene/core/src/java/org/apache/lucene/document/FloatRange.java
index a74936f..15bf70b 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatRange.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatRange.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.util.Objects;
-
import org.apache.lucene.document.RangeFieldQuery.QueryType;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
@@ -25,20 +24,25 @@ import org.apache.lucene.util.NumericUtils;
/**
* An indexed Float Range field.
- * <p>
- * This field indexes dimensional ranges defined as min/max pairs. It supports
- * up to a maximum of 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single float range,
- * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a tesseract.
- * <p>
- * Multiple values for the same field in one document is supported, and open ended ranges can be defined using
- * {@code Float.NEGATIVE_INFINITY} and {@code Float.POSITIVE_INFINITY}.
*
- * <p>
- * This field defines the following static factory methods for common search operations over float ranges:
+ * <p>This field indexes dimensional ranges defined as min/max pairs. It supports up to a maximum of
+ * 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single float range, 2
+ * dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a
+ * tesseract.
+ *
+ * <p>Multiple values for the same field in one document is supported, and open ended ranges can be
+ * defined using {@code Float.NEGATIVE_INFINITY} and {@code Float.POSITIVE_INFINITY}.
+ *
+ * <p>This field defines the following static factory methods for common search operations over
+ * float ranges:
+ *
* <ul>
- * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined search range.
- * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search range.
- * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search range.
+ * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined
+ * search range.
+ * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search
+ * range.
+ * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search
+ * range.
* </ul>
*/
public class FloatRange extends Field {
@@ -65,30 +69,38 @@ public class FloatRange extends Field {
FieldType ft = new FieldType();
// dimensions is set as 2*dimension size (min/max per dimension)
- ft.setDimensions(dimensions*2, BYTES);
+ ft.setDimensions(dimensions * 2, BYTES);
ft.freeze();
return ft;
}
/**
* Changes the values of the field.
+ *
* @param min array of min values. (accepts {@code Float.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Float.POSITIVE_INFINITY})
* @throws IllegalArgumentException if {@code min} or {@code max} is invalid
*/
public void setRangeValues(float[] min, float[] max) {
checkArgs(min, max);
- if (min.length*2 != type.pointDimensionCount() || max.length*2 != type.pointDimensionCount()) {
- throw new IllegalArgumentException("field (name=" + name + ") uses " + type.pointDimensionCount()/2
- + " dimensions; cannot change to (incoming) " + min.length + " dimensions");
+ if (min.length * 2 != type.pointDimensionCount()
+ || max.length * 2 != type.pointDimensionCount()) {
+ throw new IllegalArgumentException(
+ "field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount() / 2
+ + " dimensions; cannot change to (incoming) "
+ + min.length
+ + " dimensions");
}
final byte[] bytes;
if (fieldsData == null) {
- bytes = new byte[BYTES*2*min.length];
+ bytes = new byte[BYTES * 2 * min.length];
fieldsData = new BytesRef(bytes);
} else {
- bytes = ((BytesRef)fieldsData).bytes;
+ bytes = ((BytesRef) fieldsData).bytes;
}
verifyAndEncode(min, max, bytes);
}
@@ -106,32 +118,32 @@ public class FloatRange extends Field {
}
}
- /**
- * Encodes the min, max ranges into a byte array
- */
+ /** Encodes the min, max ranges into a byte array */
static byte[] encode(float[] min, float[] max) {
checkArgs(min, max);
- byte[] b = new byte[BYTES*2*min.length];
+ byte[] b = new byte[BYTES * 2 * min.length];
verifyAndEncode(min, max, b);
return b;
}
/**
* encode the ranges into a sortable byte array ({@code Float.NaN} not allowed)
- * <p>
- * example for 4 dimensions (8 bytes per dimension value):
- * minD1 ... minD4 | maxD1 ... maxD4
+ *
+ * <p>example for 4 dimensions (8 bytes per dimension value): minD1 ... minD4 | maxD1 ... maxD4
*/
static void verifyAndEncode(float[] min, float[] max, byte[] bytes) {
- for (int d=0,i=0,j=min.length*BYTES; d<min.length; ++d, i+=BYTES, j+=BYTES) {
+ for (int d = 0, i = 0, j = min.length * BYTES; d < min.length; ++d, i += BYTES, j += BYTES) {
if (Double.isNaN(min[d])) {
- throw new IllegalArgumentException("invalid min value (" + Float.NaN + ")" + " in FloatRange");
+ throw new IllegalArgumentException(
+ "invalid min value (" + Float.NaN + ")" + " in FloatRange");
}
if (Double.isNaN(max[d])) {
- throw new IllegalArgumentException("invalid max value (" + Float.NaN + ")" + " in FloatRange");
+ throw new IllegalArgumentException(
+ "invalid max value (" + Float.NaN + ")" + " in FloatRange");
}
if (min[d] > max[d]) {
- throw new IllegalArgumentException("min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
+ throw new IllegalArgumentException(
+ "min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
}
encode(min[d], bytes, i);
encode(max[d], bytes, j);
@@ -145,43 +157,47 @@ public class FloatRange extends Field {
/**
* Get the min value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded min value
*/
public float getMin(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMin(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMin(((BytesRef) fieldsData).bytes, dimension);
}
/**
* Get the max value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded max value
*/
public float getMax(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMax(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMax(((BytesRef) fieldsData).bytes, dimension);
}
/** decodes the min value (for the defined dimension) from the encoded input byte array */
static float decodeMin(byte[] b, int dimension) {
- int offset = dimension*BYTES;
+ int offset = dimension * BYTES;
return NumericUtils.sortableIntToFloat(NumericUtils.sortableBytesToInt(b, offset));
}
/** decodes the max value (for the defined dimension) from the encoded input byte array */
static float decodeMax(byte[] b, int dimension) {
- int offset = b.length/2 + dimension*BYTES;
+ int offset = b.length / 2 + dimension * BYTES;
return NumericUtils.sortableIntToFloat(NumericUtils.sortableBytesToInt(b, offset));
}
/**
* Create a query for matching indexed ranges that intersect the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Float.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Float.MAX_VALUE})
* @return query for matching intersecting ranges (overlap, within, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newIntersectsQuery(String field, final float[] min, final float[] max) {
return newRelationQuery(field, min, max, QueryType.INTERSECTS);
@@ -189,11 +205,13 @@ public class FloatRange extends Field {
/**
* Create a query for matching indexed float ranges that contain the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Float.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Float.POSITIVE_INFINITY})
* @return query for matching ranges that contain the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newContainsQuery(String field, final float[] min, final float[] max) {
return newRelationQuery(field, min, max, QueryType.CONTAINS);
@@ -201,32 +219,37 @@ public class FloatRange extends Field {
/**
* Create a query for matching indexed ranges that are within the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Float.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Float.POSITIVE_INFINITY})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newWithinQuery(String field, final float[] min, final float[] max) {
return newRelationQuery(field, min, max, QueryType.WITHIN);
}
/**
- * Create a query for matching indexed ranges that cross the defined range.
- * A CROSSES is defined as any set of ranges that are not disjoint and not wholly contained by
- * the query. Effectively, its the complement of union(WITHIN, DISJOINT).
+ * Create a query for matching indexed ranges that cross the defined range. A CROSSES is defined
+ * as any set of ranges that are not disjoint and not wholly contained by the query. Effectively,
+ * its the complement of union(WITHIN, DISJOINT).
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Float.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Float.POSITIVE_INFINITY})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newCrossesQuery(String field, final float[] min, final float[] max) {
return newRelationQuery(field, min, max, QueryType.CROSSES);
}
/** helper method for creating the desired relational query */
- private static Query newRelationQuery(String field, final float[] min, final float[] max, QueryType relation) {
+ private static Query newRelationQuery(
+ String field, final float[] min, final float[] max, QueryType relation) {
checkArgs(min, max);
return new RangeFieldQuery(field, encode(min, max), min.length, relation) {
@Override
@@ -243,7 +266,7 @@ public class FloatRange extends Field {
sb.append(" <");
sb.append(name);
sb.append(':');
- byte[] b = ((BytesRef)fieldsData).bytes;
+ byte[] b = ((BytesRef) fieldsData).bytes;
toString(b, 0);
for (int d = 0; d < type.pointDimensionCount() / 2; ++d) {
sb.append(' ');
@@ -256,12 +279,16 @@ public class FloatRange extends Field {
/**
* Returns the String representation for the range at the given dimension
+ *
* @param ranges the encoded ranges, never null
* @param dimension the dimension of interest
* @return The string representation for the range at the provided dimension
*/
private static String toString(byte[] ranges, int dimension) {
- return "[" + Float.toString(decodeMin(ranges, dimension)) + " : "
- + Float.toString(decodeMax(ranges, dimension)) + "]";
+ return "["
+ + Float.toString(decodeMin(ranges, dimension))
+ + " : "
+ + Float.toString(decodeMax(ranges, dimension))
+ + "]";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/FloatRangeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/FloatRangeDocValuesField.java
index c5fefc4..45184d9 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatRangeDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatRangeDocValuesField.java
@@ -20,10 +20,10 @@ package org.apache.lucene.document;
import org.apache.lucene.search.Query;
/**
- * DocValues field for FloatRange. This is a single valued field per document
- * due to being an extension of BinaryDocValuesField.
+ * DocValues field for FloatRange. This is a single valued field per document due to being an
+ * extension of BinaryDocValuesField.
*/
-public class FloatRangeDocValuesField extends BinaryRangeDocValuesField{
+public class FloatRangeDocValuesField extends BinaryRangeDocValuesField {
final String field;
final float[] min;
final float[] max;
@@ -55,22 +55,23 @@ public class FloatRangeDocValuesField extends BinaryRangeDocValuesField{
return max[dimension];
}
- private static Query newSlowRangeQuery(String field, final float[] min, final float[] max,
- RangeFieldQuery.QueryType queryType) {
+ private static Query newSlowRangeQuery(
+ String field, final float[] min, final float[] max, RangeFieldQuery.QueryType queryType) {
checkArgs(min, max);
return new FloatRangeSlowRangeQuery(field, min, max, queryType);
}
- /** Create a new range query that finds all ranges that intersect using doc values.
- * NOTE: This doesn't leverage indexing and may be slow.
- * @see FloatRange#newIntersectsQuery */
+ /**
+ * Create a new range query that finds all ranges that intersect using doc values. NOTE: This
+ * doesn't leverage indexing and may be slow.
+ *
+ * @see FloatRange#newIntersectsQuery
+ */
public static Query newSlowIntersectsQuery(String field, final float[] min, final float[] max) {
return newSlowRangeQuery(field, min, max, RangeFieldQuery.QueryType.INTERSECTS);
}
- /**
- * validate the arguments
- */
+ /** validate the arguments */
private static void checkArgs(final float[] min, final float[] max) {
if (min == null || max == null || min.length == 0 || max.length == 0) {
throw new IllegalArgumentException("min/max range values cannot be null or empty");
diff --git a/lucene/core/src/java/org/apache/lucene/document/FloatRangeSlowRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/FloatRangeSlowRangeQuery.java
index dd208aa..9c01162 100644
--- a/lucene/core/src/java/org/apache/lucene/document/FloatRangeSlowRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/FloatRangeSlowRangeQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryVisitor;
@@ -30,7 +29,8 @@ class FloatRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
private final float[] min;
private final float[] max;
- FloatRangeSlowRangeQuery(String field, float[] min, float[] max, RangeFieldQuery.QueryType queryType) {
+ FloatRangeSlowRangeQuery(
+ String field, float[] min, float[] max, RangeFieldQuery.QueryType queryType) {
super(field, encodeRanges(min, max), FloatRange.BYTES, min.length, queryType);
this.field = field;
this.min = min;
@@ -70,8 +70,7 @@ class FloatRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
if (this.field.equals(field) == false) {
b.append(this.field).append(":");
}
- return b
- .append("[")
+ return b.append("[")
.append(Arrays.toString(min))
.append(" TO ")
.append(Arrays.toString(max))
diff --git a/lucene/core/src/java/org/apache/lucene/document/InetAddressPoint.java b/lucene/core/src/java/org/apache/lucene/document/InetAddressPoint.java
index 7316835..8a9cc72 100644
--- a/lucene/core/src/java/org/apache/lucene/document/InetAddressPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/InetAddressPoint.java
@@ -20,7 +20,6 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Comparator;
-
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.PointInSetQuery;
import org.apache.lucene.search.PointRangeQuery;
@@ -28,24 +27,27 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-/**
+/**
* An indexed 128-bit {@code InetAddress} field.
- * <p>
- * 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:
+ *
+ * <p>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 #newExactQuery(String, InetAddress)} for matching an exact network address.
- * <li>{@link #newPrefixQuery(String, InetAddress, int)} for matching a network based on CIDR prefix.
- * <li>{@link #newRangeQuery(String, InetAddress, InetAddress)} for matching arbitrary network address ranges.
+ * <li>{@link #newPrefixQuery(String, InetAddress, int)} for matching a network based on CIDR
+ * prefix.
+ * <li>{@link #newRangeQuery(String, InetAddress, InetAddress)} for matching arbitrary network
+ * address ranges.
* <li>{@link #newSetQuery(String, InetAddress...)} for matching a set of network addresses.
* </ul>
- * <p>
- * This field supports both IPv4 and IPv6 addresses: IPv4 addresses are converted
- * to <a href="https://tools.ietf.org/html/rfc4291#section-2.5.5">IPv4-Mapped IPv6 Addresses</a>:
- * indexing {@code 1.2.3.4} is the same as indexing {@code ::FFFF:1.2.3.4}.
+ *
+ * <p>This field supports both IPv4 and IPv6 addresses: IPv4 addresses are converted to <a
+ * href="https://tools.ietf.org/html/rfc4291#section-2.5.5">IPv4-Mapped IPv6 Addresses</a>: indexing
+ * {@code 1.2.3.4} is the same as indexing {@code ::FFFF:1.2.3.4}.
+ *
* @see PointValues
*/
public class InetAddressPoint extends Field {
@@ -54,11 +56,12 @@ public class InetAddressPoint extends Field {
// so its not wasteful, but allows one field to handle both IPv4 and IPv6.
/** The number of bytes per dimension: 128 bits */
public static final int BYTES = 16;
-
+
// rfc4291 prefix
- static final byte[] IPV4_PREFIX = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 };
+ static final byte[] IPV4_PREFIX = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1};
private static final FieldType TYPE;
+
static {
TYPE = new FieldType();
TYPE.setDimensions(1, BYTES);
@@ -69,6 +72,7 @@ public class InetAddressPoint extends Field {
public static final InetAddress MIN_VALUE;
/** The maximum value that an ip address can hold. */
public static final InetAddress MAX_VALUE;
+
static {
MIN_VALUE = decode(new byte[BYTES]);
byte[] maxValueBytes = new byte[BYTES];
@@ -77,36 +81,36 @@ public class InetAddressPoint extends Field {
}
/**
- * Return the {@link InetAddress} that compares immediately greater than
- * {@code address}.
- * @throws ArithmeticException if the provided address is the
- * {@link #MAX_VALUE maximum ip address}
+ * Return the {@link InetAddress} that compares immediately greater than {@code address}.
+ *
+ * @throws ArithmeticException if the provided address is the {@link #MAX_VALUE maximum ip
+ * address}
*/
public static InetAddress nextUp(InetAddress address) {
if (address.equals(MAX_VALUE)) {
- throw new ArithmeticException("Overflow: there is no greater InetAddress than "
- + address.getHostAddress());
+ throw new ArithmeticException(
+ "Overflow: there is no greater InetAddress than " + address.getHostAddress());
}
byte[] delta = new byte[BYTES];
- delta[BYTES-1] = 1;
+ delta[BYTES - 1] = 1;
byte[] nextUpBytes = new byte[InetAddressPoint.BYTES];
NumericUtils.add(InetAddressPoint.BYTES, 0, encode(address), delta, nextUpBytes);
return decode(nextUpBytes);
}
/**
- * Return the {@link InetAddress} that compares immediately less than
- * {@code address}.
- * @throws ArithmeticException if the provided address is the
- * {@link #MIN_VALUE minimum ip address}
+ * Return the {@link InetAddress} that compares immediately less than {@code address}.
+ *
+ * @throws ArithmeticException if the provided address is the {@link #MIN_VALUE minimum ip
+ * address}
*/
public static InetAddress nextDown(InetAddress address) {
if (address.equals(MIN_VALUE)) {
- throw new ArithmeticException("Underflow: there is no smaller InetAddress than "
- + address.getHostAddress());
+ throw new ArithmeticException(
+ "Underflow: there is no smaller InetAddress than " + address.getHostAddress());
}
byte[] delta = new byte[BYTES];
- delta[BYTES-1] = 1;
+ delta[BYTES - 1] = 1;
byte[] nextDownBytes = new byte[InetAddressPoint.BYTES];
NumericUtils.subtract(InetAddressPoint.BYTES, 0, encode(address), delta, nextDownBytes);
return decode(nextDownBytes);
@@ -125,18 +129,18 @@ public class InetAddressPoint extends Field {
throw new IllegalArgumentException("cannot change value type from InetAddress to BytesRef");
}
- /** Creates a new InetAddressPoint, indexing the
- * provided address.
+ /**
+ * Creates a new InetAddressPoint, indexing the provided address.
*
- * @param name field name
- * @param point InetAddress value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point InetAddress value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public InetAddressPoint(String name, InetAddress point) {
super(name, TYPE);
setInetAddressValue(point);
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -159,7 +163,7 @@ public class InetAddressPoint extends Field {
result.append('>');
return result.toString();
}
-
+
// public helper methods (e.g. for queries)
/** Encode InetAddress value into binary encoding */
@@ -176,7 +180,7 @@ public class InetAddressPoint extends Field {
}
return address;
}
-
+
/** Decodes InetAddress value from binary encoding */
public static InetAddress decode(byte value[]) {
try {
@@ -189,7 +193,7 @@ public class InetAddressPoint extends Field {
// static methods for generating queries
- /**
+ /**
* Create a query for matching a network address.
*
* @param field field name. must not be {@code null}.
@@ -200,13 +204,14 @@ public class InetAddressPoint extends Field {
public static Query newExactQuery(String field, InetAddress value) {
return newRangeQuery(field, value, value);
}
-
- /**
+
+ /**
* Create a prefix query for matching a CIDR network range.
*
* @param field field name. must not be {@code null}.
* @param value any host address
- * @param prefixLength the network prefix length for this address. This is also known as the subnet mask in the context of IPv4 addresses.
+ * @param prefixLength the network prefix length for this address. This is also known as the
+ * subnet mask in the context of IPv4 addresses.
* @throws IllegalArgumentException if {@code field} is null, or prefixLength is invalid.
* @return a query matching documents with addresses contained within this network
*/
@@ -215,9 +220,13 @@ public class InetAddressPoint extends Field {
throw new IllegalArgumentException("InetAddress must not be null");
}
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");
+ throw new IllegalArgumentException(
+ "illegal prefixLength '"
+ + prefixLength
+ + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges");
}
- // create the lower value by zeroing out the host portion, upper value by filling it with all ones.
+ // create the lower value by zeroing out the host portion, upper value by filling it with all
+ // ones.
byte lower[] = value.getAddress();
byte upper[] = value.getAddress();
for (int i = prefixLength; i < 8 * lower.length; i++) {
@@ -232,20 +241,21 @@ public class InetAddressPoint extends Field {
}
}
- /**
+ /**
* Create a range query for network addresses.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = InetAddressPoint.MIN_VALUE} or
- * {@code upperValue = InetAddressPoint.MAX_VALUE}.
- * <p> Ranges are inclusive. For exclusive ranges, pass {@code InetAddressPoint#nextUp(lowerValue)}
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = InetAddressPoint.MIN_VALUE} or {@code upperValue =
+ * InetAddressPoint.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code InetAddressPoint#nextUp(lowerValue)}
* or {@code InetAddressPoint#nexDown(upperValue)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be null.
* @param upperValue upper portion of the range (inclusive). must not be null.
- * @throws IllegalArgumentException if {@code field} is null, {@code lowerValue} is null,
- * or {@code upperValue} is null
+ * @throws IllegalArgumentException if {@code field} is null, {@code lowerValue} is null, or
+ * {@code upperValue} is null
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, InetAddress lowerValue, InetAddress upperValue) {
@@ -259,8 +269,9 @@ public class InetAddressPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -269,39 +280,44 @@ public class InetAddressPoint extends Field {
// We must compare the encoded form (InetAddress doesn't implement Comparable, and even if it
// did, we do our own thing with ipv4 addresses):
- // NOTE: we could instead convert-per-comparison and save this extra array, at cost of slower sort:
+ // NOTE: we could instead convert-per-comparison and save this extra array, at cost of slower
+ // sort:
byte[][] sortedValues = new byte[values.length][];
- for(int i=0;i<values.length;i++) {
+ for (int i = 0; i < values.length; i++) {
sortedValues[i] = encode(values[i]);
}
- Arrays.sort(sortedValues,
- new Comparator<byte[]>() {
- @Override
- public int compare(byte[] a, byte[] b) {
- return Arrays.compareUnsigned(a, 0, BYTES, b, 0, BYTES);
- }
- });
+ Arrays.sort(
+ sortedValues,
+ new Comparator<byte[]>() {
+ @Override
+ public int compare(byte[] a, byte[] b) {
+ return Arrays.compareUnsigned(a, 0, BYTES, b, 0, BYTES);
+ }
+ });
final BytesRef encoded = new BytesRef(new byte[BYTES]);
- return new PointInSetQuery(field, 1, BYTES,
- new PointInSetQuery.Stream() {
+ return new PointInSetQuery(
+ field,
+ 1,
+ BYTES,
+ new PointInSetQuery.Stream() {
- int upto;
+ int upto;
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encoded.bytes = sortedValues[upto];
- assert encoded.bytes.length == encoded.length;
- upto++;
- return encoded;
- }
- }
- }) {
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encoded.bytes = sortedValues[upto];
+ assert encoded.bytes.length == encoded.length;
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
assert value.length == BYTES;
diff --git a/lucene/core/src/java/org/apache/lucene/document/InetAddressRange.java b/lucene/core/src/java/org/apache/lucene/document/InetAddressRange.java
index b530f99..48edf68 100644
--- a/lucene/core/src/java/org/apache/lucene/document/InetAddressRange.java
+++ b/lucene/core/src/java/org/apache/lucene/document/InetAddressRange.java
@@ -18,26 +18,30 @@ package org.apache.lucene.document;
import java.net.InetAddress;
import java.util.Arrays;
-
import org.apache.lucene.document.RangeFieldQuery.QueryType;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
/**
* An indexed InetAddress Range Field
- * <p>
- * This field indexes an {@code InetAddress} range defined as a min/max pairs. It is single
+ *
+ * <p>This field indexes an {@code InetAddress} range defined as a min/max pairs. It is single
* dimension only (indexed as two 16 byte paired values).
- * <p>
- * Multiple values are supported.
*
- * <p>
- * This field defines the following static factory methods for common search operations over Ip Ranges
+ * <p>Multiple values are supported.
+ *
+ * <p>This field defines the following static factory methods for common search operations over Ip
+ * Ranges
+ *
* <ul>
- * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ip ranges that intersect the defined search range.
- * <li>{@link #newWithinQuery newWithinQuery()} matches ip ranges that are within the defined search range.
- * <li>{@link #newContainsQuery newContainsQuery()} matches ip ranges that contain the defined search range.
- * <li>{@link #newCrossesQuery newCrossesQuery()} matches ip ranges that cross the defined search range
+ * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ip ranges that intersect the
+ * defined search range.
+ * <li>{@link #newWithinQuery newWithinQuery()} matches ip ranges that are within the defined
+ * search range.
+ * <li>{@link #newContainsQuery newContainsQuery()} matches ip ranges that contain the defined
+ * search range.
+ * <li>{@link #newCrossesQuery newCrossesQuery()} matches ip ranges that cross the defined search
+ * range
* </ul>
*/
public class InetAddressRange extends Field {
@@ -45,6 +49,7 @@ public class InetAddressRange extends Field {
public static final int BYTES = InetAddressPoint.BYTES;
private static final FieldType TYPE;
+
static {
TYPE = new FieldType();
TYPE.setDimensions(2, BYTES);
@@ -53,6 +58,7 @@ public class InetAddressRange extends Field {
/**
* Create a new InetAddressRange from min/max value
+ *
* @param name field name. must not be null.
* @param min range min value; defined as an {@code InetAddress}
* @param max range max value; defined as an {@code InetAddress}
@@ -64,16 +70,17 @@ public class InetAddressRange extends Field {
/**
* Change (or set) the min/max values of the field.
+ *
* @param min range min value; defined as an {@code InetAddress}
* @param max range max value; defined as an {@code InetAddress}
*/
public void setRangeValues(InetAddress min, InetAddress max) {
final byte[] bytes;
if (fieldsData == null) {
- bytes = new byte[BYTES*2];
+ bytes = new byte[BYTES * 2];
fieldsData = new BytesRef(bytes);
} else {
- bytes = ((BytesRef)fieldsData).bytes;
+ bytes = ((BytesRef) fieldsData).bytes;
}
encode(min, max, bytes);
}
@@ -85,7 +92,8 @@ public class InetAddressRange extends Field {
final byte[] maxEncoded = InetAddressPoint.encode(max);
// ensure min is lt max
if (Arrays.compareUnsigned(minEncoded, 0, BYTES, maxEncoded, 0, BYTES) > 0) {
- throw new IllegalArgumentException("min value cannot be greater than max value for InetAddressRange field");
+ throw new IllegalArgumentException(
+ "min value cannot be greater than max value for InetAddressRange field");
}
System.arraycopy(minEncoded, 0, bytes, 0, BYTES);
System.arraycopy(maxEncoded, 0, bytes, BYTES, BYTES);
@@ -93,30 +101,35 @@ public class InetAddressRange extends Field {
/** encode the min/max range and return the byte array */
private static byte[] encode(InetAddress min, InetAddress max) {
- byte[] b = new byte[BYTES*2];
+ byte[] b = new byte[BYTES * 2];
encode(min, max, b);
return b;
}
/**
* Create a query for matching indexed ip ranges that {@code INTERSECT} the defined range.
+ *
* @param field field name. must not be null.
* @param min range min value; provided as an {@code InetAddress}
* @param max range max value; provided as an {@code InetAddress}
* @return query for matching intersecting ranges (overlap, within, crosses, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
- public static Query newIntersectsQuery(String field, final InetAddress min, final InetAddress max) {
+ public static Query newIntersectsQuery(
+ String field, final InetAddress min, final InetAddress max) {
return newRelationQuery(field, min, max, QueryType.INTERSECTS);
}
/**
* Create a query for matching indexed ip ranges that {@code CONTAINS} the defined range.
+ *
* @param field field name. must not be null.
* @param min range min value; provided as an {@code InetAddress}
* @param max range max value; provided as an {@code InetAddress}
* @return query for matching intersecting ranges (overlap, within, crosses, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newContainsQuery(String field, final InetAddress min, final InetAddress max) {
return newRelationQuery(field, min, max, QueryType.CONTAINS);
@@ -124,11 +137,13 @@ public class InetAddressRange extends Field {
/**
* Create a query for matching indexed ip ranges that are {@code WITHIN} the defined range.
+ *
* @param field field name. must not be null.
* @param min range min value; provided as an {@code InetAddress}
* @param max range max value; provided as an {@code InetAddress}
* @return query for matching intersecting ranges (overlap, within, crosses, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newWithinQuery(String field, final InetAddress min, final InetAddress max) {
return newRelationQuery(field, min, max, QueryType.WITHIN);
@@ -136,18 +151,21 @@ public class InetAddressRange extends Field {
/**
* Create a query for matching indexed ip ranges that {@code CROSS} the defined range.
+ *
* @param field field name. must not be null.
* @param min range min value; provided as an {@code InetAddress}
* @param max range max value; provided as an {@code InetAddress}
* @return query for matching intersecting ranges (overlap, within, crosses, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newCrossesQuery(String field, final InetAddress min, final InetAddress max) {
return newRelationQuery(field, min, max, QueryType.CROSSES);
}
/** helper method for creating the desired relational query */
- private static Query newRelationQuery(String field, final InetAddress min, final InetAddress max, QueryType relation) {
+ private static Query newRelationQuery(
+ String field, final InetAddress min, final InetAddress max, QueryType relation) {
return new RangeFieldQuery(field, encode(min, max), 1, relation) {
@Override
protected String toString(byte[] ranges, int dimension) {
@@ -158,6 +176,7 @@ public class InetAddressRange extends Field {
/**
* Returns the String representation for the range at the given dimension
+ *
* @param ranges the encoded ranges, never null
* @param dimension the dimension of interest (not used for this field)
* @return The string representation for the range at the provided dimension
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 c138f50..dfde582 100644
--- a/lucene/core/src/java/org/apache/lucene/document/IntPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/IntPoint.java
@@ -18,7 +18,6 @@ package org.apache.lucene.document;
import java.util.Arrays;
import java.util.Collection;
-
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.PointInSetQuery;
import org.apache.lucene.search.PointRangeQuery;
@@ -26,21 +25,23 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-/**
- * An indexed {@code int} field for fast range filters. If you also
- * need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * Finding all documents within an N-dimensional shape or 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:
+/**
+ * An indexed {@code int} field for fast range filters. If you also need to store the value, you
+ * should add a separate {@link StoredField} instance.
+ *
+ * <p>Finding all documents within an N-dimensional shape or 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 #newExactQuery(String, int)} for matching an exact 1D point.
* <li>{@link #newSetQuery(String, int...)} for matching a set of 1D values.
* <li>{@link #newRangeQuery(String, int, int)} for matching a 1D range.
- * <li>{@link #newRangeQuery(String, int[], int[])} for matching points/ranges in n-dimensional space.
+ * <li>{@link #newRangeQuery(String, int[], int[])} for matching points/ranges in n-dimensional
+ * space.
* </ul>
+ *
* @see PointValues
*/
public final class IntPoint extends Field {
@@ -59,7 +60,14 @@ public final class IntPoint extends Field {
/** Change the values of this field */
public void setIntValues(int... point) {
if (type.pointDimensionCount() != point.length) {
- throw new IllegalArgumentException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot change to (incoming) " + point.length + " dimensions");
+ throw new IllegalArgumentException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot change to (incoming) "
+ + point.length
+ + " dimensions");
}
fieldsData = pack(point);
}
@@ -72,7 +80,12 @@ public final class IntPoint extends Field {
@Override
public Number numericValue() {
if (type.pointDimensionCount() != 1) {
- throw new IllegalStateException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot convert to a single numeric value");
+ throw new IllegalStateException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot convert to a single numeric value");
}
BytesRef bytes = (BytesRef) fieldsData;
assert bytes.length == Integer.BYTES;
@@ -80,7 +93,7 @@ public final class IntPoint extends Field {
}
/**
- * Pack an integer point into a BytesRef
+ * Pack an integer point into a BytesRef
*
* @param point int[] value
* @throws IllegalArgumentException is the value is null or of zero length
@@ -93,7 +106,7 @@ public final class IntPoint extends Field {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
byte[] packed = new byte[point.length * Integer.BYTES];
-
+
for (int dim = 0; dim < point.length; dim++) {
encodeDimension(point[dim], packed, dim * Integer.BYTES);
}
@@ -101,17 +114,17 @@ public final class IntPoint extends Field {
return new BytesRef(packed);
}
- /** Creates a new IntPoint, indexing the
- * provided N-dimensional int point.
+ /**
+ * Creates a new IntPoint, indexing the provided N-dimensional int point.
*
- * @param name field name
- * @param point int[] value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point int[] value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public IntPoint(String name, int... point) {
super(name, pack(point), getType(point.length));
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -131,26 +144,26 @@ public final class IntPoint extends Field {
result.append('>');
return result.toString();
}
-
+
// public helper methods (e.g. for queries)
-
+
/** Encode single integer dimension */
public static void encodeDimension(int value, byte dest[], int offset) {
NumericUtils.intToSortableBytes(value, dest, offset);
}
-
+
/** Decode single integer dimension */
public static int decodeDimension(byte value[], int offset) {
return NumericUtils.sortableBytesToInt(value, offset);
}
-
+
// static methods for generating queries
-
- /**
+
+ /**
* Create a query for matching an exact integer value.
- * <p>
- * This is for simple one-dimension points, for multidimensional points use
- * {@link #newRangeQuery(String, int[], int[])} instead.
+ *
+ * <p>This is for simple one-dimension points, for multidimensional points use {@link
+ * #newRangeQuery(String, int[], int[])} instead.
*
* @param field field name. must not be {@code null}.
* @param value exact value
@@ -161,17 +174,17 @@ public final class IntPoint extends Field {
return newRangeQuery(field, value, value);
}
- /**
+ /**
* Create a range query for integer values.
- * <p>
- * This is for simple one-dimension ranges, for multidimensional ranges use
- * {@link #newRangeQuery(String, int[], int[])} instead.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = Integer.MIN_VALUE} or {@code upperValue = Integer.MAX_VALUE}.
- * <p>
- * Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)}
- * or {@code Math.addExact(upperValue, -1)}.
+ *
+ * <p>This is for simple one-dimension ranges, for multidimensional ranges use {@link
+ * #newRangeQuery(String, int[], int[])} instead.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = Integer.MIN_VALUE} or {@code upperValue = Integer.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)} or
+ * {@code Math.addExact(upperValue, -1)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive).
@@ -180,28 +193,29 @@ public final class IntPoint extends Field {
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, int lowerValue, int upperValue) {
- return newRangeQuery(field, new int[] { lowerValue }, new int[] { upperValue });
+ return newRangeQuery(field, new int[] {lowerValue}, new int[] {upperValue});
}
- /**
+ /**
* Create a range query for n-dimensional integer values.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue[i] = Integer.MIN_VALUE} or {@code upperValue[i] = Integer.MAX_VALUE}.
- * <p>
- * Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue[i], 1)}
- * or {@code Math.addExact(upperValue[i], -1)}.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue[i] = Integer.MIN_VALUE} or {@code upperValue[i] = Integer.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue[i], 1)} or
+ * {@code Math.addExact(upperValue[i], -1)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be {@code null}.
* @param upperValue upper portion of the range (inclusive). must not be {@code null}.
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if {@code upperValue} is null,
- * or if {@code lowerValue.length != upperValue.length}
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if
+ * {@code upperValue} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, int[] lowerValue, int[] upperValue) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
- return new PointRangeQuery(field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
+ return new PointRangeQuery(
+ field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
@Override
protected String toString(int dimension, byte[] value) {
return Integer.toString(decodeDimension(value, 0));
@@ -210,8 +224,9 @@ public final class IntPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -223,22 +238,25 @@ public final class IntPoint extends Field {
final BytesRef encoded = new BytesRef(new byte[Integer.BYTES]);
- return new PointInSetQuery(field, 1, Integer.BYTES,
- new PointInSetQuery.Stream() {
+ return new PointInSetQuery(
+ field,
+ 1,
+ Integer.BYTES,
+ new PointInSetQuery.Stream() {
- int upto;
+ int upto;
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encodeDimension(sortedValues[upto], encoded.bytes, 0);
- upto++;
- return encoded;
- }
- }
- }) {
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encodeDimension(sortedValues[upto], encoded.bytes, 0);
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
assert value.length == Integer.BYTES;
@@ -246,10 +264,11 @@ public final class IntPoint extends Field {
}
};
}
-
+
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
diff --git a/lucene/core/src/java/org/apache/lucene/document/IntRange.java b/lucene/core/src/java/org/apache/lucene/document/IntRange.java
index b03fe8f..74ad82f 100644
--- a/lucene/core/src/java/org/apache/lucene/document/IntRange.java
+++ b/lucene/core/src/java/org/apache/lucene/document/IntRange.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.util.Objects;
-
import org.apache.lucene.document.RangeFieldQuery.QueryType;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
@@ -25,20 +24,25 @@ import org.apache.lucene.util.NumericUtils;
/**
* An indexed Integer Range field.
- * <p>
- * This field indexes dimensional ranges defined as min/max pairs. It supports
- * up to a maximum of 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single integer range,
- * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a tesseract.
- * <p>
- * Multiple values for the same field in one document is supported, and open ended ranges can be defined using
- * {@code Integer.MIN_VALUE} and {@code Integer.MAX_VALUE}.
*
- * <p>
- * This field defines the following static factory methods for common search operations over integer ranges:
+ * <p>This field indexes dimensional ranges defined as min/max pairs. It supports up to a maximum of
+ * 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single integer range,
+ * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a
+ * tesseract.
+ *
+ * <p>Multiple values for the same field in one document is supported, and open ended ranges can be
+ * defined using {@code Integer.MIN_VALUE} and {@code Integer.MAX_VALUE}.
+ *
+ * <p>This field defines the following static factory methods for common search operations over
+ * integer ranges:
+ *
* <ul>
- * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined search range.
- * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search range.
- * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search range.
+ * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined
+ * search range.
+ * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search
+ * range.
+ * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search
+ * range.
* </ul>
*/
public class IntRange extends Field {
@@ -65,30 +69,38 @@ public class IntRange extends Field {
FieldType ft = new FieldType();
// dimensions is set as 2*dimension size (min/max per dimension)
- ft.setDimensions(dimensions*2, BYTES);
+ ft.setDimensions(dimensions * 2, BYTES);
ft.freeze();
return ft;
}
/**
* Changes the values of the field.
+ *
* @param min array of min values. (accepts {@code Integer.NEGATIVE_INFINITY})
* @param max array of max values. (accepts {@code Integer.POSITIVE_INFINITY})
* @throws IllegalArgumentException if {@code min} or {@code max} is invalid
*/
public void setRangeValues(int[] min, int[] max) {
checkArgs(min, max);
- if (min.length*2 != type.pointDimensionCount() || max.length*2 != type.pointDimensionCount()) {
- throw new IllegalArgumentException("field (name=" + name + ") uses " + type.pointDimensionCount()/2
- + " dimensions; cannot change to (incoming) " + min.length + " dimensions");
+ if (min.length * 2 != type.pointDimensionCount()
+ || max.length * 2 != type.pointDimensionCount()) {
+ throw new IllegalArgumentException(
+ "field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount() / 2
+ + " dimensions; cannot change to (incoming) "
+ + min.length
+ + " dimensions");
}
final byte[] bytes;
if (fieldsData == null) {
- bytes = new byte[BYTES*2*min.length];
+ bytes = new byte[BYTES * 2 * min.length];
fieldsData = new BytesRef(bytes);
} else {
- bytes = ((BytesRef)fieldsData).bytes;
+ bytes = ((BytesRef) fieldsData).bytes;
}
verifyAndEncode(min, max, bytes);
}
@@ -106,32 +118,32 @@ public class IntRange extends Field {
}
}
- /**
- * Encodes the min, max ranges into a byte array
- */
+ /** Encodes the min, max ranges into a byte array */
static byte[] encode(int[] min, int[] max) {
checkArgs(min, max);
- byte[] b = new byte[BYTES*2*min.length];
+ byte[] b = new byte[BYTES * 2 * min.length];
verifyAndEncode(min, max, b);
return b;
}
/**
* encode the ranges into a sortable byte array ({@code Double.NaN} not allowed)
- * <p>
- * example for 4 dimensions (8 bytes per dimension value):
- * minD1 ... minD4 | maxD1 ... maxD4
+ *
+ * <p>example for 4 dimensions (8 bytes per dimension value): minD1 ... minD4 | maxD1 ... maxD4
*/
static void verifyAndEncode(int[] min, int[] max, byte[] bytes) {
- for (int d=0,i=0,j=min.length*BYTES; d<min.length; ++d, i+=BYTES, j+=BYTES) {
+ for (int d = 0, i = 0, j = min.length * BYTES; d < min.length; ++d, i += BYTES, j += BYTES) {
if (Double.isNaN(min[d])) {
- throw new IllegalArgumentException("invalid min value (" + Double.NaN + ")" + " in IntRange");
+ throw new IllegalArgumentException(
+ "invalid min value (" + Double.NaN + ")" + " in IntRange");
}
if (Double.isNaN(max[d])) {
- throw new IllegalArgumentException("invalid max value (" + Double.NaN + ")" + " in IntRange");
+ throw new IllegalArgumentException(
+ "invalid max value (" + Double.NaN + ")" + " in IntRange");
}
if (min[d] > max[d]) {
- throw new IllegalArgumentException("min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
+ throw new IllegalArgumentException(
+ "min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
}
encode(min[d], bytes, i);
encode(max[d], bytes, j);
@@ -145,43 +157,47 @@ public class IntRange extends Field {
/**
* Get the min value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded min value
*/
public int getMin(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMin(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMin(((BytesRef) fieldsData).bytes, dimension);
}
/**
* Get the max value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded max value
*/
public int getMax(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMax(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMax(((BytesRef) fieldsData).bytes, dimension);
}
/** decodes the min value (for the defined dimension) from the encoded input byte array */
static int decodeMin(byte[] b, int dimension) {
- int offset = dimension*BYTES;
+ int offset = dimension * BYTES;
return NumericUtils.sortableBytesToInt(b, offset);
}
/** decodes the max value (for the defined dimension) from the encoded input byte array */
static int decodeMax(byte[] b, int dimension) {
- int offset = b.length/2 + dimension*BYTES;
+ int offset = b.length / 2 + dimension * BYTES;
return NumericUtils.sortableBytesToInt(b, offset);
}
/**
* Create a query for matching indexed ranges that intersect the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Integer.MIN_VALUE})
* @param max array of max values. (accepts {@code Integer.MAX_VALUE})
* @return query for matching intersecting ranges (overlap, within, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newIntersectsQuery(String field, final int[] min, final int[] max) {
return newRelationQuery(field, min, max, QueryType.INTERSECTS);
@@ -189,11 +205,13 @@ public class IntRange extends Field {
/**
* Create a query for matching indexed ranges that contain the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Integer.MIN_VALUE})
* @param max array of max values. (accepts {@code Integer.MAX_VALUE})
* @return query for matching ranges that contain the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newContainsQuery(String field, final int[] min, final int[] max) {
return newRelationQuery(field, min, max, QueryType.CONTAINS);
@@ -201,32 +219,37 @@ public class IntRange extends Field {
/**
* Create a query for matching indexed ranges that are within the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Integer.MIN_VALUE})
* @param max array of max values. (accepts {@code Integer.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newWithinQuery(String field, final int[] min, final int[] max) {
return newRelationQuery(field, min, max, QueryType.WITHIN);
}
/**
- * Create a query for matching indexed ranges that cross the defined range.
- * A CROSSES is defined as any set of ranges that are not disjoint and not wholly contained by
- * the query. Effectively, its the complement of union(WITHIN, DISJOINT).
+ * Create a query for matching indexed ranges that cross the defined range. A CROSSES is defined
+ * as any set of ranges that are not disjoint and not wholly contained by the query. Effectively,
+ * its the complement of union(WITHIN, DISJOINT).
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Integer.MIN_VALUE})
* @param max array of max values. (accepts {@code Integer.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newCrossesQuery(String field, final int[] min, final int[] max) {
return newRelationQuery(field, min, max, QueryType.CROSSES);
}
/** helper method for creating the desired relational query */
- private static Query newRelationQuery(String field, final int[] min, final int[] max, QueryType relation) {
+ private static Query newRelationQuery(
+ String field, final int[] min, final int[] max, QueryType relation) {
checkArgs(min, max);
return new RangeFieldQuery(field, encode(min, max), min.length, relation) {
@Override
@@ -243,7 +266,7 @@ public class IntRange extends Field {
sb.append(" <");
sb.append(name);
sb.append(':');
- byte[] b = ((BytesRef)fieldsData).bytes;
+ byte[] b = ((BytesRef) fieldsData).bytes;
toString(b, 0);
for (int d = 0; d < type.pointDimensionCount() / 2; ++d) {
sb.append(' ');
@@ -256,12 +279,16 @@ public class IntRange extends Field {
/**
* Returns the String representation for the range at the given dimension
+ *
* @param ranges the encoded ranges, never null
* @param dimension the dimension of interest
* @return The string representation for the range at the provided dimension
*/
private static String toString(byte[] ranges, int dimension) {
- return "[" + Integer.toString(decodeMin(ranges, dimension)) + " : "
- + Integer.toString(decodeMax(ranges, dimension)) + "]";
+ return "["
+ + Integer.toString(decodeMin(ranges, dimension))
+ + " : "
+ + Integer.toString(decodeMax(ranges, dimension))
+ + "]";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/IntRangeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/IntRangeDocValuesField.java
index f23d152..ece6c49 100644
--- a/lucene/core/src/java/org/apache/lucene/document/IntRangeDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/IntRangeDocValuesField.java
@@ -20,10 +20,10 @@ package org.apache.lucene.document;
import org.apache.lucene.search.Query;
/**
- * DocValues field for IntRange. This is a single valued field per document
- * due to being an extension of BinaryDocValuesField.
+ * DocValues field for IntRange. This is a single valued field per document due to being an
+ * extension of BinaryDocValuesField.
*/
-public class IntRangeDocValuesField extends BinaryRangeDocValuesField{
+public class IntRangeDocValuesField extends BinaryRangeDocValuesField {
final String field;
final int[] min;
final int[] max;
@@ -55,22 +55,23 @@ public class IntRangeDocValuesField extends BinaryRangeDocValuesField{
return max[dimension];
}
- private static Query newSlowRangeQuery(String field, final int[] min, final int[] max,
- RangeFieldQuery.QueryType queryType) {
+ private static Query newSlowRangeQuery(
+ String field, final int[] min, final int[] max, RangeFieldQuery.QueryType queryType) {
checkArgs(min, max);
return new IntRangeSlowRangeQuery(field, min, max, queryType);
}
- /** Create a new range query that finds all ranges that intersect using doc values.
- * NOTE: This doesn't leverage indexing and may be slow.
- * @see IntRange#newIntersectsQuery */
+ /**
+ * Create a new range query that finds all ranges that intersect using doc values. NOTE: This
+ * doesn't leverage indexing and may be slow.
+ *
+ * @see IntRange#newIntersectsQuery
+ */
public static Query newSlowIntersectsQuery(String field, final int[] min, final int[] max) {
return newSlowRangeQuery(field, min, max, RangeFieldQuery.QueryType.INTERSECTS);
}
- /**
- * validate the arguments
- */
+ /** validate the arguments */
private static void checkArgs(final int[] min, final int[] max) {
if (min == null || max == null || min.length == 0 || max.length == 0) {
throw new IllegalArgumentException("min/max range values cannot be null or empty");
@@ -81,7 +82,8 @@ public class IntRangeDocValuesField extends BinaryRangeDocValuesField{
for (int i = 0; i < min.length; i++) {
if (min[i] > max[i]) {
- throw new IllegalArgumentException("min should be less than max but min = " + min[i] + " and max = " + max[i]);
+ throw new IllegalArgumentException(
+ "min should be less than max but min = " + min[i] + " and max = " + max[i]);
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/IntRangeSlowRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/IntRangeSlowRangeQuery.java
index ed62108..cd0714a 100644
--- a/lucene/core/src/java/org/apache/lucene/document/IntRangeSlowRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/IntRangeSlowRangeQuery.java
@@ -19,7 +19,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryVisitor;
@@ -69,8 +68,7 @@ class IntRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
if (this.field.equals(field) == false) {
b.append(this.field).append(":");
}
- return b
- .append("[")
+ return b.append("[")
.append(Arrays.toString(min))
.append(" TO ")
.append(Arrays.toString(max))
@@ -89,4 +87,4 @@ class IntRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
IntRange.verifyAndEncode(min, max, result);
return result;
}
-}
\ No newline at end of file
+}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesBoxQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesBoxQuery.java
index 180caa5..3eaac0c 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesBoxQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesBoxQuery.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.io.IOException;
-
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.geo.GeoUtils;
import org.apache.lucene.index.DocValues;
@@ -40,7 +39,12 @@ final class LatLonDocValuesBoxQuery extends Query {
private final int minLatitude, maxLatitude, minLongitude, maxLongitude;
private final boolean crossesDateline;
- LatLonDocValuesBoxQuery(String field, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
+ LatLonDocValuesBoxQuery(
+ String field,
+ double minLatitude,
+ double maxLatitude,
+ double minLongitude,
+ double maxLongitude) {
GeoUtils.checkLatitude(minLatitude);
GeoUtils.checkLatitude(maxLatitude);
GeoUtils.checkLongitude(minLongitude);
@@ -76,12 +80,12 @@ final class LatLonDocValuesBoxQuery extends Query {
return false;
}
LatLonDocValuesBoxQuery other = (LatLonDocValuesBoxQuery) obj;
- return field.equals(other.field) &&
- crossesDateline == other.crossesDateline &&
- minLatitude == other.minLatitude &&
- maxLatitude == other.maxLatitude &&
- minLongitude == other.minLongitude &&
- maxLongitude == other.maxLongitude;
+ return field.equals(other.field)
+ && crossesDateline == other.crossesDateline
+ && minLatitude == other.minLatitude
+ && maxLatitude == other.maxLatitude
+ && minLongitude == other.minLongitude
+ && maxLongitude == other.maxLongitude;
}
@Override
@@ -104,7 +108,8 @@ final class LatLonDocValuesBoxQuery extends Query {
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
return new ConstantScoreWeight(this, boost) {
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
@@ -113,40 +118,41 @@ final class LatLonDocValuesBoxQuery extends Query {
return null;
}
- final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {
- @Override
- public boolean matches() throws IOException {
- for (int i = 0, count = values.docValueCount(); i < count; ++i) {
- final long value = values.nextValue();
- final int lat = (int) (value >>> 32);
- if (lat < minLatitude || lat > maxLatitude) {
- // not within latitude range
- continue;
- }
-
- final int lon = (int) (value & 0xFFFFFFFF);
- if (crossesDateline) {
- if (lon > maxLongitude && lon < minLongitude) {
- // not within longitude range
- continue;
- }
- } else {
- if (lon < minLongitude || lon > maxLongitude) {
- // not within longitude range
- continue;
+ final TwoPhaseIterator iterator =
+ new TwoPhaseIterator(values) {
+ @Override
+ public boolean matches() throws IOException {
+ for (int i = 0, count = values.docValueCount(); i < count; ++i) {
+ final long value = values.nextValue();
+ final int lat = (int) (value >>> 32);
+ if (lat < minLatitude || lat > maxLatitude) {
+ // not within latitude range
+ continue;
+ }
+
+ final int lon = (int) (value & 0xFFFFFFFF);
+ if (crossesDateline) {
+ if (lon > maxLongitude && lon < minLongitude) {
+ // not within longitude range
+ continue;
+ }
+ } else {
+ if (lon < minLongitude || lon > maxLongitude) {
+ // not within longitude range
+ continue;
+ }
+ }
+
+ return true;
}
+ return false;
}
- return true;
- }
- return false;
- }
-
- @Override
- public float matchCost() {
- return 5; // 5 comparisons
- }
- };
+ @Override
+ public float matchCost() {
+ return 5; // 5 comparisons
+ }
+ };
return new ConstantScoreScorer(this, boost, scoreMode, iterator);
}
@@ -154,8 +160,6 @@ final class LatLonDocValuesBoxQuery extends Query {
public boolean isCacheable(LeafReaderContext ctx) {
return DocValues.isCacheable(ctx, field);
}
-
};
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesField.java
index e263f78..8c80363 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesField.java
@@ -33,55 +33,63 @@ import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
-/**
+/**
* An per-document location field.
- * <p>
- * Sorting by distance is efficient. Multiple values for the same field in one document
- * is allowed.
- * <p>
- * This field defines static factory methods for common operations:
+ *
+ * <p>Sorting by distance is efficient. Multiple values for the same field in one document is
+ * allowed.
+ *
+ * <p>This field defines static factory methods for common operations:
+ *
* <ul>
- * <li>{@link #newDistanceSort newDistanceSort()} for ordering documents by distance from a specified location.
+ * <li>{@link #newDistanceSort newDistanceSort()} for ordering documents by distance from a
+ * specified location.
* </ul>
- * <p>
- * If you also need query operations, you should add a separate {@link LatLonPoint} instance.
- * If you also need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * <b>WARNING</b>: Values are indexed with some loss of precision from the
- * original {@code double} values (4.190951585769653E-8 for the latitude component
- * and 8.381903171539307E-8 for longitude).
+ *
+ * <p>If you also need query operations, you should add a separate {@link LatLonPoint} instance. If
+ * you also need to store the value, you should add a separate {@link StoredField} instance.
+ *
+ * <p><b>WARNING</b>: Values are indexed with some loss of precision from the original {@code
+ * double} values (4.190951585769653E-8 for the latitude component and 8.381903171539307E-8 for
+ * longitude).
+ *
* @see LatLonPoint
*/
public class LatLonDocValuesField extends Field {
/**
* Type for a LatLonDocValuesField
- * <p>
- * Each value stores a 64-bit long where the upper 32 bits are the encoded latitude,
- * and the lower 32 bits are the encoded longitude.
+ *
+ * <p>Each value stores a 64-bit long where the upper 32 bits are the encoded latitude, and the
+ * lower 32 bits are the encoded longitude.
+ *
* @see org.apache.lucene.geo.GeoEncodingUtils#decodeLatitude(int)
* @see org.apache.lucene.geo.GeoEncodingUtils#decodeLongitude(int)
*/
public static final FieldType TYPE = new FieldType();
+
static {
TYPE.setDocValuesType(DocValuesType.SORTED_NUMERIC);
TYPE.freeze();
}
-
- /**
+
+ /**
* Creates a new LatLonDocValuesField with the specified latitude and longitude
+ *
* @param name field name
* @param latitude latitude value: must be within standard +/-90 coordinate bounds.
* @param longitude longitude value: must be within standard +/-180 coordinate bounds.
- * @throws IllegalArgumentException if the field name is null or latitude or longitude are out of bounds
+ * @throws IllegalArgumentException if the field name is null or latitude or longitude are out of
+ * bounds
*/
public LatLonDocValuesField(String name, double latitude, double longitude) {
super(name, TYPE);
setLocationValue(latitude, longitude);
}
-
+
/**
* Change the values of this field
+ *
* @param latitude latitude value: must be within standard +/-90 coordinate bounds.
* @param longitude longitude value: must be within standard +/-180 coordinate bounds.
* @throws IllegalArgumentException if latitude or longitude are out of bounds
@@ -89,19 +97,28 @@ public class LatLonDocValuesField extends Field {
public void setLocationValue(double latitude, double longitude) {
int latitudeEncoded = encodeLatitude(latitude);
int longitudeEncoded = encodeLongitude(longitude);
- fieldsData = Long.valueOf((((long)latitudeEncoded) << 32) | (longitudeEncoded & 0xFFFFFFFFL));
+ fieldsData = Long.valueOf((((long) latitudeEncoded) << 32) | (longitudeEncoded & 0xFFFFFFFFL));
}
- /** helper: checks a fieldinfo and throws exception if its definitely not a LatLonDocValuesField */
+ /**
+ * helper: checks a fieldinfo and throws exception if its definitely not a LatLonDocValuesField
+ */
static void checkCompatible(FieldInfo fieldInfo) {
- // dv properties could be "unset", if you e.g. used only StoredField with this same name in the segment.
- if (fieldInfo.getDocValuesType() != DocValuesType.NONE && fieldInfo.getDocValuesType() != TYPE.docValuesType()) {
- throw new IllegalArgumentException("field=\"" + fieldInfo.name + "\" was indexed with docValuesType=" + fieldInfo.getDocValuesType() +
- " but this type has docValuesType=" + TYPE.docValuesType() +
- ", is the field really a LatLonDocValuesField?");
+ // dv properties could be "unset", if you e.g. used only StoredField with this same name in the
+ // segment.
+ if (fieldInfo.getDocValuesType() != DocValuesType.NONE
+ && fieldInfo.getDocValuesType() != TYPE.docValuesType()) {
+ throw new IllegalArgumentException(
+ "field=\""
+ + fieldInfo.name
+ + "\" was indexed with docValuesType="
+ + fieldInfo.getDocValuesType()
+ + " but this type has docValuesType="
+ + TYPE.docValuesType()
+ + ", is the field really a LatLonDocValuesField?");
}
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -110,10 +127,10 @@ public class LatLonDocValuesField extends Field {
result.append(name);
result.append(':');
- long currentValue = (Long)fieldsData;
- result.append(decodeLatitude((int)(currentValue >> 32)));
+ long currentValue = (Long) fieldsData;
+ result.append(decodeLatitude((int) (currentValue >> 32)));
result.append(',');
- result.append(decodeLongitude((int)(currentValue & 0xFFFFFFFF)));
+ result.append(decodeLongitude((int) (currentValue & 0xFFFFFFFF)));
result.append('>');
return result.toString();
@@ -121,15 +138,16 @@ public class LatLonDocValuesField extends Field {
/**
* Creates a SortField for sorting by distance from a location.
- * <p>
- * This sort orders documents by ascending distance from the location. The value returned in {@link FieldDoc} for
- * the hits contains a Double instance with the distance in meters.
- * <p>
- * If a document is missing the field, then by default it is treated as having {@link Double#POSITIVE_INFINITY} distance
- * (missing values sort last).
- * <p>
- * If a document contains multiple values for the field, the <i>closest</i> distance to the location is used.
- *
+ *
+ * <p>This sort orders documents by ascending distance from the location. The value returned in
+ * {@link FieldDoc} for the hits contains a Double instance with the distance in meters.
+ *
+ * <p>If a document is missing the field, then by default it is treated as having {@link
+ * Double#POSITIVE_INFINITY} distance (missing values sort last).
+ *
+ * <p>If a document contains multiple values for the field, the <i>closest</i> distance to the
+ * location is used.
+ *
* @param field field name. must not be null.
* @param latitude latitude at the center: must be within standard +/-90 coordinate bounds.
* @param longitude longitude at the center: must be within standard +/-180 coordinate bounds.
@@ -141,15 +159,21 @@ public class LatLonDocValuesField extends Field {
}
/**
- * Create a query for matching a bounding box using doc values.
- * This query is usually slow as it does not use an index structure and needs
- * to verify documents one-by-one in order to know whether they match. It is
- * best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
+ * Create a query for matching a bounding box using doc values. This query is usually slow as it
+ * does not use an index structure and needs to verify documents one-by-one in order to know
+ * whether they match. It is best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
* {@link LatLonPoint#newBoxQuery}.
*/
- public static Query newSlowBoxQuery(String field, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
- // exact double values of lat=90.0D and lon=180.0D must be treated special as they are not represented in the encoding
- // and should not drag in extra bogus junk! TODO: should encodeCeil just throw ArithmeticException to be less trappy here?
+ public static Query newSlowBoxQuery(
+ String field,
+ double minLatitude,
+ double maxLatitude,
+ double minLongitude,
+ double maxLongitude) {
+ // exact double values of lat=90.0D and lon=180.0D must be treated special as they are not
+ // represented in the encoding
+ // and should not drag in extra bogus junk! TODO: should encodeCeil just throw
+ // ArithmeticException to be less trappy here?
if (minLatitude == 90.0) {
// range cannot match as 90.0 can never exist
return new MatchNoDocsQuery("LatLonDocValuesField.newBoxQuery with minLatitude=90.0");
@@ -157,7 +181,8 @@ public class LatLonDocValuesField extends Field {
if (minLongitude == 180.0) {
if (maxLongitude == 180.0) {
// range cannot match as 180.0 can never exist
- return new MatchNoDocsQuery("LatLonDocValuesField.newBoxQuery with minLongitude=maxLongitude=180.0");
+ return new MatchNoDocsQuery(
+ "LatLonDocValuesField.newBoxQuery with minLongitude=maxLongitude=180.0");
} else if (maxLongitude < minLongitude) {
// encodeCeil() with dateline wrapping!
minLongitude = -180.0;
@@ -167,48 +192,54 @@ public class LatLonDocValuesField extends Field {
}
/**
- * Create a query for matching points within the specified distance of the supplied location.
- * This query is usually slow as it does not use an index structure and needs
- * to verify documents one-by-one in order to know whether they match. It is
- * best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
- * {@link LatLonPoint#newDistanceQuery}.
+ * Create a query for matching points within the specified distance of the supplied location. This
+ * query is usually slow as it does not use an index structure and needs to verify documents
+ * one-by-one in order to know whether they match. It is best used wrapped in an {@link
+ * IndexOrDocValuesQuery} alongside a {@link LatLonPoint#newDistanceQuery}.
+ *
* @param field field name. must not be null.
* @param latitude latitude at the center: must be within standard +/-90 coordinate bounds.
* @param longitude longitude at the center: must be within standard +/-180 coordinate bounds.
- * @param radiusMeters maximum distance from the center in meters: must be non-negative and finite.
+ * @param radiusMeters maximum distance from the center in meters: must be non-negative and
+ * finite.
* @return query matching points within this distance
- * @throws IllegalArgumentException if {@code field} is null, location has invalid coordinates, or radius is invalid.
+ * @throws IllegalArgumentException if {@code field} is null, location has invalid coordinates, or
+ * radius is invalid.
*/
- public static Query newSlowDistanceQuery(String field, double latitude, double longitude, double radiusMeters) {
+ public static Query newSlowDistanceQuery(
+ String field, double latitude, double longitude, double radiusMeters) {
Circle circle = new Circle(latitude, longitude, radiusMeters);
return newSlowGeometryQuery(field, circle);
}
/**
- * Create a query for matching points within the supplied polygons.
- * This query is usually slow as it does not use an index structure and needs
- * to verify documents one-by-one in order to know whether they match. It is
- * best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
+ * Create a query for matching points within the supplied polygons. This query is usually slow as
+ * it does not use an index structure and needs to verify documents one-by-one in order to know
+ * whether they match. It is best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
* {@link LatLonPoint#newPolygonQuery(String, Polygon...)}.
+ *
* @param field field name. must not be null.
* @param polygons array of polygons. must not be null or empty.
* @return query matching points within the given polygons.
- * @throws IllegalArgumentException if {@code field} is null or polygons is empty or contain a null polygon.
+ * @throws IllegalArgumentException if {@code field} is null or polygons is empty or contain a
+ * null polygon.
*/
public static Query newSlowPolygonQuery(String field, Polygon... polygons) {
return newSlowGeometryQuery(field, polygons);
}
/**
- * Create a query for matching points within the supplied geometries. Line geometries are not supported.
- * This query is usually slow as it does not use an index structure and needs
- * to verify documents one-by-one in order to know whether they match. It is
- * best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
- * {@link LatLonPoint#newGeometryQuery(String, LatLonGeometry...)}.
+ * Create a query for matching points within the supplied geometries. Line geometries are not
+ * supported. This query is usually slow as it does not use an index structure and needs to verify
+ * documents one-by-one in order to know whether they match. It is best used wrapped in an {@link
+ * IndexOrDocValuesQuery} alongside a {@link LatLonPoint#newGeometryQuery(String,
+ * LatLonGeometry...)}.
+ *
* @param field field name. must not be null.
* @param latLonGeometries array of LatLonGeometries. must not be null or empty.
* @return query matching points within the given polygons.
- * @throws IllegalArgumentException if {@code field} is null, {@code latLonGeometries} is null, empty or contain a null or line geometry.
+ * @throws IllegalArgumentException if {@code field} is null, {@code latLonGeometries} is null,
+ * empty or contain a null or line geometry.
*/
public static Query newSlowGeometryQuery(String field, LatLonGeometry... latLonGeometries) {
if (latLonGeometries.length == 1 && latLonGeometries[0] instanceof Rectangle) {
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesPointInGeometryQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesPointInGeometryQuery.java
index 04cb612..5bb1550 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesPointInGeometryQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonDocValuesPointInGeometryQuery.java
@@ -17,6 +17,8 @@
package org.apache.lucene.document;
+import java.io.IOException;
+import java.util.Arrays;
import org.apache.lucene.geo.Component2D;
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.geo.LatLonGeometry;
@@ -34,16 +36,12 @@ import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TwoPhaseIterator;
import org.apache.lucene.search.Weight;
-import java.io.IOException;
-import java.util.Arrays;
-
/** Geometry query for {@link LatLonDocValuesField}. */
public class LatLonDocValuesPointInGeometryQuery extends Query {
private final String field;
private final LatLonGeometry[] geometries;
-
LatLonDocValuesPointInGeometryQuery(String field, LatLonGeometry... geometries) {
if (field == null) {
throw new IllegalArgumentException("field must not be null");
@@ -59,7 +57,8 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
throw new IllegalArgumentException("geometries[" + i + "] must not be null");
}
if (geometries[i] instanceof Line) {
- throw new IllegalArgumentException("LatLonDocValuesPointInGeometryQuery does not support queries with line geometries");
+ throw new IllegalArgumentException(
+ "LatLonDocValuesPointInGeometryQuery does not support queries with line geometries");
}
}
this.field = field;
@@ -83,8 +82,7 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
return false;
}
LatLonDocValuesPointInGeometryQuery other = (LatLonDocValuesPointInGeometryQuery) obj;
- return field.equals(other.field) &&
- Arrays.equals(geometries, other.geometries);
+ return field.equals(other.field) && Arrays.equals(geometries, other.geometries);
}
@Override
@@ -103,7 +101,8 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
final Component2D tree = LatLonGeometry.create(geometries);
if (tree.getMinY() > tree.getMaxY()) {
@@ -122,10 +121,11 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
};
}
- final GeoEncodingUtils.Component2DPredicate component2DPredicate = GeoEncodingUtils.createComponentPredicate(tree);
-
+ final GeoEncodingUtils.Component2DPredicate component2DPredicate =
+ GeoEncodingUtils.createComponentPredicate(tree);
+
return new ConstantScoreWeight(this, boost) {
-
+
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
@@ -133,26 +133,27 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
return null;
}
- final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {
+ final TwoPhaseIterator iterator =
+ new TwoPhaseIterator(values) {
+
+ @Override
+ public boolean matches() throws IOException {
+ for (int i = 0, count = values.docValueCount(); i < count; ++i) {
+ final long value = values.nextValue();
+ final int lat = (int) (value >>> 32);
+ final int lon = (int) (value & 0xFFFFFFFF);
+ if (component2DPredicate.test(lat, lon)) {
+ return true;
+ }
+ }
+ return false;
+ }
- @Override
- public boolean matches() throws IOException {
- for (int i = 0, count = values.docValueCount(); i < count; ++i) {
- final long value = values.nextValue();
- final int lat = (int) (value >>> 32);
- final int lon = (int) (value & 0xFFFFFFFF);
- if (component2DPredicate.test(lat, lon)) {
- return true;
+ @Override
+ public float matchCost() {
+ return 1000f; // TODO: what should it be?
}
- }
- return false;
- }
-
- @Override
- public float matchCost() {
- return 1000f; // TODO: what should it be?
- }
- };
+ };
return new ConstantScoreScorer(this, boost, scoreMode, iterator);
}
@@ -160,7 +161,6 @@ public class LatLonDocValuesPointInGeometryQuery extends Query {
public boolean isCacheable(LeafReaderContext ctx) {
return DocValues.isCacheable(ctx, field);
}
-
};
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPoint.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPoint.java
index 7dfb5a0..06de3cf 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPoint.java
@@ -16,6 +16,13 @@
*/
package org.apache.lucene.document;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitudeCeil;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitudeCeil;
+
import org.apache.lucene.geo.Circle;
import org.apache.lucene.geo.LatLonGeometry;
import org.apache.lucene.geo.Polygon;
@@ -23,8 +30,8 @@ import org.apache.lucene.geo.Rectangle;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.search.BooleanClause;
-import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
@@ -33,56 +40,58 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitudeCeil;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitudeCeil;
-
-/**
+/**
* An indexed location field.
- * <p>
- * 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 common operations:
+ *
+ * <p>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 common operations:
+ *
* <ul>
* <li>{@link #newBoxQuery newBoxQuery()} for matching points within a bounding box.
- * <li>{@link #newDistanceQuery newDistanceQuery()} for matching points within a specified distance.
+ * <li>{@link #newDistanceQuery newDistanceQuery()} for matching points within a specified
+ * distance.
* <li>{@link #newPolygonQuery newPolygonQuery()} for matching points within an arbitrary polygon.
- * <li>{@link #newGeometryQuery newGeometryQuery()} for matching points within an arbitrary geometry collection.
+ * <li>{@link #newGeometryQuery newGeometryQuery()} for matching points within an arbitrary
+ * geometry collection.
* </ul>
- * <p>
- * If you also need per-document operations such as sort by distance, add a separate {@link LatLonDocValuesField} instance.
- * If you also need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * <b>WARNING</b>: Values are indexed with some loss of precision from the
- * original {@code double} values (4.190951585769653E-8 for the latitude component
- * and 8.381903171539307E-8 for longitude).
+ *
+ * <p>If you also need per-document operations such as sort by distance, add a separate {@link
+ * LatLonDocValuesField} instance. If you also need to store the value, you should add a separate
+ * {@link StoredField} instance.
+ *
+ * <p><b>WARNING</b>: Values are indexed with some loss of precision from the original {@code
+ * double} values (4.190951585769653E-8 for the latitude component and 8.381903171539307E-8 for
+ * longitude).
+ *
* @see PointValues
* @see LatLonDocValuesField
*/
-// 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".
+// 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 {
/** LatLonPoint is encoded as integer values so number of bytes is 4 */
public static final int BYTES = Integer.BYTES;
/**
* Type for an indexed LatLonPoint
- * <p>
- * Each point stores two dimensions with 4 bytes per dimension.
+ *
+ * <p>Each point stores two dimensions with 4 bytes per dimension.
*/
public static final FieldType TYPE = new FieldType();
+
static {
TYPE.setDimensions(2, Integer.BYTES);
TYPE.freeze();
}
-
+
/**
* Change the values of this field
+ *
* @param latitude latitude value: must be within standard +/-90 coordinate bounds.
* @param longitude longitude value: must be within standard +/-180 coordinate bounds.
* @throws IllegalArgumentException if latitude or longitude are out of bounds
@@ -103,12 +112,14 @@ public class LatLonPoint extends Field {
NumericUtils.intToSortableBytes(longitudeEncoded, bytes, Integer.BYTES);
}
- /**
+ /**
* Creates a new LatLonPoint with the specified latitude and longitude
+ *
* @param name field name
* @param latitude latitude value: must be within standard +/-90 coordinate bounds.
* @param longitude longitude value: must be within standard +/-180 coordinate bounds.
- * @throws IllegalArgumentException if the field name is null or latitude or longitude are out of bounds
+ * @throws IllegalArgumentException if the field name is null or latitude or longitude are out of
+ * bounds
*/
public LatLonPoint(String name, double latitude, double longitude) {
super(name, TYPE);
@@ -131,7 +142,7 @@ public class LatLonPoint extends Field {
result.append('>');
return result.toString();
}
-
+
/** sugar encodes a single point as a byte array */
private static byte[] encode(double latitude, double longitude) {
byte[] bytes = new byte[2 * Integer.BYTES];
@@ -139,7 +150,7 @@ public class LatLonPoint extends Field {
NumericUtils.intToSortableBytes(encodeLongitude(longitude), bytes, Integer.BYTES);
return bytes;
}
-
+
/** sugar encodes a single point as a byte array, rounding values up */
private static byte[] encodeCeil(double latitude, double longitude) {
byte[] bytes = new byte[2 * Integer.BYTES];
@@ -150,16 +161,28 @@ public class LatLonPoint extends Field {
/** helper: checks a fieldinfo and throws exception if its definitely not a LatLonPoint */
static void checkCompatible(FieldInfo fieldInfo) {
- // point/dv properties could be "unset", if you e.g. used only StoredField with this same name in the segment.
- if (fieldInfo.getPointDimensionCount() != 0 && fieldInfo.getPointDimensionCount() != TYPE.pointDimensionCount()) {
- throw new IllegalArgumentException("field=\"" + fieldInfo.name + "\" was indexed with numDims=" + fieldInfo.getPointDimensionCount() +
- " but this point type has numDims=" + TYPE.pointDimensionCount() +
- ", is the field really a LatLonPoint?");
+ // point/dv properties could be "unset", if you e.g. used only StoredField with this same name
+ // in the segment.
+ if (fieldInfo.getPointDimensionCount() != 0
+ && fieldInfo.getPointDimensionCount() != TYPE.pointDimensionCount()) {
+ throw new IllegalArgumentException(
+ "field=\""
+ + fieldInfo.name
+ + "\" was indexed with numDims="
+ + fieldInfo.getPointDimensionCount()
+ + " but this point type has numDims="
+ + TYPE.pointDimensionCount()
+ + ", is the field really a LatLonPoint?");
}
if (fieldInfo.getPointNumBytes() != 0 && fieldInfo.getPointNumBytes() != TYPE.pointNumBytes()) {
- throw new IllegalArgumentException("field=\"" + fieldInfo.name + "\" was indexed with bytesPerDim=" + fieldInfo.getPointNumBytes() +
- " but this point type has bytesPerDim=" + TYPE.pointNumBytes() +
- ", is the field really a LatLonPoint?");
+ throw new IllegalArgumentException(
+ "field=\""
+ + fieldInfo.name
+ + "\" was indexed with bytesPerDim="
+ + fieldInfo.getPointNumBytes()
+ + " but this point type has bytesPerDim="
+ + TYPE.pointNumBytes()
+ + ", is the field really a LatLonPoint?");
}
}
@@ -167,8 +190,9 @@ public class LatLonPoint extends Field {
/**
* Create a query for matching a bounding box.
- * <p>
- * The box may cross over the dateline.
+ *
+ * <p>The box may cross over the dateline.
+ *
* @param field field name. must not be null.
* @param minLatitude latitude lower bound: must be within standard +/-90 coordinate bounds.
* @param maxLatitude latitude upper bound: must be within standard +/-90 coordinate bounds.
@@ -177,9 +201,16 @@ public class LatLonPoint extends Field {
* @return query matching points within this box
* @throws IllegalArgumentException if {@code field} is null, or the box has invalid coordinates.
*/
- public static Query newBoxQuery(String field, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
- // exact double values of lat=90.0D and lon=180.0D must be treated special as they are not represented in the encoding
- // and should not drag in extra bogus junk! TODO: should encodeCeil just throw ArithmeticException to be less trappy here?
+ public static Query newBoxQuery(
+ String field,
+ double minLatitude,
+ double maxLatitude,
+ double minLongitude,
+ double maxLongitude) {
+ // exact double values of lat=90.0D and lon=180.0D must be treated special as they are not
+ // represented in the encoding
+ // and should not drag in extra bogus junk! TODO: should encodeCeil just throw
+ // ArithmeticException to be less trappy here?
if (minLatitude == 90.0) {
// range cannot match as 90.0 can never exist
return new MatchNoDocsQuery("LatLonPoint.newBoxQuery with minLatitude=90.0");
@@ -197,7 +228,8 @@ public class LatLonPoint extends Field {
byte[] upper = encode(maxLatitude, maxLongitude);
// Crosses date line: we just rewrite into OR of two bboxes, with longitude as an open range:
if (maxLongitude < minLongitude) {
- // Disable coord here because a multi-valued doc could match both rects and get unfairly boosted:
+ // Disable coord here because a multi-valued doc could match both rects and get unfairly
+ // boosted:
BooleanQuery.Builder q = new BooleanQuery.Builder();
// E.g.: maxLon = -179, minLon = 179
@@ -217,7 +249,7 @@ public class LatLonPoint extends Field {
return newBoxInternal(field, lower, upper);
}
}
-
+
private static Query newBoxInternal(String field, byte[] min, byte[] max) {
return new PointRangeQuery(field, min, max, 2) {
@Override
@@ -232,22 +264,27 @@ public class LatLonPoint extends Field {
}
};
}
-
+
/**
* Create a query for matching points within the specified distance of the supplied location.
+ *
* @param field field name. must not be null.
* @param latitude latitude at the center: must be within standard +/-90 coordinate bounds.
* @param longitude longitude at the center: must be within standard +/-180 coordinate bounds.
- * @param radiusMeters maximum distance from the center in meters: must be non-negative and finite.
+ * @param radiusMeters maximum distance from the center in meters: must be non-negative and
+ * finite.
* @return query matching points within this distance
- * @throws IllegalArgumentException if {@code field} is null, location has invalid coordinates, or radius is invalid.
+ * @throws IllegalArgumentException if {@code field} is null, location has invalid coordinates, or
+ * radius is invalid.
*/
- public static Query newDistanceQuery(String field, double latitude, double longitude, double radiusMeters) {
+ public static Query newDistanceQuery(
+ String field, double latitude, double longitude, double radiusMeters) {
return new LatLonPointDistanceQuery(field, latitude, longitude, radiusMeters);
}
-
- /**
+
+ /**
* Create a query for matching one or more polygons.
+ *
* @param field field name. must not be null.
* @param polygons array of polygons. must not be null or empty
* @return query matching points within this polygon
@@ -260,10 +297,12 @@ public class LatLonPoint extends Field {
/**
* Create a query for matching one or more geometries. Line geometries are not supported.
+ *
* @param field field name. must not be null.
* @param latLonGeometries array of LatLonGeometries. must not be null or empty.
* @return query matching points within at least one geometry.
- * @throws IllegalArgumentException if {@code field} is null, {@code latLonGeometries} is null, empty or contain a null or line geometry.
+ * @throws IllegalArgumentException if {@code field} is null, {@code latLonGeometries} is null,
+ * empty or contain a null or line geometry.
* @see LatLonGeometry
*/
public static Query newGeometryQuery(String field, LatLonGeometry... latLonGeometries) {
@@ -281,25 +320,24 @@ public class LatLonPoint extends Field {
}
/**
- * Given a field that indexes point values into a {@link LatLonPoint}
- * and doc values into {@link LatLonDocValuesField}, this returns a query that scores
- * documents based on their haversine distance in meters to {@code (originLat, originLon)}:
- * {@code score = weight * pivotDistanceMeters / (pivotDistanceMeters + distance)}, ie.
- * score is in the {@code [0, weight]} range, is equal to {@code weight} when
- * the document's value is equal to {@code (originLat, originLon)} and is equal to
- * {@code weight/2} when the document's value is distant of
- * {@code pivotDistanceMeters} from {@code (originLat, originLon)}.
- * In case of multi-valued fields, only the closest point to {@code (originLat, originLon)}
- * will be considered.
- * This query is typically useful to boost results based on distance by adding
- * this query to a {@link Occur#SHOULD} clause of a {@link BooleanQuery}.
+ * Given a field that indexes point values into a {@link LatLonPoint} and doc values into {@link
+ * LatLonDocValuesField}, this returns a query that scores documents based on their haversine
+ * distance in meters to {@code (originLat, originLon)}: {@code score = weight *
+ * pivotDistanceMeters / (pivotDistanceMeters + distance)}, ie. score is in the {@code [0,
+ * weight]} range, is equal to {@code weight} when the document's value is equal to {@code
+ * (originLat, originLon)} and is equal to {@code weight/2} when the document's value is distant
+ * of {@code pivotDistanceMeters} from {@code (originLat, originLon)}. In case of multi-valued
+ * fields, only the closest point to {@code (originLat, originLon)} will be considered. This query
+ * is typically useful to boost results based on distance by adding this query to a {@link
+ * Occur#SHOULD} clause of a {@link BooleanQuery}.
*/
- public static Query newDistanceFeatureQuery(String field, float weight, double originLat, double originLon, double pivotDistanceMeters) {
- Query query = new LatLonPointDistanceFeatureQuery(field, originLat, originLon, pivotDistanceMeters);
+ public static Query newDistanceFeatureQuery(
+ String field, float weight, double originLat, double originLon, double pivotDistanceMeters) {
+ Query query =
+ new LatLonPointDistanceFeatureQuery(field, originLat, originLon, pivotDistanceMeters);
if (weight != 1f) {
query = new BoostQuery(query, weight);
}
return query;
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceComparator.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceComparator.java
index 10566b6..ef11ef5 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceComparator.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceComparator.java
@@ -16,8 +16,12 @@
*/
package org.apache.lucene.document;
-import java.io.IOException;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
+import java.io.IOException;
import org.apache.lucene.geo.Rectangle;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.FieldInfo;
@@ -30,16 +34,11 @@ import org.apache.lucene.search.Scorable;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.SloppyMath;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
-
/**
* Compares documents by distance from an origin point
- * <p>
- * When the least competitive item on the priority queue changes (setBottom), we recompute
- * a bounding box representing competitive distance to the top-N. Then in compareBottom, we can
+ *
+ * <p>When the least competitive item on the priority queue changes (setBottom), we recompute a
+ * bounding box representing competitive distance to the top-N. Then in compareBottom, we can
* quickly reject hits based on bounding box alone without computing distance for every element.
*/
class LatLonPointDistanceComparator extends FieldComparator<Double> implements LeafFieldComparator {
@@ -51,9 +50,9 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
double bottom;
double topValue;
SortedNumericDocValues currentDocs;
-
+
// current bounding box(es) for the bottom distance on the PQ.
- // these are pre-encoded with LatLonPoint's encoding and
+ // these are pre-encoded with LatLonPoint's encoding and
// used to exclude uncompetitive hits faster.
int minLon = Integer.MIN_VALUE;
int maxLon = Integer.MAX_VALUE;
@@ -69,13 +68,14 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
private long[] currentValues = new long[4];
private int valuesDocID = -1;
- public LatLonPointDistanceComparator(String field, double latitude, double longitude, int numHits) {
+ public LatLonPointDistanceComparator(
+ String field, double latitude, double longitude, int numHits) {
this.field = field;
this.latitude = latitude;
this.longitude = longitude;
this.values = new double[numHits];
}
-
+
@Override
public void setScorer(Scorable scorer) {}
@@ -83,7 +83,7 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
public int compare(int slot1, int slot2) {
return Double.compare(values[slot1], values[slot2]);
}
-
+
@Override
public void setBottom(int slot) {
bottom = values[slot];
@@ -92,7 +92,7 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
// boxes if comparator hits a worst case order (e.g. backwards distance order)
if (setBottomCounter < 1024 || (setBottomCounter & 0x3F) == 0x3F) {
Rectangle box = Rectangle.fromPointDistance(latitude, longitude, haversin2(bottom));
- // pre-encode our box to our integer encoding, so we don't have to decode
+ // pre-encode our box to our integer encoding, so we don't have to decode
// to double values for uncompetitive hits. This has some cost!
minLat = encodeLatitude(box.minLat);
maxLat = encodeLatitude(box.maxLat);
@@ -111,7 +111,7 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
}
setBottomCounter++;
}
-
+
@Override
public void setTopValue(Double value) {
topValue = value.doubleValue();
@@ -119,18 +119,19 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
private void setValues() throws IOException {
if (valuesDocID != currentDocs.docID()) {
- assert valuesDocID < currentDocs.docID(): " valuesDocID=" + valuesDocID + " vs " + currentDocs.docID();
+ assert valuesDocID < currentDocs.docID()
+ : " valuesDocID=" + valuesDocID + " vs " + currentDocs.docID();
valuesDocID = currentDocs.docID();
int count = currentDocs.docValueCount();
if (count > currentValues.length) {
currentValues = new long[ArrayUtil.oversize(count, Long.BYTES)];
}
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
currentValues[i] = currentDocs.nextValue();
}
}
}
-
+
@Override
public int compareBottom(int doc) throws IOException {
if (doc > currentDocs.docID()) {
@@ -149,11 +150,11 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
long encoded = currentValues[i];
// test bounding box
- int latitudeBits = (int)(encoded >> 32);
+ int latitudeBits = (int) (encoded >> 32);
if (latitudeBits < minLat || latitudeBits > maxLat) {
continue;
}
- int longitudeBits = (int)(encoded & 0xFFFFFFFF);
+ int longitudeBits = (int) (encoded & 0xFFFFFFFF);
if ((longitudeBits < minLon || longitudeBits > maxLon) && (longitudeBits < minLon2)) {
continue;
}
@@ -161,7 +162,12 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
// only compute actual distance if its inside "competitive bounding box"
double docLatitude = decodeLatitude(latitudeBits);
double docLongitude = decodeLongitude(longitudeBits);
- cmp = Math.max(cmp, Double.compare(bottom, SloppyMath.haversinSortKey(latitude, longitude, docLatitude, docLongitude)));
+ cmp =
+ Math.max(
+ cmp,
+ Double.compare(
+ bottom,
+ SloppyMath.haversinSortKey(latitude, longitude, docLatitude, docLongitude)));
// once we compete in the PQ, no need to continue.
if (cmp > 0) {
return cmp;
@@ -169,12 +175,12 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
}
return cmp;
}
-
+
@Override
public void copy(int slot, int doc) throws IOException {
values[slot] = sortKey(doc);
}
-
+
@Override
public LeafFieldComparator getLeafComparator(LeafReaderContext context) throws IOException {
LeafReader reader = context.reader();
@@ -186,17 +192,17 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
valuesDocID = -1;
return this;
}
-
+
@Override
public Double value(int slot) {
return Double.valueOf(haversin2(values[slot]));
}
-
+
@Override
public int compareTop(int doc) throws IOException {
return Double.compare(topValue, haversin2(sortKey(doc)));
}
-
+
// TODO: optimize for single-valued case?
// TODO: do all kinds of other optimizations!
double sortKey(int doc) throws IOException {
@@ -209,15 +215,19 @@ class LatLonPointDistanceComparator extends FieldComparator<Double> implements L
int numValues = currentDocs.docValueCount();
for (int i = 0; i < numValues; i++) {
long encoded = currentValues[i];
- double docLatitude = decodeLatitude((int)(encoded >> 32));
- double docLongitude = decodeLongitude((int)(encoded & 0xFFFFFFFF));
- minValue = Math.min(minValue, SloppyMath.haversinSortKey(latitude, longitude, docLatitude, docLongitude));
+ double docLatitude = decodeLatitude((int) (encoded >> 32));
+ double docLongitude = decodeLongitude((int) (encoded & 0xFFFFFFFF));
+ minValue =
+ Math.min(
+ minValue,
+ SloppyMath.haversinSortKey(latitude, longitude, docLatitude, docLongitude));
}
}
return minValue;
}
- // second half of the haversin calculation, used to convert results from haversin1 (used internally
+ // second half of the haversin calculation, used to convert results from haversin1 (used
+ // internally
// for sorting) for display purposes.
static double haversin2(double partial) {
if (Double.isInfinite(partial)) {
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceFeatureQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceFeatureQuery.java
index 846b353..5cf75e2 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceFeatureQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceFeatureQuery.java
@@ -19,7 +19,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.geo.GeoUtils;
import org.apache.lucene.geo.Rectangle;
@@ -43,7 +42,6 @@ import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.SloppyMath;
-
final class LatLonPointDistanceFeatureQuery extends Query {
private final String field;
@@ -51,7 +49,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
private final double originLon;
private final double pivotDistance;
- LatLonPointDistanceFeatureQuery(String field, double originLat, double originLon, double pivotDistance) {
+ LatLonPointDistanceFeatureQuery(
+ String field, double originLat, double originLon, double pivotDistance) {
this.field = Objects.requireNonNull(field);
GeoUtils.checkLatitude(originLat);
GeoUtils.checkLongitude(originLon);
@@ -72,15 +71,14 @@ final class LatLonPointDistanceFeatureQuery extends Query {
@Override
public final boolean equals(Object o) {
- return sameClassAs(o) &&
- equalsTo(getClass().cast(o));
+ return sameClassAs(o) && equalsTo(getClass().cast(o));
}
private boolean equalsTo(LatLonPointDistanceFeatureQuery other) {
- return Objects.equals(field, other.field) &&
- originLon == other.originLon &&
- originLat == other.originLat &&
- pivotDistance == other.pivotDistance;
+ return Objects.equals(field, other.field)
+ && originLon == other.originLon
+ && originLat == other.originLat
+ && pivotDistance == other.pivotDistance;
}
@Override
@@ -95,11 +93,21 @@ final class LatLonPointDistanceFeatureQuery extends Query {
@Override
public String toString(String field) {
- return getClass().getSimpleName() + "(field=" + field + ",originLat=" + originLat + ",originLon=" + originLon + ",pivotDistance=" + pivotDistance + ")";
+ return getClass().getSimpleName()
+ + "(field="
+ + field
+ + ",originLat="
+ + originLat
+ + ",originLon="
+ + originLon
+ + ",pivotDistance="
+ + pivotDistance
+ + ")";
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
return new Weight(this) {
@Override
@@ -111,16 +119,19 @@ final class LatLonPointDistanceFeatureQuery extends Query {
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
SortedNumericDocValues multiDocValues = DocValues.getSortedNumeric(context.reader(), field);
if (multiDocValues.advanceExact(doc) == false) {
- return Explanation.noMatch("Document " + doc + " doesn't have a value for field " + field);
+ return Explanation.noMatch(
+ "Document " + doc + " doesn't have a value for field " + field);
}
long encoded = selectValue(multiDocValues);
- int latitudeBits = (int)(encoded >> 32);
- int longitudeBits = (int)(encoded & 0xFFFFFFFF);
+ int latitudeBits = (int) (encoded >> 32);
+ int longitudeBits = (int) (encoded & 0xFFFFFFFF);
double lat = GeoEncodingUtils.decodeLatitude(latitudeBits);
double lon = GeoEncodingUtils.decodeLongitude(longitudeBits);
double distance = SloppyMath.haversinMeters(originLat, originLon, lat, lon);
float score = (float) (boost * (pivotDistance / (pivotDistance + distance)));
- return Explanation.match(score, "Distance score, computed as weight * pivotDistance / (pivotDistance + abs(distance)) from:",
+ return Explanation.match(
+ score,
+ "Distance score, computed as weight * pivotDistance / (pivotDistance + abs(distance)) from:",
Explanation.match(boost, "weight"),
Explanation.match(pivotDistance, "pivotDistance"),
Explanation.match(originLat, "originLat"),
@@ -154,7 +165,7 @@ final class LatLonPointDistanceFeatureQuery extends Query {
if (singleton != null) {
return singleton;
}
- return new NumericDocValues() {
+ return new NumericDocValues() {
long value;
@@ -192,7 +203,6 @@ final class LatLonPointDistanceFeatureQuery extends Query {
public long cost() {
return multiDocValues.cost();
}
-
};
}
@@ -203,7 +213,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
// No data on this segment
return null;
}
- final SortedNumericDocValues multiDocValues = DocValues.getSortedNumeric(context.reader(), field);
+ final SortedNumericDocValues multiDocValues =
+ DocValues.getSortedNumeric(context.reader(), field);
final NumericDocValues docValues = selectValues(multiDocValues);
final Weight weight = this;
@@ -211,7 +222,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
@Override
public Scorer get(long leadCost) throws IOException {
- return new DistanceScorer(weight, context.reader().maxDoc(), leadCost, boost, pointValues, docValues);
+ return new DistanceScorer(
+ weight, context.reader().maxDoc(), leadCost, boost, pointValues, docValues);
}
@Override
@@ -229,7 +241,6 @@ final class LatLonPointDistanceFeatureQuery extends Query {
}
return scorerSupplier.get(Long.MAX_VALUE);
}
-
};
}
@@ -238,8 +249,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
}
private double getDistanceKeyFromEncoded(long encoded) {
- int latitudeBits = (int)(encoded >> 32);
- int longitudeBits = (int)(encoded & 0xFFFFFFFF);
+ int latitudeBits = (int) (encoded >> 32);
+ int longitudeBits = (int) (encoded & 0xFFFFFFFF);
double lat = GeoEncodingUtils.decodeLatitude(latitudeBits);
double lon = GeoEncodingUtils.decodeLongitude(longitudeBits);
return SloppyMath.haversinSortKey(originLat, originLon, lat, lon);
@@ -256,8 +267,13 @@ final class LatLonPointDistanceFeatureQuery extends Query {
private final NumericDocValues docValues;
private double maxDistance = GeoUtils.EARTH_MEAN_RADIUS_METERS * Math.PI;
- protected DistanceScorer(Weight weight, int maxDoc, long leadCost, float boost,
- PointValues pointValues, NumericDocValues docValues) {
+ protected DistanceScorer(
+ Weight weight,
+ int maxDoc,
+ long leadCost,
+ float boost,
+ PointValues pointValues,
+ NumericDocValues docValues) {
super(weight);
this.maxDoc = maxDoc;
this.leadCost = leadCost;
@@ -279,9 +295,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
}
/**
- * Inverting the score computation is very hard due to all potential
- * rounding errors, so we binary search the maximum distance. The limit
- * is set to 1 meter.
+ * Inverting the score computation is very hard due to all potential rounding errors, so we
+ * binary search the maximum distance. The limit is set to 1 meter.
*/
private double computeMaxDistance(float minScore, double previousMaxDistance) {
assert score(0) >= minScore;
@@ -337,7 +352,7 @@ final class LatLonPointDistanceFeatureQuery extends Query {
@Override
public int advance(int target) throws IOException {
- return doc = it.advance(target);
+ return doc = it.advance(target);
}
};
}
@@ -349,7 +364,6 @@ final class LatLonPointDistanceFeatureQuery extends Query {
private int setMinCompetitiveScoreCounter = 0;
-
@Override
public void setMinCompetitiveScore(float minScore) throws IOException {
if (minScore > boost) {
@@ -370,8 +384,8 @@ final class LatLonPointDistanceFeatureQuery extends Query {
return;
}
- //Ideally we would be doing a distance query but that is too expensive so we approximate
- //with a box query which performs better.
+ // Ideally we would be doing a distance query but that is too expensive so we approximate
+ // with a box query which performs better.
Rectangle box = Rectangle.fromPointDistance(originLat, originLon, maxDistance);
final byte minLat[] = new byte[LatLonPoint.BYTES];
final byte maxLat[] = new byte[LatLonPoint.BYTES];
@@ -379,7 +393,6 @@ final class LatLonPointDistanceFeatureQuery extends Query {
final byte maxLon[] = new byte[LatLonPoint.BYTES];
final boolean crossDateLine = box.crossesDateline();
-
NumericUtils.intToSortableBytes(GeoEncodingUtils.encodeLatitude(box.minLat), minLat, 0);
NumericUtils.intToSortableBytes(GeoEncodingUtils.encodeLatitude(box.maxLat), maxLat, 0);
NumericUtils.intToSortableBytes(GeoEncodingUtils.encodeLongitude(box.minLon), minLon, 0);
@@ -387,89 +400,190 @@ final class LatLonPointDistanceFeatureQuery extends Query {
DocIdSetBuilder result = new DocIdSetBuilder(maxDoc);
final int doc = docID();
- IntersectVisitor visitor = new IntersectVisitor() {
-
- DocIdSetBuilder.BulkAdder adder;
+ IntersectVisitor visitor =
+ new IntersectVisitor() {
- @Override
- public void grow(int count) {
- adder = result.grow(count);
- }
+ DocIdSetBuilder.BulkAdder adder;
- @Override
- public void visit(int docID) {
- if (docID <= doc) {
- // Already visited or skipped
- return;
- }
- adder.add(docID);
- }
-
- @Override
- public void visit(int docID, byte[] packedValue) {
- if (docID <= doc) {
- // Already visited or skipped
- return;
- }
- if (Arrays.compareUnsigned(packedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES) > 0 ||
- Arrays.compareUnsigned(packedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES) < 0) {
- //Latitude out of range
- return;
- }
- if (crossDateLine) {
- if (Arrays.compareUnsigned(packedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) < 0 &&
- Arrays.compareUnsigned(packedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) > 0) {
- //Longitude out of range
- return;
+ @Override
+ public void grow(int count) {
+ adder = result.grow(count);
}
- } else {
- if (Arrays.compareUnsigned(packedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) > 0 ||
- Arrays.compareUnsigned(packedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) < 0) {
- //Longitude out of range
- return;
+ @Override
+ public void visit(int docID) {
+ if (docID <= doc) {
+ // Already visited or skipped
+ return;
+ }
+ adder.add(docID);
}
- }
- adder.add(docID);
- }
- @Override
- public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
-
- if (Arrays.compareUnsigned(minPackedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES) < 0) {
- return Relation.CELL_OUTSIDE_QUERY;
- }
- boolean crosses = Arrays.compareUnsigned(minPackedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES) < 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES) > 0;
-
- if (crossDateLine) {
- if (Arrays.compareUnsigned(minPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) > 0 &&
- Arrays.compareUnsigned(maxPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) < 0) {
- return Relation.CELL_OUTSIDE_QUERY;
+ @Override
+ public void visit(int docID, byte[] packedValue) {
+ if (docID <= doc) {
+ // Already visited or skipped
+ return;
+ }
+ if (Arrays.compareUnsigned(
+ packedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ packedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES)
+ < 0) {
+ // Latitude out of range
+ return;
+ }
+ if (crossDateLine) {
+ if (Arrays.compareUnsigned(
+ packedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0
+ && Arrays.compareUnsigned(
+ packedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0) {
+ // Longitude out of range
+ return;
+ }
+
+ } else {
+ if (Arrays.compareUnsigned(
+ packedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ packedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0) {
+ // Longitude out of range
+ return;
+ }
+ }
+ adder.add(docID);
}
- crosses |= Arrays.compareUnsigned(minPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) < 0 ||
- Arrays.compareUnsigned(maxPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) > 0;
- } else {
- if (Arrays.compareUnsigned(minPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) < 0) {
- return Relation.CELL_OUTSIDE_QUERY;
+ @Override
+ public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
+
+ if (Arrays.compareUnsigned(
+ minPackedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxPackedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES)
+ < 0) {
+ return Relation.CELL_OUTSIDE_QUERY;
+ }
+ boolean crosses =
+ Arrays.compareUnsigned(
+ minPackedValue, 0, LatLonPoint.BYTES, minLat, 0, LatLonPoint.BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ maxPackedValue, 0, LatLonPoint.BYTES, maxLat, 0, LatLonPoint.BYTES)
+ > 0;
+
+ if (crossDateLine) {
+ if (Arrays.compareUnsigned(
+ minPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0
+ && Arrays.compareUnsigned(
+ maxPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0) {
+ return Relation.CELL_OUTSIDE_QUERY;
+ }
+ crosses |=
+ Arrays.compareUnsigned(
+ minPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ maxPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0;
+
+ } else {
+ if (Arrays.compareUnsigned(
+ minPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0) {
+ return Relation.CELL_OUTSIDE_QUERY;
+ }
+ crosses |=
+ Arrays.compareUnsigned(
+ minPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ minLon,
+ 0,
+ LatLonPoint.BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ maxPackedValue,
+ LatLonPoint.BYTES,
+ 2 * LatLonPoint.BYTES,
+ maxLon,
+ 0,
+ LatLonPoint.BYTES)
+ > 0;
+ }
+ if (crosses) {
+ return Relation.CELL_CROSSES_QUERY;
+ } else {
+ return Relation.CELL_INSIDE_QUERY;
+ }
}
- crosses |= Arrays.compareUnsigned(minPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, minLon, 0, LatLonPoint.BYTES) < 0 ||
- Arrays.compareUnsigned(maxPackedValue, LatLonPoint.BYTES, 2 * LatLonPoint.BYTES, maxLon, 0, LatLonPoint.BYTES) > 0;
- }
- if (crosses) {
- return Relation.CELL_CROSSES_QUERY;
- } else {
- return Relation.CELL_INSIDE_QUERY;
- }
- }
- };
+ };
final long currentQueryCost = Math.min(leadCost, it.cost());
final long threshold = currentQueryCost >>> 3;
- long estimatedNumberOfMatches = pointValues.estimatePointCount(visitor); // runs in O(log(numPoints))
+ long estimatedNumberOfMatches =
+ pointValues.estimatePointCount(visitor); // runs in O(log(numPoints))
// TODO: what is the right factor compared to the current disi? Is 8 optimal?
if (estimatedNumberOfMatches >= threshold) {
// the new range is not selective enough to be worth materializing
@@ -478,6 +592,5 @@ final class LatLonPointDistanceFeatureQuery extends Query {
pointValues.intersect(visitor);
it = result.build().iterator();
}
-
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceQuery.java
index 79fabf3..bca9128 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointDistanceQuery.java
@@ -16,9 +16,13 @@
*/
package org.apache.lucene.document;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
+
import java.io.IOException;
import java.util.Arrays;
-
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.geo.GeoUtils;
import org.apache.lucene.geo.Rectangle;
@@ -43,21 +47,15 @@ import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.NumericUtils;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
-
-/**
- * Distance query for {@link LatLonPoint}.
- */
+/** Distance query for {@link LatLonPoint}. */
final class LatLonPointDistanceQuery extends Query {
final String field;
final double latitude;
final double longitude;
final double radiusMeters;
- public LatLonPointDistanceQuery(String field, double latitude, double longitude, double radiusMeters) {
+ public LatLonPointDistanceQuery(
+ String field, double latitude, double longitude, double radiusMeters) {
if (field == null) {
throw new IllegalArgumentException("field must not be null");
}
@@ -80,7 +78,8 @@ final class LatLonPointDistanceQuery extends Query {
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
Rectangle box = Rectangle.fromPointDistance(latitude, longitude, radiusMeters);
// create bounding box(es) for the distance range
// these are pre-encoded with LatLonPoint's encoding
@@ -115,7 +114,8 @@ final class LatLonPointDistanceQuery extends Query {
return new ConstantScoreWeight(this, boost) {
- final GeoEncodingUtils.DistancePredicate distancePredicate = GeoEncodingUtils.createDistancePredicate(latitude, longitude, radiusMeters);
+ final GeoEncodingUtils.DistancePredicate distancePredicate =
+ GeoEncodingUtils.createDistancePredicate(latitude, longitude, radiusMeters);
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
@@ -165,7 +165,7 @@ final class LatLonPointDistanceQuery extends Query {
// by computing the set of documents that do NOT match the range
final FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.set(0, reader.maxDoc());
- int[] cost = new int[]{reader.maxDoc()};
+ int[] cost = new int[] {reader.maxDoc()};
values.intersect(getInverseIntersectVisitor(result, cost));
final DocIdSetIterator iterator = new BitSetIterator(result, cost[0]);
return new ConstantScoreScorer(weight, score(), scoreMode, iterator);
@@ -183,20 +183,41 @@ final class LatLonPointDistanceQuery extends Query {
return cost;
}
};
-
}
private boolean matches(byte[] packedValue) {
// bounding box check
- if (Arrays.compareUnsigned(packedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(packedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES) < 0) {
+ if (Arrays.compareUnsigned(packedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0
+ || Arrays.compareUnsigned(packedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES)
+ < 0) {
// latitude out of bounding box range
return false;
}
- if ((Arrays.compareUnsigned(packedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, maxLon, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(packedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, minLon, 0, Integer.BYTES) < 0)
- && Arrays.compareUnsigned(packedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, minLon2, 0, Integer.BYTES) < 0) {
+ if ((Arrays.compareUnsigned(
+ packedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ maxLon,
+ 0,
+ Integer.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ packedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ minLon,
+ 0,
+ Integer.BYTES)
+ < 0)
+ && Arrays.compareUnsigned(
+ packedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ minLon2,
+ 0,
+ Integer.BYTES)
+ < 0) {
// longitude out of bounding box range
return false;
}
@@ -211,19 +232,43 @@ final class LatLonPointDistanceQuery extends Query {
// algorithm: we create a bounding box (two bounding boxes if we cross the dateline).
// 1. check our bounding box(es) first. if the subtree is entirely outside of those, bail.
- // 2. check if the subtree is disjoint. it may cross the bounding box but not intersect with circle
- // 3. see if the subtree is fully contained. if the subtree is enormous along the x axis, wrapping half way around the world, etc: then this can't work, just go to step 4.
+ // 2. check if the subtree is disjoint. it may cross the bounding box but not intersect with
+ // circle
+ // 3. see if the subtree is fully contained. if the subtree is enormous along the x axis,
+ // wrapping half way around the world, etc: then this can't work, just go to step 4.
// 4. recurse naively (subtrees crossing over circle edge)
private Relation relate(byte[] minPackedValue, byte[] maxPackedValue) {
- if (Arrays.compareUnsigned(minPackedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES) < 0) {
+ if (Arrays.compareUnsigned(minPackedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0
+ || Arrays.compareUnsigned(maxPackedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES)
+ < 0) {
// latitude out of bounding box range
return Relation.CELL_OUTSIDE_QUERY;
}
- if ((Arrays.compareUnsigned(minPackedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, maxLon, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, minLon, 0, Integer.BYTES) < 0)
- && Arrays.compareUnsigned(maxPackedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, minLon2, 0, Integer.BYTES) < 0) {
+ if ((Arrays.compareUnsigned(
+ minPackedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ maxLon,
+ 0,
+ Integer.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxPackedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ minLon,
+ 0,
+ Integer.BYTES)
+ < 0)
+ && Arrays.compareUnsigned(
+ maxPackedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ minLon2,
+ 0,
+ Integer.BYTES)
+ < 0) {
// longitude out of bounding box range
return Relation.CELL_OUTSIDE_QUERY;
}
@@ -233,12 +278,11 @@ final class LatLonPointDistanceQuery extends Query {
double latMax = decodeLatitude(maxPackedValue, 0);
double lonMax = decodeLongitude(maxPackedValue, Integer.BYTES);
- return GeoUtils.relate(latMin, latMax, lonMin, lonMax, latitude, longitude, sortKey, axisLat);
+ return GeoUtils.relate(
+ latMin, latMax, lonMin, lonMax, latitude, longitude, sortKey, axisLat);
}
- /**
- * Create a visitor that collects documents matching the range.
- */
+ /** Create a visitor that collects documents matching the range. */
private IntersectVisitor getIntersectVisitor(DocIdSetBuilder result) {
return new IntersectVisitor() {
@@ -278,9 +322,7 @@ final class LatLonPointDistanceQuery extends Query {
};
}
- /**
- * Create a visitor that clears documents that do NOT match the range.
- */
+ /** Create a visitor that clears documents that do NOT match the range. */
private IntersectVisitor getInverseIntersectVisitor(FixedBitSet result, int[] cost) {
return new IntersectVisitor() {
@@ -359,15 +401,14 @@ final class LatLonPointDistanceQuery extends Query {
@Override
public boolean equals(Object other) {
- return sameClassAs(other) &&
- equalsTo(getClass().cast(other));
+ return sameClassAs(other) && equalsTo(getClass().cast(other));
}
private boolean equalsTo(LatLonPointDistanceQuery other) {
- return field.equals(other.field) &&
- Double.doubleToLongBits(latitude) == Double.doubleToLongBits(other.latitude) &&
- Double.doubleToLongBits(longitude) == Double.doubleToLongBits(other.longitude) &&
- Double.doubleToLongBits(radiusMeters) == Double.doubleToLongBits(other.radiusMeters);
+ return field.equals(other.field)
+ && Double.doubleToLongBits(latitude) == Double.doubleToLongBits(other.latitude)
+ && Double.doubleToLongBits(longitude) == Double.doubleToLongBits(other.longitude)
+ && Double.doubleToLongBits(radiusMeters) == Double.doubleToLongBits(other.radiusMeters);
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointInGeometryQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointInGeometryQuery.java
index 2d749cc..66ad777 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointInGeometryQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointInGeometryQuery.java
@@ -16,6 +16,13 @@
*/
package org.apache.lucene.document;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
+
+import java.io.IOException;
+import java.util.Arrays;
import org.apache.lucene.geo.Component2D;
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.geo.LatLonGeometry;
@@ -39,20 +46,13 @@ import org.apache.lucene.search.Weight;
import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.NumericUtils;
-import java.io.IOException;
-import java.util.Arrays;
-
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
-
-/** Finds all previously indexed points that fall within the specified geometries.
+/**
+ * Finds all previously indexed points that fall within the specified geometries.
*
- * <p>The field must be indexed with using {@link LatLonPoint} added per document.
+ * <p>The field must be indexed with using {@link LatLonPoint} added per document.
*
- * @lucene.experimental */
-
+ * @lucene.experimental
+ */
final class LatLonPointInGeometryQuery extends Query {
final String field;
final LatLonGeometry[] geometries;
@@ -72,7 +72,8 @@ final class LatLonPointInGeometryQuery extends Query {
throw new IllegalArgumentException("geometries[" + i + "] must not be null");
}
if (geometries[i] instanceof Line) {
- throw new IllegalArgumentException("LatLonPointInGeometryQuery does not support queries with line geometries");
+ throw new IllegalArgumentException(
+ "LatLonPointInGeometryQuery does not support queries with line geometries");
}
}
this.field = field;
@@ -86,62 +87,86 @@ final class LatLonPointInGeometryQuery extends Query {
}
}
- private IntersectVisitor getIntersectVisitor(DocIdSetBuilder result, Component2D tree, GeoEncodingUtils.Component2DPredicate component2DPredicate,
- byte[] minLat, byte[] maxLat, byte[] minLon, byte[] maxLon) {
+ private IntersectVisitor getIntersectVisitor(
+ DocIdSetBuilder result,
+ Component2D tree,
+ GeoEncodingUtils.Component2DPredicate component2DPredicate,
+ byte[] minLat,
+ byte[] maxLat,
+ byte[] minLon,
+ byte[] maxLon) {
return new IntersectVisitor() {
- DocIdSetBuilder.BulkAdder adder;
+ DocIdSetBuilder.BulkAdder adder;
- @Override
- public void grow(int count) {
- adder = result.grow(count);
- }
+ @Override
+ public void grow(int count) {
+ adder = result.grow(count);
+ }
- @Override
- public void visit(int docID) {
- adder.add(docID);
- }
+ @Override
+ public void visit(int docID) {
+ adder.add(docID);
+ }
- @Override
- public void visit(int docID, byte[] packedValue) {
- if (component2DPredicate.test(NumericUtils.sortableBytesToInt(packedValue, 0),
- NumericUtils.sortableBytesToInt(packedValue, Integer.BYTES))) {
- visit(docID);
- }
- }
+ @Override
+ public void visit(int docID, byte[] packedValue) {
+ if (component2DPredicate.test(
+ NumericUtils.sortableBytesToInt(packedValue, 0),
+ NumericUtils.sortableBytesToInt(packedValue, Integer.BYTES))) {
+ visit(docID);
+ }
+ }
- @Override
- public void visit(DocIdSetIterator iterator, byte[] packedValue) throws IOException {
- if (component2DPredicate.test(NumericUtils.sortableBytesToInt(packedValue, 0),
- NumericUtils.sortableBytesToInt(packedValue, Integer.BYTES))) {
- int docID;
- while ((docID = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
- visit(docID);
- }
- }
+ @Override
+ public void visit(DocIdSetIterator iterator, byte[] packedValue) throws IOException {
+ if (component2DPredicate.test(
+ NumericUtils.sortableBytesToInt(packedValue, 0),
+ NumericUtils.sortableBytesToInt(packedValue, Integer.BYTES))) {
+ int docID;
+ while ((docID = iterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ visit(docID);
}
+ }
+ }
- @Override
- public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
- if (Arrays.compareUnsigned(minPackedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES) < 0 ||
- Arrays.compareUnsigned(minPackedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, maxLon, 0, Integer.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, Integer.BYTES, Integer.BYTES + Integer.BYTES, minLon, 0, Integer.BYTES) < 0) {
- // outside of global bounding box range
- return Relation.CELL_OUTSIDE_QUERY;
- }
+ @Override
+ public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
+ if (Arrays.compareUnsigned(minPackedValue, 0, Integer.BYTES, maxLat, 0, Integer.BYTES) > 0
+ || Arrays.compareUnsigned(maxPackedValue, 0, Integer.BYTES, minLat, 0, Integer.BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ minPackedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ maxLon,
+ 0,
+ Integer.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxPackedValue,
+ Integer.BYTES,
+ Integer.BYTES + Integer.BYTES,
+ minLon,
+ 0,
+ Integer.BYTES)
+ < 0) {
+ // outside of global bounding box range
+ return Relation.CELL_OUTSIDE_QUERY;
+ }
- double cellMinLat = decodeLatitude(minPackedValue, 0);
- double cellMinLon = decodeLongitude(minPackedValue, Integer.BYTES);
- double cellMaxLat = decodeLatitude(maxPackedValue, 0);
- double cellMaxLon = decodeLongitude(maxPackedValue, Integer.BYTES);
+ double cellMinLat = decodeLatitude(minPackedValue, 0);
+ double cellMinLon = decodeLongitude(minPackedValue, Integer.BYTES);
+ double cellMaxLat = decodeLatitude(maxPackedValue, 0);
+ double cellMaxLon = decodeLongitude(maxPackedValue, Integer.BYTES);
- return tree.relate(cellMinLon, cellMaxLon, cellMinLat, cellMaxLat);
- }
- };
+ return tree.relate(cellMinLon, cellMaxLon, cellMinLat, cellMaxLat);
+ }
+ };
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
final Component2D tree = LatLonGeometry.create(geometries);
if (tree.getMinY() > tree.getMaxY()) {
// encodeLatitudeCeil may cause minY to be > maxY iff
@@ -158,8 +183,10 @@ final class LatLonPointInGeometryQuery extends Query {
}
};
}
- final GeoEncodingUtils.Component2DPredicate component2DPredicate = GeoEncodingUtils.createComponentPredicate(tree);
- // bounding box over all geometries, this can speed up tree intersection/cheaply improve approximation for complex multi-geometries
+ final GeoEncodingUtils.Component2DPredicate component2DPredicate =
+ GeoEncodingUtils.createComponentPredicate(tree);
+ // bounding box over all geometries, this can speed up tree intersection/cheaply improve
+ // approximation for complex multi-geometries
final byte minLat[] = new byte[Integer.BYTES];
final byte maxLat[] = new byte[Integer.BYTES];
final byte minLon[] = new byte[Integer.BYTES];
@@ -191,7 +218,9 @@ final class LatLonPointInGeometryQuery extends Query {
long cost = -1;
DocIdSetBuilder result = new DocIdSetBuilder(reader.maxDoc(), values, field);
- final IntersectVisitor visitor = getIntersectVisitor(result, tree, component2DPredicate, minLat, maxLat, minLon, maxLon);
+ final IntersectVisitor visitor =
+ getIntersectVisitor(
+ result, tree, component2DPredicate, minLat, maxLat, minLon, maxLon);
@Override
public Scorer get(long leadCost) throws IOException {
@@ -202,7 +231,7 @@ final class LatLonPointInGeometryQuery extends Query {
@Override
public long cost() {
if (cost == -1) {
- // Computing the cost may be expensive, so only do it if necessary
+ // Computing the cost may be expensive, so only do it if necessary
cost = values.estimateDocCount(visitor);
assert cost >= 0;
}
@@ -225,7 +254,6 @@ final class LatLonPointInGeometryQuery extends Query {
return true;
}
};
-
}
/** Returns the query field */
@@ -249,13 +277,11 @@ final class LatLonPointInGeometryQuery extends Query {
@Override
public boolean equals(Object other) {
- return sameClassAs(other) &&
- equalsTo(getClass().cast(other));
+ return sameClassAs(other) && equalsTo(getClass().cast(other));
}
private boolean equalsTo(LatLonPointInGeometryQuery other) {
- return field.equals(other.field) &&
- Arrays.equals(geometries, other.geometries);
+ return field.equals(other.field) && Arrays.equals(geometries, other.geometries);
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointSortField.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointSortField.java
index 8d6f652..36f3935 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointSortField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointSortField.java
@@ -20,9 +20,7 @@ import org.apache.lucene.geo.GeoUtils;
import org.apache.lucene.search.FieldComparator;
import org.apache.lucene.search.SortField;
-/**
- * Sorts by distance from an origin location.
- */
+/** Sorts by distance from an origin location. */
final class LatLonPointSortField extends SortField {
final double latitude;
final double longitude;
@@ -38,7 +36,7 @@ final class LatLonPointSortField extends SortField {
this.longitude = longitude;
setMissingValue(Double.POSITIVE_INFINITY);
}
-
+
@Override
public FieldComparator<?> getComparator(int numHits, int sortPos) {
return new LatLonPointDistanceComparator(getField(), latitude, longitude, numHits);
@@ -52,11 +50,13 @@ final class LatLonPointSortField extends SortField {
@Override
public void setMissingValue(Object missingValue) {
if (Double.valueOf(Double.POSITIVE_INFINITY).equals(missingValue) == false) {
- throw new IllegalArgumentException("Missing value can only be Double.POSITIVE_INFINITY (missing values last), but got " + missingValue);
+ throw new IllegalArgumentException(
+ "Missing value can only be Double.POSITIVE_INFINITY (missing values last), but got "
+ + missingValue);
}
this.missingValue = missingValue;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
@@ -76,7 +76,8 @@ final class LatLonPointSortField extends SortField {
if (getClass() != obj.getClass()) return false;
LatLonPointSortField other = (LatLonPointSortField) obj;
if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude)) return false;
- if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude)) return false;
+ if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude))
+ return false;
return true;
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
index 5e442dd..a35af35 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
@@ -16,9 +16,11 @@
*/
package org.apache.lucene.document;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
+import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
+
import java.util.ArrayList;
import java.util.List;
-
import org.apache.lucene.document.ShapeField.QueryRelation; // javadoc
import org.apache.lucene.document.ShapeField.Triangle;
import org.apache.lucene.geo.Circle;
@@ -35,36 +37,37 @@ import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
-import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
-
/**
- * An geo shape utility class for indexing and searching gis geometries
- * whose vertices are latitude, longitude values (in decimal degrees).
- * <p>
- * This class defines seven static factory methods for common indexing and search operations:
+ * An geo shape utility class for indexing and searching gis geometries whose vertices are latitude,
+ * longitude values (in decimal degrees).
+ *
+ * <p>This class defines seven static factory methods for common indexing and search operations:
+ *
* <ul>
* <li>{@link #createIndexableFields(String, Polygon)} for indexing a geo polygon.
* <li>{@link #createIndexableFields(String, Line)} for indexing a geo linestring.
* <li>{@link #createIndexableFields(String, double, double)} for indexing a lat, lon geo point.
- * <li>{@link #newBoxQuery newBoxQuery()} for matching geo shapes that have some {@link QueryRelation} with a bounding box.
- * <li>{@link #newLineQuery newLineQuery()} for matching geo shapes that have some {@link QueryRelation} with a linestring.
- * <li>{@link #newPolygonQuery newPolygonQuery()} for matching geo shapes that have some {@link QueryRelation} with a polygon.
- * <li>{@link #newGeometryQuery newGeometryQuery()} for matching geo shapes that have some {@link QueryRelation}
- * with one or more {@link LatLonGeometry}.
+ * <li>{@link #newBoxQuery newBoxQuery()} for matching geo shapes that have some {@link
+ * QueryRelation} with a bounding box.
+ * <li>{@link #newLineQuery newLineQuery()} for matching geo shapes that have some {@link
+ * QueryRelation} with a linestring.
+ * <li>{@link #newPolygonQuery newPolygonQuery()} for matching geo shapes that have some {@link
+ * QueryRelation} with a polygon.
+ * <li>{@link #newGeometryQuery newGeometryQuery()} for matching geo shapes that have some {@link
+ * QueryRelation} with one or more {@link LatLonGeometry}.
* </ul>
-
- * <b>WARNING</b>: Like {@link LatLonPoint}, vertex values are indexed with some loss of precision from the
- * original {@code double} values (4.190951585769653E-8 for the latitude component
- * and 8.381903171539307E-8 for longitude).
+ *
+ * <b>WARNING</b>: Like {@link LatLonPoint}, vertex values are indexed with some loss of precision
+ * from the original {@code double} values (4.190951585769653E-8 for the latitude component and
+ * 8.381903171539307E-8 for longitude).
+ *
* @see PointValues
* @see LatLonDocValuesField
*/
public class LatLonShape {
// no instance:
- private LatLonShape() {
- }
+ private LatLonShape() {}
/** create indexable fields for polygon geometry */
public static Field[] createIndexableFields(String fieldName, Polygon polygon) {
@@ -83,71 +86,104 @@ public class LatLonShape {
Field[] fields = new Field[numPoints - 1];
// create "flat" triangles
for (int i = 0, j = 1; j < numPoints; ++i, ++j) {
- fields[i] = new Triangle(fieldName,
- encodeLongitude(line.getLon(i)), encodeLatitude(line.getLat(i)),
- encodeLongitude(line.getLon(j)), encodeLatitude(line.getLat(j)),
- encodeLongitude(line.getLon(i)), encodeLatitude(line.getLat(i)));
+ fields[i] =
+ new Triangle(
+ fieldName,
+ encodeLongitude(line.getLon(i)),
+ encodeLatitude(line.getLat(i)),
+ encodeLongitude(line.getLon(j)),
+ encodeLatitude(line.getLat(j)),
+ encodeLongitude(line.getLon(i)),
+ encodeLatitude(line.getLat(i)));
}
return fields;
}
/** create indexable fields for point geometry */
public static Field[] createIndexableFields(String fieldName, double lat, double lon) {
- return new Field[] {new Triangle(fieldName,
- encodeLongitude(lon), encodeLatitude(lat),
- encodeLongitude(lon), encodeLatitude(lat),
- encodeLongitude(lon), encodeLatitude(lat))};
+ return new Field[] {
+ new Triangle(
+ fieldName,
+ encodeLongitude(lon),
+ encodeLatitude(lat),
+ encodeLongitude(lon),
+ encodeLatitude(lat),
+ encodeLongitude(lon),
+ encodeLatitude(lat))
+ };
}
- /** create a query to find all indexed geo shapes that intersect a defined bounding box **/
- public static Query newBoxQuery(String field, QueryRelation queryRelation, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
+ /** create a query to find all indexed geo shapes that intersect a defined bounding box * */
+ public static Query newBoxQuery(
+ String field,
+ QueryRelation queryRelation,
+ double minLatitude,
+ double maxLatitude,
+ double minLongitude,
+ double maxLongitude) {
if (queryRelation == QueryRelation.CONTAINS && minLongitude > maxLongitude) {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
- builder.add(newBoxQuery(field, queryRelation, minLatitude, maxLatitude, minLongitude, GeoUtils.MAX_LON_INCL), BooleanClause.Occur.MUST);
- builder.add(newBoxQuery(field, queryRelation, minLatitude, maxLatitude, GeoUtils.MIN_LON_INCL, maxLongitude), BooleanClause.Occur.MUST);
+ builder.add(
+ newBoxQuery(
+ field, queryRelation, minLatitude, maxLatitude, minLongitude, GeoUtils.MAX_LON_INCL),
+ BooleanClause.Occur.MUST);
+ builder.add(
+ newBoxQuery(
+ field, queryRelation, minLatitude, maxLatitude, GeoUtils.MIN_LON_INCL, maxLongitude),
+ BooleanClause.Occur.MUST);
return builder.build();
}
Rectangle rectangle = new Rectangle(minLatitude, maxLatitude, minLongitude, maxLongitude);
return new LatLonShapeBoundingBoxQuery(field, queryRelation, rectangle);
}
- /** create a query to find all indexed geo shapes that intersect a provided linestring (or array of linestrings)
- * note: does not support dateline crossing
- **/
+ /**
+ * create a query to find all indexed geo shapes that intersect a provided linestring (or array of
+ * linestrings) note: does not support dateline crossing
+ */
public static Query newLineQuery(String field, QueryRelation queryRelation, Line... lines) {
return newGeometryQuery(field, queryRelation, lines);
}
- /** create a query to find all indexed geo shapes that intersect a provided polygon (or array of polygons)
- * note: does not support dateline crossing
- **/
- public static Query newPolygonQuery(String field, QueryRelation queryRelation, Polygon... polygons) {
+ /**
+ * create a query to find all indexed geo shapes that intersect a provided polygon (or array of
+ * polygons) note: does not support dateline crossing
+ */
+ public static Query newPolygonQuery(
+ String field, QueryRelation queryRelation, Polygon... polygons) {
return newGeometryQuery(field, queryRelation, polygons);
}
- /** create a query to find all indexed shapes that comply the {@link QueryRelation} with the provided points
- **/
+ /**
+ * create a query to find all indexed shapes that comply the {@link QueryRelation} with the
+ * provided points
+ */
public static Query newPointQuery(String field, QueryRelation queryRelation, double[]... points) {
Point[] pointArray = new Point[points.length];
- for (int i =0; i < points.length; i++) {
+ for (int i = 0; i < points.length; i++) {
pointArray[i] = new Point(points[i][0], points[i][1]);
}
return newGeometryQuery(field, queryRelation, pointArray);
}
/** create a query to find all polygons that intersect a provided circle. */
- public static Query newDistanceQuery(String field, QueryRelation queryRelation, Circle... circle) {
+ public static Query newDistanceQuery(
+ String field, QueryRelation queryRelation, Circle... circle) {
return newGeometryQuery(field, queryRelation, circle);
}
- /** create a query to find all indexed geo shapes that intersect a provided geometry (or array of geometries).
- **/
- public static Query newGeometryQuery(String field, QueryRelation queryRelation, LatLonGeometry... latLonGeometries) {
- if (latLonGeometries.length == 1) {
+ /**
+ * create a query to find all indexed geo shapes that intersect a provided geometry (or array of
+ * geometries).
+ */
+ public static Query newGeometryQuery(
+ String field, QueryRelation queryRelation, LatLonGeometry... latLonGeometries) {
+ if (latLonGeometries.length == 1) {
LatLonGeometry geometry = latLonGeometries[0];
if (geometry instanceof Rectangle) {
Rectangle rect = (Rectangle) geometry;
- return newBoxQuery(field, queryRelation, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
+ return newBoxQuery(
+ field, queryRelation, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
} else {
return new LatLonShapeQuery(field, queryRelation, latLonGeometries);
}
@@ -166,12 +202,16 @@ public class LatLonShape {
if (geometry instanceof Rectangle) {
// this handles rectangles across the dateline
Rectangle rect = (Rectangle) geometry;
- builder.add(newBoxQuery(field, QueryRelation.CONTAINS, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon), BooleanClause.Occur.MUST);
+ builder.add(
+ newBoxQuery(
+ field, QueryRelation.CONTAINS, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon),
+ BooleanClause.Occur.MUST);
} else {
- builder.add(new LatLonShapeQuery(field, QueryRelation.CONTAINS, geometry), BooleanClause.Occur.MUST);
+ builder.add(
+ new LatLonShapeQuery(field, QueryRelation.CONTAINS, geometry),
+ BooleanClause.Occur.MUST);
}
}
return new ConstantScoreQuery(builder.build());
}
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java
index aca9349..4dcdc47 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java
@@ -16,15 +16,6 @@
*/
package org.apache.lucene.document;
-import java.util.Arrays;
-
-import org.apache.lucene.document.ShapeField.QueryRelation;
-import org.apache.lucene.geo.Component2D;
-import org.apache.lucene.geo.GeoUtils;
-import org.apache.lucene.geo.Rectangle;
-import org.apache.lucene.index.PointValues.Relation;
-import org.apache.lucene.util.NumericUtils;
-
import static java.lang.Integer.BYTES;
import static org.apache.lucene.geo.GeoEncodingUtils.MAX_LON_ENCODED;
import static org.apache.lucene.geo.GeoEncodingUtils.MIN_LON_ENCODED;
@@ -33,12 +24,20 @@ import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitudeCeil;
import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitudeCeil;
+import java.util.Arrays;
+import org.apache.lucene.document.ShapeField.QueryRelation;
+import org.apache.lucene.geo.Component2D;
+import org.apache.lucene.geo.GeoUtils;
+import org.apache.lucene.geo.Rectangle;
+import org.apache.lucene.index.PointValues.Relation;
+import org.apache.lucene.util.NumericUtils;
+
/**
* Finds all previously indexed geo shapes that intersect the specified bounding box.
*
- * <p>The field must be indexed using
- * {@link org.apache.lucene.document.LatLonShape#createIndexableFields} added per document.
- **/
+ * <p>The field must be indexed using {@link
+ * org.apache.lucene.document.LatLonShape#createIndexableFields} added per document.
+ */
final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
private final Rectangle rectangle;
private final EncodedRectangle encodedRectangle;
@@ -46,44 +45,57 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
LatLonShapeBoundingBoxQuery(String field, QueryRelation queryRelation, Rectangle rectangle) {
super(field, queryRelation);
this.rectangle = rectangle;
- this.encodedRectangle = new EncodedRectangle(rectangle.minLat, rectangle.maxLat, rectangle.minLon, rectangle.maxLon);
+ this.encodedRectangle =
+ new EncodedRectangle(
+ rectangle.minLat, rectangle.maxLat, rectangle.minLon, rectangle.maxLon);
}
@Override
- protected Relation relateRangeBBoxToQuery(int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
+ protected Relation relateRangeBBoxToQuery(
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
if (queryRelation == QueryRelation.INTERSECTS || queryRelation == QueryRelation.DISJOINT) {
- return encodedRectangle.intersectRangeBBox(minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ return encodedRectangle.intersectRangeBBox(
+ minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
}
- return encodedRectangle.relateRangeBBox(minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ return encodedRectangle.relateRangeBBox(
+ minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
}
-
@Override
protected boolean queryIntersects(byte[] t, ShapeField.DecodedTriangle scratchTriangle) {
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY);
- }
- case LINE: {
- int aY = scratchTriangle.aY;
- int aX = scratchTriangle.aX;
- int bY = scratchTriangle.bY;
- int bX = scratchTriangle.bX;
- return encodedRectangle.intersectsLine(aX, aY, bX, bY);
- }
- case TRIANGLE: {
- int aY = scratchTriangle.aY;
- int aX = scratchTriangle.aX;
- int bY = scratchTriangle.bY;
- int bX = scratchTriangle.bX;
- int cY = scratchTriangle.cY;
- int cX = scratchTriangle.cX;
- return encodedRectangle.intersectsTriangle(aX, aY, bX, bY, cX, cY);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY);
+ }
+ case LINE:
+ {
+ int aY = scratchTriangle.aY;
+ int aX = scratchTriangle.aX;
+ int bY = scratchTriangle.bY;
+ int bX = scratchTriangle.bX;
+ return encodedRectangle.intersectsLine(aX, aY, bX, bY);
+ }
+ case TRIANGLE:
+ {
+ int aY = scratchTriangle.aY;
+ int aX = scratchTriangle.aX;
+ int bY = scratchTriangle.bY;
+ int bX = scratchTriangle.bX;
+ int cY = scratchTriangle.cY;
+ int cX = scratchTriangle.cX;
+ return encodedRectangle.intersectsTriangle(aX, aY, bX, bY, cX, cY);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@@ -92,58 +104,82 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY);
- }
- case LINE: {
- int aY = scratchTriangle.aY;
- int aX = scratchTriangle.aX;
- int bY = scratchTriangle.bY;
- int bX = scratchTriangle.bX;
- return encodedRectangle.containsLine(aX, aY, bX, bY);
- }
- case TRIANGLE: {
- int aY = scratchTriangle.aY;
- int aX = scratchTriangle.aX;
- int bY = scratchTriangle.bY;
- int bX = scratchTriangle.bX;
- int cY = scratchTriangle.cY;
- int cX = scratchTriangle.cX;
- return encodedRectangle.containsTriangle(aX, aY, bX, bY, cX, cY);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY);
+ }
+ case LINE:
+ {
+ int aY = scratchTriangle.aY;
+ int aX = scratchTriangle.aX;
+ int bY = scratchTriangle.bY;
+ int bX = scratchTriangle.bX;
+ return encodedRectangle.containsLine(aX, aY, bX, bY);
+ }
+ case TRIANGLE:
+ {
+ int aY = scratchTriangle.aY;
+ int aX = scratchTriangle.aX;
+ int bY = scratchTriangle.bY;
+ int bX = scratchTriangle.bX;
+ int cY = scratchTriangle.cY;
+ int cX = scratchTriangle.cX;
+ return encodedRectangle.containsTriangle(aX, aY, bX, bY, cX, cY);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@Override
- protected Component2D.WithinRelation queryWithin(byte[] t, ShapeField.DecodedTriangle scratchTriangle) {
+ protected Component2D.WithinRelation queryWithin(
+ byte[] t, ShapeField.DecodedTriangle scratchTriangle) {
if (encodedRectangle.crossesDateline()) {
- throw new IllegalArgumentException("withinTriangle is not supported for rectangles crossing the date line");
+ throw new IllegalArgumentException(
+ "withinTriangle is not supported for rectangles crossing the date line");
}
// decode indexed triangle
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY)
- ? Component2D.WithinRelation.NOTWITHIN : Component2D.WithinRelation.DISJOINT;
- }
- case LINE: {
- return encodedRectangle.withinLine(scratchTriangle.aX, scratchTriangle.aY, scratchTriangle.ab,
- scratchTriangle.bX, scratchTriangle.bY);
- }
- case TRIANGLE: {
- return encodedRectangle.withinTriangle(scratchTriangle.aX, scratchTriangle.aY, scratchTriangle.ab,
- scratchTriangle.bX, scratchTriangle.bY, scratchTriangle.bc,
- scratchTriangle.cX, scratchTriangle.cY, scratchTriangle.ca);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ return encodedRectangle.contains(scratchTriangle.aX, scratchTriangle.aY)
+ ? Component2D.WithinRelation.NOTWITHIN
+ : Component2D.WithinRelation.DISJOINT;
+ }
+ case LINE:
+ {
+ return encodedRectangle.withinLine(
+ scratchTriangle.aX,
+ scratchTriangle.aY,
+ scratchTriangle.ab,
+ scratchTriangle.bX,
+ scratchTriangle.bY);
+ }
+ case TRIANGLE:
+ {
+ return encodedRectangle.withinTriangle(
+ scratchTriangle.aX,
+ scratchTriangle.aY,
+ scratchTriangle.ab,
+ scratchTriangle.bX,
+ scratchTriangle.bY,
+ scratchTriangle.bc,
+ scratchTriangle.cX,
+ scratchTriangle.cY,
+ scratchTriangle.ca);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@Override
protected boolean equalsTo(Object o) {
- return super.equalsTo(o) && rectangle.equals(((LatLonShapeBoundingBoxQuery)o).rectangle);
+ return super.equalsTo(o) && rectangle.equals(((LatLonShapeBoundingBoxQuery) o).rectangle);
}
@Override
@@ -184,7 +220,7 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
this.minX = encodeLongitudeCeil(minLon);
this.maxX = encodeLongitude(maxLon);
- this.minY = encodeLatitudeCeil(minLat);
+ this.minY = encodeLatitudeCeil(minLat);
this.maxY = encodeLatitude(maxLat);
this.crossesDateline = minLon > maxLon;
if (this.crossesDateline) {
@@ -198,10 +234,9 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
}
- /**
- * encodes a bounding box into the provided byte array
- */
- private static void encode(final int minX, final int maxX, final int minY, final int maxY, byte[] b) {
+ /** encodes a bounding box into the provided byte array */
+ private static void encode(
+ final int minX, final int maxX, final int minY, final int maxY, byte[] b) {
if (b == null) {
b = new byte[4 * BYTES];
}
@@ -215,47 +250,71 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
return crossesDateline;
}
- /**
- * compare this to a provided range bounding box
- **/
- Relation relateRangeBBox(int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
- Relation eastRelation = compareBBoxToRangeBBox(this.bbox,
- minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ /** compare this to a provided range bounding box */
+ Relation relateRangeBBox(
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
+ Relation eastRelation =
+ compareBBoxToRangeBBox(
+ this.bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
if (this.crossesDateline() && eastRelation == Relation.CELL_OUTSIDE_QUERY) {
- return compareBBoxToRangeBBox(this.west, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ return compareBBoxToRangeBBox(
+ this.west, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
}
return eastRelation;
}
- /**
- * intersects this to a provided range bounding box
- **/
- Relation intersectRangeBBox(int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
- Relation eastRelation = intersectBBoxWithRangeBBox(this.bbox,
- minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ /** intersects this to a provided range bounding box */
+ Relation intersectRangeBBox(
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
+ Relation eastRelation =
+ intersectBBoxWithRangeBBox(
+ this.bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
if (this.crossesDateline() && eastRelation == Relation.CELL_OUTSIDE_QUERY) {
- return intersectBBoxWithRangeBBox(this.west, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
+ return intersectBBoxWithRangeBBox(
+ this.west, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle);
}
return eastRelation;
}
/**
- * static utility method to compare a bbox with a range of triangles (just the bbox of the triangle collection)
- **/
- private static Relation compareBBoxToRangeBBox(final byte[] bbox,
- int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
+ * static utility method to compare a bbox with a range of triangles (just the bbox of the
+ * triangle collection)
+ */
+ private static Relation compareBBoxToRangeBBox(
+ final byte[] bbox,
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
// check bounding box (DISJOINT)
- if (disjoint(bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle)) {
+ if (disjoint(
+ bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle)) {
return Relation.CELL_OUTSIDE_QUERY;
}
- if (Arrays.compareUnsigned(minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES) >= 0 &&
- Arrays.compareUnsigned(maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES) <= 0 &&
- Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES) >= 0 &&
- Arrays.compareUnsigned(maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES) <= 0) {
+ if (Arrays.compareUnsigned(
+ minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES)
+ >= 0
+ && Arrays.compareUnsigned(
+ maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES)
+ <= 0
+ && Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES)
+ >= 0
+ && Arrays.compareUnsigned(
+ maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES)
+ <= 0) {
return Relation.CELL_INSIDE_QUERY;
}
@@ -263,37 +322,64 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
/**
- * static utility method to compare a bbox with a range of triangles (just the bbox of the triangle collection)
- * for intersection
- **/
- private static Relation intersectBBoxWithRangeBBox(final byte[] bbox,
- int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
+ * static utility method to compare a bbox with a range of triangles (just the bbox of the
+ * triangle collection) for intersection
+ */
+ private static Relation intersectBBoxWithRangeBBox(
+ final byte[] bbox,
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
// check bounding box (DISJOINT)
- if (disjoint(bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle)) {
+ if (disjoint(
+ bbox, minXOffset, minYOffset, minTriangle, maxXOffset, maxYOffset, maxTriangle)) {
return Relation.CELL_OUTSIDE_QUERY;
}
- if (Arrays.compareUnsigned(minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES) >= 0 &&
- Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES) >= 0) {
- if (Arrays.compareUnsigned(maxTriangle, minXOffset, minXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES) <= 0 &&
- Arrays.compareUnsigned(maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES) <= 0) {
+ if (Arrays.compareUnsigned(
+ minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES)
+ >= 0
+ && Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES)
+ >= 0) {
+ if (Arrays.compareUnsigned(
+ maxTriangle, minXOffset, minXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES)
+ <= 0
+ && Arrays.compareUnsigned(
+ maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES)
+ <= 0) {
return Relation.CELL_INSIDE_QUERY;
}
- if (Arrays.compareUnsigned(maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES) <= 0 &&
- Arrays.compareUnsigned(maxTriangle, minYOffset, minYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES) <= 0) {
+ if (Arrays.compareUnsigned(
+ maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES)
+ <= 0
+ && Arrays.compareUnsigned(
+ maxTriangle, minYOffset, minYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES)
+ <= 0) {
return Relation.CELL_INSIDE_QUERY;
}
}
- if (Arrays.compareUnsigned(maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES) <= 0 &&
- Arrays.compareUnsigned(maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES) <= 0) {
- if (Arrays.compareUnsigned(minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES) >= 0 &&
- Arrays.compareUnsigned(minTriangle, maxYOffset, maxYOffset + BYTES, bbox, 0, BYTES) >= 0) {
+ if (Arrays.compareUnsigned(
+ maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES)
+ <= 0
+ && Arrays.compareUnsigned(
+ maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES)
+ <= 0) {
+ if (Arrays.compareUnsigned(
+ minTriangle, minXOffset, minXOffset + BYTES, bbox, BYTES, 2 * BYTES)
+ >= 0
+ && Arrays.compareUnsigned(minTriangle, maxYOffset, maxYOffset + BYTES, bbox, 0, BYTES)
+ >= 0) {
return Relation.CELL_INSIDE_QUERY;
}
- if (Arrays.compareUnsigned(minTriangle, maxXOffset, maxXOffset + BYTES, bbox, BYTES, 2 * BYTES) >= 0 &&
- Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES) >= 0) {
+ if (Arrays.compareUnsigned(
+ minTriangle, maxXOffset, maxXOffset + BYTES, bbox, BYTES, 2 * BYTES)
+ >= 0
+ && Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 0, BYTES)
+ >= 0) {
return Relation.CELL_INSIDE_QUERY;
}
}
@@ -301,21 +387,29 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
return Relation.CELL_CROSSES_QUERY;
}
- /**
- * static utility method to check a bbox is disjoint with a range of triangles
- **/
- private static boolean disjoint(final byte[] bbox,
- int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
- return Arrays.compareUnsigned(minTriangle, minXOffset, minXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES) > 0 ||
- Arrays.compareUnsigned(maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, BYTES, 2 * BYTES) < 0 ||
- Arrays.compareUnsigned(minTriangle, minYOffset, minYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES) > 0 ||
- Arrays.compareUnsigned(maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 0, BYTES) < 0;
+ /** static utility method to check a bbox is disjoint with a range of triangles */
+ private static boolean disjoint(
+ final byte[] bbox,
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
+ return Arrays.compareUnsigned(
+ minTriangle, minXOffset, minXOffset + BYTES, bbox, 3 * BYTES, 4 * BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxTriangle, maxXOffset, maxXOffset + BYTES, bbox, BYTES, 2 * BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ minTriangle, minYOffset, minYOffset + BYTES, bbox, 2 * BYTES, 3 * BYTES)
+ > 0
+ || Arrays.compareUnsigned(maxTriangle, maxYOffset, maxYOffset + BYTES, bbox, 0, BYTES)
+ < 0;
}
- /**
- * Checks if the rectangle contains the provided point
- **/
+ /** Checks if the rectangle contains the provided point */
boolean contains(int x, int y) {
if (y < minY || y > maxY) {
return false;
@@ -327,9 +421,7 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
}
- /**
- * Checks if the rectangle intersects the provided LINE
- **/
+ /** Checks if the rectangle intersects the provided LINE */
boolean intersectsLine(int aX, int aY, int bX, int bY) {
if (contains(aX, aY) || contains(bX, bY)) {
return true;
@@ -351,9 +443,7 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
return edgeIntersectsQuery(aX, aY, bX, bY);
}
- /**
- * Checks if the rectangle intersects the provided triangle
- **/
+ /** Checks if the rectangle intersects the provided triangle */
boolean intersectsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {
// query contains any triangle points
if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {
@@ -378,60 +468,48 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
}
// expensive part
- return Component2D.pointInTriangle(tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY) ||
- edgeIntersectsQuery(aX, aY, bX, bY) ||
- edgeIntersectsQuery(bX, bY, cX, cY) ||
- edgeIntersectsQuery(cX, cY, aX, aY);
+ return Component2D.pointInTriangle(
+ tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)
+ || edgeIntersectsQuery(aX, aY, bX, bY)
+ || edgeIntersectsQuery(bX, bY, cX, cY)
+ || edgeIntersectsQuery(cX, cY, aX, aY);
}
- /**
- * Checks if the rectangle contains the provided LINE
- **/
+ /** Checks if the rectangle contains the provided LINE */
boolean containsLine(int aX, int aY, int bX, int bY) {
- if (aY < minY || bY < minY ||
- aY > maxY || bY > maxY ) {
+ if (aY < minY || bY < minY || aY > maxY || bY > maxY) {
return false;
}
if (crossesDateline) { // crosses dateline
- return (aX >= minX && bX >= minX) ||
- (aX <= maxX && bX <= maxX);
+ return (aX >= minX && bX >= minX) || (aX <= maxX && bX <= maxX);
} else {
- return aX >= minX && bX >= minX &&
- aX <= maxX && bX <= maxX;
+ return aX >= minX && bX >= minX && aX <= maxX && bX <= maxX;
}
}
- /**
- * Checks if the rectangle contains the provided triangle
- **/
+ /** Checks if the rectangle contains the provided triangle */
boolean containsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {
- if (aY < minY || bY < minY || cY < minY ||
- aY > maxY || bY > maxY || cY > maxY) {
+ if (aY < minY || bY < minY || cY < minY || aY > maxY || bY > maxY || cY > maxY) {
return false;
}
if (crossesDateline) { // crosses dateline
- return (aX >= minX && bX >= minX && cX >= minX) ||
- (aX <= maxX && bX <= maxX && cX <= maxX);
+ return (aX >= minX && bX >= minX && cX >= minX) || (aX <= maxX && bX <= maxX && cX <= maxX);
} else {
- return aX >= minX && bX >= minX && cX >= minX &&
- aX <= maxX && bX <= maxX && cX <= maxX;
+ return aX >= minX && bX >= minX && cX >= minX && aX <= maxX && bX <= maxX && cX <= maxX;
}
}
- /**
- * Returns the Within relation to the provided triangle
- */
+ /** Returns the Within relation to the provided triangle */
Component2D.WithinRelation withinLine(int ax, int ay, boolean ab, int bx, int by) {
if (ab == true && edgeIntersectsBox(ax, ay, bx, by, minX, maxX, minY, maxY) == true) {
- return Component2D.WithinRelation.NOTWITHIN;
+ return Component2D.WithinRelation.NOTWITHIN;
}
return Component2D.WithinRelation.DISJOINT;
}
- /**
- * Returns the Within relation to the provided triangle
- */
- Component2D.WithinRelation withinTriangle(int aX, int aY, boolean ab, int bX, int bY, boolean bc, int cX, int cY, boolean ca) {
+ /** Returns the Within relation to the provided triangle */
+ Component2D.WithinRelation withinTriangle(
+ int aX, int aY, boolean ab, int bX, int bY, boolean bc, int cX, int cY, boolean ca) {
// Points belong to the shape so if points are inside the rectangle then it cannot be within.
if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {
return Component2D.WithinRelation.NOTWITHIN;
@@ -480,16 +558,15 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
}
}
// Check if shape is within the triangle
- if (relation == Component2D.WithinRelation.CANDIDATE ||
- Component2D.pointInTriangle(tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)) {
+ if (relation == Component2D.WithinRelation.CANDIDATE
+ || Component2D.pointInTriangle(
+ tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)) {
return Component2D.WithinRelation.CANDIDATE;
}
return relation;
}
- /**
- * returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the query
- */
+ /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the query */
private boolean edgeIntersectsQuery(int aX, int aY, int bX, int bY) {
if (crossesDateline) {
return edgeIntersectsBox(aX, aY, bX, bY, MIN_LON_ENCODED, this.maxX, this.minY, this.maxY)
@@ -498,18 +575,22 @@ final class LatLonShapeBoundingBoxQuery extends ShapeQuery {
return edgeIntersectsBox(aX, aY, bX, bY, this.minX, this.maxX, this.minY, this.maxY);
}
- /**
- * returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the box
- */
- private static boolean edgeIntersectsBox(int aX, int aY, int bX, int bY,
- int minX, int maxX, int minY, int maxY) {
- if (Math.max(aX, bX) < minX || Math.min(aX, bX) > maxX || Math.min(aY, bY) > maxY || Math.max(aY, bY) < minY) {
+ /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the box */
+ private static boolean edgeIntersectsBox(
+ int aX, int aY, int bX, int bY, int minX, int maxX, int minY, int maxY) {
+ if (Math.max(aX, bX) < minX
+ || Math.min(aX, bX) > maxX
+ || Math.min(aY, bY) > maxY
+ || Math.max(aY, bY) < minY) {
return false;
}
- return GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, maxY, maxX, maxY) || // top
- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, maxY, maxX, minY) || // bottom
- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, minY, minX, minY) || // left
- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, minY, minX, maxY); // right
+ return GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, maxY, maxX, maxY)
+ || // top
+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, maxY, maxX, minY)
+ || // bottom
+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, minY, minX, minY)
+ || // left
+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, minY, minX, maxY); // right
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java
index 400a6f2..5b7ed54 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.util.Arrays;
-
import org.apache.lucene.document.ShapeField.QueryRelation;
import org.apache.lucene.geo.Component2D;
import org.apache.lucene.geo.GeoEncodingUtils;
@@ -31,11 +30,10 @@ import org.apache.lucene.util.NumericUtils;
* the specified array of {@link LatLonGeometry}.
*
* <p>The field must be indexed using {@link LatLonShape#createIndexableFields} added per document.
- *
- **/
+ */
final class LatLonShapeQuery extends ShapeQuery {
- final private LatLonGeometry[] geometries;
- final private Component2D component2D;
+ private final LatLonGeometry[] geometries;
+ private final Component2D component2D;
/**
* Creates a query that matches all indexed shapes to the provided array of {@link LatLonGeometry}
@@ -46,23 +44,34 @@ final class LatLonShapeQuery extends ShapeQuery {
for (LatLonGeometry geometry : geometries) {
if (geometry instanceof Line) {
// TODO: line queries do not support within relations
- throw new IllegalArgumentException("LatLonShapeQuery does not support " + QueryRelation.WITHIN + " queries with line geometries");
+ throw new IllegalArgumentException(
+ "LatLonShapeQuery does not support "
+ + QueryRelation.WITHIN
+ + " queries with line geometries");
}
}
-
}
this.component2D = LatLonGeometry.create(geometries);
this.geometries = geometries.clone();
}
@Override
- protected Relation relateRangeBBoxToQuery(int minXOffset, int minYOffset, byte[] minTriangle,
- int maxXOffset, int maxYOffset, byte[] maxTriangle) {
-
- double minLat = GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(minTriangle, minYOffset));
- double minLon = GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(minTriangle, minXOffset));
- double maxLat = GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(maxTriangle, maxYOffset));
- double maxLon = GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(maxTriangle, maxXOffset));
+ protected Relation relateRangeBBoxToQuery(
+ int minXOffset,
+ int minYOffset,
+ byte[] minTriangle,
+ int maxXOffset,
+ int maxYOffset,
+ byte[] maxTriangle) {
+
+ double minLat =
+ GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(minTriangle, minYOffset));
+ double minLon =
+ GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(minTriangle, minXOffset));
+ double maxLat =
+ GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(maxTriangle, maxYOffset));
+ double maxLon =
+ GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(maxTriangle, maxXOffset));
// check internal node against query
return component2D.relate(minLon, maxLon, minLat, maxLat);
@@ -73,28 +82,33 @@ final class LatLonShapeQuery extends ShapeQuery {
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- return component2D.contains(alon, alat);
- }
- case LINE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- return component2D.intersectsLine(alon, alat, blon, blat);
- }
- case TRIANGLE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
- double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
- return component2D.intersectsTriangle(alon, alat, blon, blat, clon, clat);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ return component2D.contains(alon, alat);
+ }
+ case LINE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ return component2D.intersectsLine(alon, alat, blon, blat);
+ }
+ case TRIANGLE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
+ double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
+ return component2D.intersectsTriangle(alon, alat, blon, blat, clon, clat);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@@ -103,58 +117,78 @@ final class LatLonShapeQuery extends ShapeQuery {
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- return component2D.contains(alon, alat);
- }
- case LINE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- return component2D.containsLine(alon, alat, blon, blat);
- }
- case TRIANGLE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
- double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
- return component2D.containsTriangle(alon, alat, blon, blat, clon, clat);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ return component2D.contains(alon, alat);
+ }
+ case LINE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ return component2D.containsLine(alon, alat, blon, blat);
+ }
+ case TRIANGLE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
+ double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
+ return component2D.containsTriangle(alon, alat, blon, blat, clon, clat);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@Override
- protected Component2D.WithinRelation queryWithin(byte[] t, ShapeField.DecodedTriangle scratchTriangle) {
+ protected Component2D.WithinRelation queryWithin(
+ byte[] t, ShapeField.DecodedTriangle scratchTriangle) {
ShapeField.decodeTriangle(t, scratchTriangle);
switch (scratchTriangle.type) {
- case POINT: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- return component2D.withinPoint(alon, alat);
- }
- case LINE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- return component2D.withinLine(alon, alat, scratchTriangle.ab, blon, blat);
- }
- case TRIANGLE: {
- double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
- double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
- double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
- double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
- double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
- double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
- return component2D.withinTriangle(alon, alat, scratchTriangle.ab, blon, blat, scratchTriangle.bc, clon, clat, scratchTriangle.ca);
- }
- default: throw new IllegalArgumentException("Unsupported triangle type :[" + scratchTriangle.type + "]");
+ case POINT:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ return component2D.withinPoint(alon, alat);
+ }
+ case LINE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ return component2D.withinLine(alon, alat, scratchTriangle.ab, blon, blat);
+ }
+ case TRIANGLE:
+ {
+ double alat = GeoEncodingUtils.decodeLatitude(scratchTriangle.aY);
+ double alon = GeoEncodingUtils.decodeLongitude(scratchTriangle.aX);
+ double blat = GeoEncodingUtils.decodeLatitude(scratchTriangle.bY);
+ double blon = GeoEncodingUtils.decodeLongitude(scratchTriangle.bX);
+ double clat = GeoEncodingUtils.decodeLatitude(scratchTriangle.cY);
+ double clon = GeoEncodingUtils.decodeLongitude(scratchTriangle.cX);
+ return component2D.withinTriangle(
+ alon,
+ alat,
+ scratchTriangle.ab,
+ blon,
+ blat,
+ scratchTriangle.bc,
+ clon,
+ clat,
+ scratchTriangle.ca);
+ }
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported triangle type :[" + scratchTriangle.type + "]");
}
}
@@ -179,7 +213,7 @@ final class LatLonShapeQuery extends ShapeQuery {
@Override
protected boolean equalsTo(Object o) {
- return super.equalsTo(o) && Arrays.equals(geometries, ((LatLonShapeQuery)o).geometries);
+ return super.equalsTo(o) && Arrays.equals(geometries, ((LatLonShapeQuery) o).geometries);
}
@Override
@@ -188,4 +222,4 @@ final class LatLonShapeQuery extends ShapeQuery {
hash = 31 * hash + Arrays.hashCode(geometries);
return hash;
}
-}
\ No newline at end of file
+}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LongDistanceFeatureQuery.java b/lucene/core/src/java/org/apache/lucene/document/LongDistanceFeatureQuery.java
index 0b4c365..bda1112 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongDistanceFeatureQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongDistanceFeatureQuery.java
@@ -19,7 +19,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
@@ -55,14 +54,13 @@ final class LongDistanceFeatureQuery extends Query {
@Override
public final boolean equals(Object o) {
- return sameClassAs(o) &&
- equalsTo(getClass().cast(o));
+ return sameClassAs(o) && equalsTo(getClass().cast(o));
}
private boolean equalsTo(LongDistanceFeatureQuery other) {
- return Objects.equals(field, other.field) &&
- origin == other.origin &&
- pivotDistance == other.pivotDistance;
+ return Objects.equals(field, other.field)
+ && origin == other.origin
+ && pivotDistance == other.pivotDistance;
}
@Override
@@ -83,11 +81,19 @@ final class LongDistanceFeatureQuery extends Query {
@Override
public String toString(String field) {
- return getClass().getSimpleName() + "(field=" + field + ",origin=" + origin + ",pivotDistance=" + pivotDistance + ")";
+ return getClass().getSimpleName()
+ + "(field="
+ + field
+ + ",origin="
+ + origin
+ + ",pivotDistance="
+ + pivotDistance
+ + ")";
}
@Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
+ throws IOException {
return new Weight(this) {
@Override
@@ -99,7 +105,8 @@ final class LongDistanceFeatureQuery extends Query {
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
SortedNumericDocValues multiDocValues = DocValues.getSortedNumeric(context.reader(), field);
if (multiDocValues.advanceExact(doc) == false) {
- return Explanation.noMatch("Document " + doc + " doesn't have a value for field " + field);
+ return Explanation.noMatch(
+ "Document " + doc + " doesn't have a value for field " + field);
}
long value = selectValue(multiDocValues);
long distance = Math.max(value, origin) - Math.min(value, origin);
@@ -108,7 +115,9 @@ final class LongDistanceFeatureQuery extends Query {
distance = Long.MAX_VALUE;
}
float score = (float) (boost * (pivotDistance / (pivotDistance + (double) distance)));
- return Explanation.match(score, "Distance score, computed as weight * pivotDistance / (pivotDistance + abs(value - origin)) from:",
+ return Explanation.match(
+ score,
+ "Distance score, computed as weight * pivotDistance / (pivotDistance + abs(value - origin)) from:",
Explanation.match(boost, "weight"),
Explanation.match(pivotDistance, "pivotDistance"),
Explanation.match(origin, "origin"),
@@ -145,7 +154,7 @@ final class LongDistanceFeatureQuery extends Query {
if (singleton != null) {
return singleton;
}
- return new NumericDocValues() {
+ return new NumericDocValues() {
long value;
@@ -183,7 +192,6 @@ final class LongDistanceFeatureQuery extends Query {
public long cost() {
return multiDocValues.cost();
}
-
};
}
@@ -194,7 +202,8 @@ final class LongDistanceFeatureQuery extends Query {
// No data on this segment
return null;
}
- final SortedNumericDocValues multiDocValues = DocValues.getSortedNumeric(context.reader(), field);
+ final SortedNumericDocValues multiDocValues =
+ DocValues.getSortedNumeric(context.reader(), field);
final NumericDocValues docValues = selectValues(multiDocValues);
final Weight weight = this;
@@ -202,7 +211,8 @@ final class LongDistanceFeatureQuery extends Query {
@Override
public Scorer get(long leadCost) throws IOException {
- return new DistanceScorer(weight, context.reader().maxDoc(), leadCost, boost, pointValues, docValues);
+ return new DistanceScorer(
+ weight, context.reader().maxDoc(), leadCost, boost, pointValues, docValues);
}
@Override
@@ -220,7 +230,6 @@ final class LongDistanceFeatureQuery extends Query {
}
return scorerSupplier.get(Long.MAX_VALUE);
}
-
};
}
@@ -235,8 +244,13 @@ final class LongDistanceFeatureQuery extends Query {
private final NumericDocValues docValues;
private long maxDistance = Long.MAX_VALUE;
- protected DistanceScorer(Weight weight, int maxDoc, long leadCost, float boost,
- PointValues pointValues, NumericDocValues docValues) {
+ protected DistanceScorer(
+ Weight weight,
+ int maxDoc,
+ long leadCost,
+ float boost,
+ PointValues pointValues,
+ NumericDocValues docValues) {
super(weight);
this.maxDoc = maxDoc;
this.leadCost = leadCost;
@@ -258,8 +272,8 @@ final class LongDistanceFeatureQuery extends Query {
}
/**
- * Inverting the score computation is very hard due to all potential
- * rounding errors, so we binary search the maximum distance.
+ * Inverting the score computation is very hard due to all potential rounding errors, so we
+ * binary search the maximum distance.
*/
private long computeMaxDistance(float minScore, long previousMaxDistance) {
assert score(0) >= minScore;
@@ -323,7 +337,7 @@ final class LongDistanceFeatureQuery extends Query {
@Override
public int advance(int target) throws IOException {
- return doc = it.advance(target);
+ return doc = it.advance(target);
}
};
}
@@ -372,62 +386,74 @@ final class LongDistanceFeatureQuery extends Query {
DocIdSetBuilder result = new DocIdSetBuilder(maxDoc);
final int doc = docID();
- IntersectVisitor visitor = new IntersectVisitor() {
-
- DocIdSetBuilder.BulkAdder adder;
-
- @Override
- public void grow(int count) {
- adder = result.grow(count);
- }
+ IntersectVisitor visitor =
+ new IntersectVisitor() {
- @Override
- public void visit(int docID) {
- if (docID <= doc) {
- // Already visited or skipped
- return;
- }
- adder.add(docID);
- }
-
- @Override
- public void visit(int docID, byte[] packedValue) {
- if (docID <= doc) {
- // Already visited or skipped
- return;
- }
- if (Arrays.compareUnsigned(packedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES) < 0) {
- // Doc's value is too low, in this dimension
- return;
- }
- if (Arrays.compareUnsigned(packedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES) > 0) {
- // Doc's value is too high, in this dimension
- return;
- }
+ DocIdSetBuilder.BulkAdder adder;
- // Doc is in-bounds
- adder.add(docID);
- }
+ @Override
+ public void grow(int count) {
+ adder = result.grow(count);
+ }
- @Override
- public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
- if (Arrays.compareUnsigned(minPackedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES) > 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES) < 0) {
- return Relation.CELL_OUTSIDE_QUERY;
- }
+ @Override
+ public void visit(int docID) {
+ if (docID <= doc) {
+ // Already visited or skipped
+ return;
+ }
+ adder.add(docID);
+ }
- if (Arrays.compareUnsigned(minPackedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES) < 0 ||
- Arrays.compareUnsigned(maxPackedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES) > 0) {
- return Relation.CELL_CROSSES_QUERY;
- }
+ @Override
+ public void visit(int docID, byte[] packedValue) {
+ if (docID <= doc) {
+ // Already visited or skipped
+ return;
+ }
+ if (Arrays.compareUnsigned(packedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES)
+ < 0) {
+ // Doc's value is too low, in this dimension
+ return;
+ }
+ if (Arrays.compareUnsigned(packedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES)
+ > 0) {
+ // Doc's value is too high, in this dimension
+ return;
+ }
+
+ // Doc is in-bounds
+ adder.add(docID);
+ }
- return Relation.CELL_INSIDE_QUERY;
- }
- };
+ @Override
+ public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
+ if (Arrays.compareUnsigned(
+ minPackedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES)
+ > 0
+ || Arrays.compareUnsigned(
+ maxPackedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES)
+ < 0) {
+ return Relation.CELL_OUTSIDE_QUERY;
+ }
+
+ if (Arrays.compareUnsigned(
+ minPackedValue, 0, Long.BYTES, minValueAsBytes, 0, Long.BYTES)
+ < 0
+ || Arrays.compareUnsigned(
+ maxPackedValue, 0, Long.BYTES, maxValueAsBytes, 0, Long.BYTES)
+ > 0) {
+ return Relation.CELL_CROSSES_QUERY;
+ }
+
+ return Relation.CELL_INSIDE_QUERY;
+ }
+ };
final long currentQueryCost = Math.min(leadCost, it.cost());
final long threshold = currentQueryCost >>> 3;
- long estimatedNumberOfMatches = pointValues.estimatePointCount(visitor); // runs in O(log(numPoints))
+ long estimatedNumberOfMatches =
+ pointValues.estimatePointCount(visitor); // runs in O(log(numPoints))
// TODO: what is the right factor compared to the current disi? Is 8 optimal?
if (estimatedNumberOfMatches >= threshold) {
// the new range is not selective enough to be worth materializing
@@ -436,6 +462,5 @@ final class LongDistanceFeatureQuery extends Query {
pointValues.intersect(visitor);
it = result.build().iterator();
}
-
}
}
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 d26660f..3224c6a 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongPoint.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongPoint.java
@@ -18,32 +18,33 @@ package org.apache.lucene.document;
import java.util.Arrays;
import java.util.Collection;
-
import org.apache.lucene.index.PointValues;
+import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.PointInSetQuery;
import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
-import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-/**
- * An indexed {@code long} field for fast range filters. If you also
- * need to store the value, you should add a separate {@link StoredField} instance.
- * <p>
- * Finding all documents within an N-dimensional shape or 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:
+/**
+ * An indexed {@code long} field for fast range filters. If you also need to store the value, you
+ * should add a separate {@link StoredField} instance.
+ *
+ * <p>Finding all documents within an N-dimensional shape or 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 #newExactQuery(String, long)} for matching an exact 1D point.
* <li>{@link #newSetQuery(String, long...)} for matching a set of 1D values.
* <li>{@link #newRangeQuery(String, long, long)} for matching a 1D range.
- * <li>{@link #newRangeQuery(String, long[], long[])} for matching points/ranges in n-dimensional space.
+ * <li>{@link #newRangeQuery(String, long[], long[])} for matching points/ranges in n-dimensional
+ * space.
* </ul>
+ *
* @see PointValues
*/
public final class LongPoint extends Field {
@@ -62,7 +63,14 @@ public final class LongPoint extends Field {
/** Change the values of this field */
public void setLongValues(long... point) {
if (type.pointDimensionCount() != point.length) {
- throw new IllegalArgumentException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot change to (incoming) " + point.length + " dimensions");
+ throw new IllegalArgumentException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot change to (incoming) "
+ + point.length
+ + " dimensions");
}
fieldsData = pack(point);
}
@@ -75,7 +83,12 @@ public final class LongPoint extends Field {
@Override
public Number numericValue() {
if (type.pointDimensionCount() != 1) {
- throw new IllegalStateException("this field (name=" + name + ") uses " + type.pointDimensionCount() + " dimensions; cannot convert to a single numeric value");
+ throw new IllegalStateException(
+ "this field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount()
+ + " dimensions; cannot convert to a single numeric value");
}
BytesRef bytes = (BytesRef) fieldsData;
assert bytes.length == Long.BYTES;
@@ -83,7 +96,7 @@ public final class LongPoint extends Field {
}
/**
- * Pack a long point into a BytesRef
+ * Pack a long point into a BytesRef
*
* @param point long[] value
* @throws IllegalArgumentException is the value is null or of zero length
@@ -96,7 +109,7 @@ public final class LongPoint extends Field {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
byte[] packed = new byte[point.length * Long.BYTES];
-
+
for (int dim = 0; dim < point.length; dim++) {
encodeDimension(point[dim], packed, dim * Long.BYTES);
}
@@ -104,17 +117,17 @@ public final class LongPoint extends Field {
return new BytesRef(packed);
}
- /** Creates a new LongPoint, indexing the
- * provided N-dimensional long point.
+ /**
+ * Creates a new LongPoint, indexing the provided N-dimensional long point.
*
- * @param name field name
- * @param point long[] value
- * @throws IllegalArgumentException if the field name or value is null.
+ * @param name field name
+ * @param point long[] value
+ * @throws IllegalArgumentException if the field name or value is null.
*/
public LongPoint(String name, long... point) {
super(name, pack(point), getType(point.length));
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -134,26 +147,26 @@ public final class LongPoint extends Field {
result.append('>');
return result.toString();
}
-
+
// public helper methods (e.g. for queries)
-
+
/** Encode single long dimension */
public static void encodeDimension(long value, byte dest[], int offset) {
NumericUtils.longToSortableBytes(value, dest, offset);
}
-
+
/** Decode single long dimension */
public static long decodeDimension(byte value[], int offset) {
return NumericUtils.sortableBytesToLong(value, offset);
}
-
+
// static methods for generating queries
-
- /**
+
+ /**
* Create a query for matching an exact long value.
- * <p>
- * This is for simple one-dimension points, for multidimensional points use
- * {@link #newRangeQuery(String, long[], long[])} instead.
+ *
+ * <p>This is for simple one-dimension points, for multidimensional points use {@link
+ * #newRangeQuery(String, long[], long[])} instead.
*
* @param field field name. must not be {@code null}.
* @param value exact value
@@ -164,17 +177,17 @@ public final class LongPoint extends Field {
return newRangeQuery(field, value, value);
}
- /**
+ /**
* Create a range query for long values.
- * <p>
- * This is for simple one-dimension ranges, for multidimensional ranges use
- * {@link #newRangeQuery(String, long[], long[])} instead.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = Long.MIN_VALUE} or {@code upperValue = Long.MAX_VALUE}.
- * <p>
- * Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)}
- * or {@code Math.addExact(upperValue, -1)}.
+ *
+ * <p>This is for simple one-dimension ranges, for multidimensional ranges use {@link
+ * #newRangeQuery(String, long[], long[])} instead.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = Long.MIN_VALUE} or {@code upperValue = Long.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)} or
+ * {@code Math.addExact(upperValue, -1)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive).
@@ -183,28 +196,29 @@ public final class LongPoint extends Field {
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, long lowerValue, long upperValue) {
- return newRangeQuery(field, new long[] { lowerValue }, new long[] { upperValue });
+ return newRangeQuery(field, new long[] {lowerValue}, new long[] {upperValue});
}
- /**
+ /**
* Create a range query for n-dimensional long values.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue[i] = Long.MIN_VALUE} or {@code upperValue[i] = Long.MAX_VALUE}.
- * <p>
- * Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue[i], 1)}
- * or {@code Math.addExact(upperValue[i], -1)}.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue[i] = Long.MIN_VALUE} or {@code upperValue[i] = Long.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue[i], 1)} or
+ * {@code Math.addExact(upperValue[i], -1)}.
*
* @param field field name. must not be {@code null}.
* @param lowerValue lower portion of the range (inclusive). must not be {@code null}.
* @param upperValue upper portion of the range (inclusive). must not be {@code null}.
- * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if {@code upperValue} is null,
- * or if {@code lowerValue.length != upperValue.length}
+ * @throws IllegalArgumentException if {@code field} is null, if {@code lowerValue} is null, if
+ * {@code upperValue} is null, or if {@code lowerValue.length != upperValue.length}
* @return a query matching documents within this range.
*/
public static Query newRangeQuery(String field, long[] lowerValue, long[] upperValue) {
PointRangeQuery.checkArgs(field, lowerValue, upperValue);
- return new PointRangeQuery(field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
+ return new PointRangeQuery(
+ field, pack(lowerValue).bytes, pack(upperValue).bytes, lowerValue.length) {
@Override
protected String toString(int dimension, byte[] value) {
return Long.toString(decodeDimension(value, 0));
@@ -213,8 +227,9 @@ public final class LongPoint extends Field {
}
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -226,22 +241,25 @@ public final class LongPoint extends Field {
final BytesRef encoded = new BytesRef(new byte[Long.BYTES]);
- return new PointInSetQuery(field, 1, Long.BYTES,
- new PointInSetQuery.Stream() {
+ return new PointInSetQuery(
+ field,
+ 1,
+ Long.BYTES,
+ new PointInSetQuery.Stream() {
- int upto;
+ int upto;
- @Override
- public BytesRef next() {
- if (upto == sortedValues.length) {
- return null;
- } else {
- encodeDimension(sortedValues[upto], encoded.bytes, 0);
- upto++;
- return encoded;
- }
- }
- }) {
+ @Override
+ public BytesRef next() {
+ if (upto == sortedValues.length) {
+ return null;
+ } else {
+ encodeDimension(sortedValues[upto], encoded.bytes, 0);
+ upto++;
+ return encoded;
+ }
+ }
+ }) {
@Override
protected String toString(byte[] value) {
assert value.length == Long.BYTES;
@@ -249,10 +267,11 @@ public final class LongPoint extends Field {
}
};
}
-
+
/**
- * Create a query matching any of the specified 1D values. This is the points equivalent of {@code TermsQuery}.
- *
+ * Create a query matching any of the specified 1D values. This is the points equivalent of {@code
+ * TermsQuery}.
+ *
* @param field field name. must not be {@code null}.
* @param values all values to match
*/
@@ -266,21 +285,18 @@ public final class LongPoint extends Field {
}
/**
- * Given a field that indexes the same long values into a {@link LongPoint}
- * and doc values (either {@link NumericDocValuesField} or
- * {@link SortedNumericDocValuesField}), this returns a query that scores
- * documents based on their distance to {@code origin}:
- * {@code score = weight * pivotDistance / (pivotDistance + distance)}, ie.
- * score is in the {@code [0, weight]} range, is equal to {@code weight} when
- * the document's value is equal to {@code origin} and is equal to
- * {@code weight/2} when the document's value is distant of
- * {@code pivotDistance} from {@code origin}.
- * In case of multi-valued fields, only the closest point to {@code origin}
- * will be considered.
- * This query is typically useful to boost results based on recency by adding
- * this query to a {@link Occur#SHOULD} clause of a {@link BooleanQuery}.
+ * Given a field that indexes the same long values into a {@link LongPoint} and doc values (either
+ * {@link NumericDocValuesField} or {@link SortedNumericDocValuesField}), this returns a query
+ * that scores documents based on their distance to {@code origin}: {@code score = weight *
+ * pivotDistance / (pivotDistance + distance)}, ie. score is in the {@code [0, weight]} range, is
+ * equal to {@code weight} when the document's value is equal to {@code origin} and is equal to
+ * {@code weight/2} when the document's value is distant of {@code pivotDistance} from {@code
+ * origin}. In case of multi-valued fields, only the closest point to {@code origin} will be
+ * considered. This query is typically useful to boost results based on recency by adding this
+ * query to a {@link Occur#SHOULD} clause of a {@link BooleanQuery}.
*/
- public static Query newDistanceFeatureQuery(String field, float weight, long origin, long pivotDistance) {
+ public static Query newDistanceFeatureQuery(
+ String field, float weight, long origin, long pivotDistance) {
Query query = new LongDistanceFeatureQuery(field, origin, pivotDistance);
if (weight != 1f) {
query = new BoostQuery(query, weight);
diff --git a/lucene/core/src/java/org/apache/lucene/document/LongRange.java b/lucene/core/src/java/org/apache/lucene/document/LongRange.java
index f49ae15..6c4df42 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongRange.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongRange.java
@@ -17,7 +17,6 @@
package org.apache.lucene.document;
import java.util.Objects;
-
import org.apache.lucene.document.RangeFieldQuery.QueryType;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
@@ -25,20 +24,25 @@ import org.apache.lucene.util.NumericUtils;
/**
* An indexed Long Range field.
- * <p>
- * This field indexes dimensional ranges defined as min/max pairs. It supports
- * up to a maximum of 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single long range,
- * 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a tesseract.
- * <p>
- * Multiple values for the same field in one document is supported, and open ended ranges can be defined using
- * {@code Long.MIN_VALUE} and {@code Long.MAX_VALUE}.
*
- * <p>
- * This field defines the following static factory methods for common search operations over long ranges:
+ * <p>This field indexes dimensional ranges defined as min/max pairs. It supports up to a maximum of
+ * 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single long range, 2
+ * dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a
+ * tesseract.
+ *
+ * <p>Multiple values for the same field in one document is supported, and open ended ranges can be
+ * defined using {@code Long.MIN_VALUE} and {@code Long.MAX_VALUE}.
+ *
+ * <p>This field defines the following static factory methods for common search operations over long
+ * ranges:
+ *
* <ul>
- * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined search range.
- * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search range.
- * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search range.
+ * <li>{@link #newIntersectsQuery newIntersectsQuery()} matches ranges that intersect the defined
+ * search range.
+ * <li>{@link #newWithinQuery newWithinQuery()} matches ranges that are within the defined search
+ * range.
+ * <li>{@link #newContainsQuery newContainsQuery()} matches ranges that contain the defined search
+ * range.
* </ul>
*/
public class LongRange extends Field {
@@ -65,30 +69,38 @@ public class LongRange extends Field {
FieldType ft = new FieldType();
// dimensions is set as 2*dimension size (min/max per dimension)
- ft.setDimensions(dimensions*2, BYTES);
+ ft.setDimensions(dimensions * 2, BYTES);
ft.freeze();
return ft;
}
/**
* Changes the values of the field.
+ *
* @param min array of min values. (accepts {@code Long.MIN_VALUE})
* @param max array of max values. (accepts {@code Long.MAX_VALUE})
* @throws IllegalArgumentException if {@code min} or {@code max} is invalid
*/
public void setRangeValues(long[] min, long[] max) {
checkArgs(min, max);
- if (min.length*2 != type.pointDimensionCount() || max.length*2 != type.pointDimensionCount()) {
- throw new IllegalArgumentException("field (name=" + name + ") uses " + type.pointDimensionCount()/2
- + " dimensions; cannot change to (incoming) " + min.length + " dimensions");
+ if (min.length * 2 != type.pointDimensionCount()
+ || max.length * 2 != type.pointDimensionCount()) {
+ throw new IllegalArgumentException(
+ "field (name="
+ + name
+ + ") uses "
+ + type.pointDimensionCount() / 2
+ + " dimensions; cannot change to (incoming) "
+ + min.length
+ + " dimensions");
}
final byte[] bytes;
if (fieldsData == null) {
- bytes = new byte[BYTES*2*min.length];
+ bytes = new byte[BYTES * 2 * min.length];
fieldsData = new BytesRef(bytes);
} else {
- bytes = ((BytesRef)fieldsData).bytes;
+ bytes = ((BytesRef) fieldsData).bytes;
}
verifyAndEncode(min, max, bytes);
}
@@ -109,27 +121,29 @@ public class LongRange extends Field {
/** Encodes the min, max ranges into a byte array */
static byte[] encode(long[] min, long[] max) {
checkArgs(min, max);
- byte[] b = new byte[BYTES*2*min.length];
+ byte[] b = new byte[BYTES * 2 * min.length];
verifyAndEncode(min, max, b);
return b;
}
/**
* encode the ranges into a sortable byte array ({@code Double.NaN} not allowed)
- * <p>
- * example for 4 dimensions (8 bytes per dimension value):
- * minD1 ... minD4 | maxD1 ... maxD4
+ *
+ * <p>example for 4 dimensions (8 bytes per dimension value): minD1 ... minD4 | maxD1 ... maxD4
*/
static void verifyAndEncode(long[] min, long[] max, byte[] bytes) {
- for (int d=0,i=0,j=min.length*BYTES; d<min.length; ++d, i+=BYTES, j+=BYTES) {
+ for (int d = 0, i = 0, j = min.length * BYTES; d < min.length; ++d, i += BYTES, j += BYTES) {
if (Double.isNaN(min[d])) {
- throw new IllegalArgumentException("invalid min value (" + Double.NaN + ")" + " in LongRange");
+ throw new IllegalArgumentException(
+ "invalid min value (" + Double.NaN + ")" + " in LongRange");
}
if (Double.isNaN(max[d])) {
- throw new IllegalArgumentException("invalid max value (" + Double.NaN + ")" + " in LongRange");
+ throw new IllegalArgumentException(
+ "invalid max value (" + Double.NaN + ")" + " in LongRange");
}
if (min[d] > max[d]) {
- throw new IllegalArgumentException("min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
+ throw new IllegalArgumentException(
+ "min value (" + min[d] + ") is greater than max value (" + max[d] + ")");
}
encode(min[d], bytes, i);
encode(max[d], bytes, j);
@@ -143,43 +157,47 @@ public class LongRange extends Field {
/**
* Get the min value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded min value
*/
public long getMin(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMin(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMin(((BytesRef) fieldsData).bytes, dimension);
}
/**
* Get the max value for the given dimension
+ *
* @param dimension the dimension, always positive
* @return the decoded max value
*/
public long getMax(int dimension) {
- Objects.checkIndex(dimension, type.pointDimensionCount()/2);
- return decodeMax(((BytesRef)fieldsData).bytes, dimension);
+ Objects.checkIndex(dimension, type.pointDimensionCount() / 2);
+ return decodeMax(((BytesRef) fieldsData).bytes, dimension);
}
/** decodes the min value (for the defined dimension) from the encoded input byte array */
static long decodeMin(byte[] b, int dimension) {
- int offset = dimension*BYTES;
+ int offset = dimension * BYTES;
return NumericUtils.sortableBytesToLong(b, offset);
}
/** decodes the max value (for the defined dimension) from the encoded input byte array */
static long decodeMax(byte[] b, int dimension) {
- int offset = b.length/2 + dimension*BYTES;
+ int offset = b.length / 2 + dimension * BYTES;
return NumericUtils.sortableBytesToLong(b, offset);
}
/**
* Create a query for matching indexed ranges that intersect the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Long.MIN_VALUE})
* @param max array of max values. (accepts {@code Long.MAX_VALUE})
* @return query for matching intersecting ranges (overlap, within, or contains)
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newIntersectsQuery(String field, final long[] min, final long[] max) {
return newRelationQuery(field, min, max, QueryType.INTERSECTS);
@@ -187,11 +205,13 @@ public class LongRange extends Field {
/**
* Create a query for matching indexed ranges that contain the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Long.MIN_VALUE})
* @param max array of max values. (accepts {@code Long.MAX_VALUE})
* @return query for matching ranges that contain the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newContainsQuery(String field, final long[] min, final long[] max) {
return newRelationQuery(field, min, max, QueryType.CONTAINS);
@@ -199,32 +219,37 @@ public class LongRange extends Field {
/**
* Create a query for matching indexed ranges that are within the defined range.
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Long.MIN_VALUE})
* @param max array of max values. (accepts {@code Long.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newWithinQuery(String field, final long[] min, final long[] max) {
return newRelationQuery(field, min, max, QueryType.WITHIN);
}
/**
- * Create a query for matching indexed ranges that cross the defined range.
- * A CROSSES is defined as any set of ranges that are not disjoint and not wholly contained by
- * the query. Effectively, its the complement of union(WITHIN, DISJOINT).
+ * Create a query for matching indexed ranges that cross the defined range. A CROSSES is defined
+ * as any set of ranges that are not disjoint and not wholly contained by the query. Effectively,
+ * its the complement of union(WITHIN, DISJOINT).
+ *
* @param field field name. must not be null.
* @param min array of min values. (accepts {@code Long.MIN_VALUE})
* @param max array of max values. (accepts {@code Long.MAX_VALUE})
* @return query for matching ranges within the defined range
- * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is invalid
+ * @throws IllegalArgumentException if {@code field} is null, {@code min} or {@code max} is
+ * invalid
*/
public static Query newCrossesQuery(String field, final long[] min, final long[] max) {
return newRelationQuery(field, min, max, QueryType.CROSSES);
}
/** helper method for creating the desired relational query */
- private static Query newRelationQuery(String field, final long[] min, final long[] max, QueryType relation) {
+ private static Query newRelationQuery(
+ String field, final long[] min, final long[] max, QueryType relation) {
checkArgs(min, max);
return new RangeFieldQuery(field, encode(min, max), min.length, relation) {
@Override
@@ -241,7 +266,7 @@ public class LongRange extends Field {
sb.append(" <");
sb.append(name);
sb.append(':');
- byte[] b = ((BytesRef)fieldsData).bytes;
+ byte[] b = ((BytesRef) fieldsData).bytes;
toString(b, 0);
for (int d = 0; d < type.pointDimensionCount() / 2; ++d) {
sb.append(' ');
@@ -254,12 +279,16 @@ public class LongRange extends Field {
/**
* Returns the String representation for the range at the given dimension
+ *
* @param ranges the encoded ranges, never null
* @param dimension the dimension of interest
* @return The string representation for the range at the provided dimension
*/
private static String toString(byte[] ranges, int dimension) {
- return "[" + Long.toString(decodeMin(ranges, dimension)) + " : "
- + Long.toString(decodeMax(ranges, dimension)) + "]";
+ return "["
+ + Long.toString(decodeMin(ranges, dimension))
+ + " : "
+ + Long.toString(decodeMax(ranges, dimension))
+ + "]";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/LongRangeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/LongRangeDocValuesField.java
index 458635e..02433df 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongRangeDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongRangeDocValuesField.java
@@ -20,10 +20,10 @@ package org.apache.lucene.document;
import org.apache.lucene.search.Query;
/**
- * DocValues field for LongRange. This is a single valued field per document
- * due to being an extension of BinaryDocValuesField.
+ * DocValues field for LongRange. This is a single valued field per document due to being an
+ * extension of BinaryDocValuesField.
*/
-public class LongRangeDocValuesField extends BinaryRangeDocValuesField{
+public class LongRangeDocValuesField extends BinaryRangeDocValuesField {
final String field;
final long[] min;
final long[] max;
@@ -55,22 +55,23 @@ public class LongRangeDocValuesField extends BinaryRangeDocValuesField{
return max[dimension];
}
- private static Query newSlowRangeQuery(String field, final long[] min, final long[] max,
- RangeFieldQuery.QueryType queryType) {
+ private static Query newSlowRangeQuery(
+ String field, final long[] min, final long[] max, RangeFieldQuery.QueryType queryType) {
checkArgs(min, max);
return new LongRangeSlowRangeQuery(field, min, max, queryType);
}
- /** Create a new range query that finds all ranges that intersect using doc values.
- * NOTE: This doesn't leverage indexing and may be slow.
- * @see LongRange#newIntersectsQuery */
+ /**
+ * Create a new range query that finds all ranges that intersect using doc values. NOTE: This
+ * doesn't leverage indexing and may be slow.
+ *
+ * @see LongRange#newIntersectsQuery
+ */
public static Query newSlowIntersectsQuery(String field, final long[] min, final long[] max) {
return newSlowRangeQuery(field, min, max, RangeFieldQuery.QueryType.INTERSECTS);
}
- /**
- * validate the arguments
- */
+ /** validate the arguments */
private static void checkArgs(final long[] min, final long[] max) {
if (min == null || max == null || min.length == 0 || max.length == 0) {
throw new IllegalArgumentException("min/max range values cannot be null or empty");
diff --git a/lucene/core/src/java/org/apache/lucene/document/LongRangeSlowRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/LongRangeSlowRangeQuery.java
index 8564381..a4c1645 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LongRangeSlowRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LongRangeSlowRangeQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
-
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryVisitor;
@@ -30,7 +29,8 @@ class LongRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
private final long[] min;
private final long[] max;
- LongRangeSlowRangeQuery(String field, long[] min, long[] max, RangeFieldQuery.QueryType queryType) {
+ LongRangeSlowRangeQuery(
+ String field, long[] min, long[] max, RangeFieldQuery.QueryType queryType) {
super(field, encodeRanges(min, max), LongRange.BYTES, min.length, queryType);
this.field = field;
this.min = min;
@@ -70,8 +70,7 @@ class LongRangeSlowRangeQuery extends BinaryRangeFieldRangeQuery {
if (this.field.equals(field) == false) {
b.append(this.field).append(":");
}
- return b
- .append("[")
+ return b.append("[")
.append(Arrays.toString(min))
.append(" TO ")
.append(Arrays.toString(max))
diff --git a/lucene/core/src/java/org/apache/lucene/document/NumericDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/NumericDocValuesField.java
index 0b20ca9..3fc36a4 100644
--- a/lucene/core/src/java/org/apache/lucene/document/NumericDocValuesField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/NumericDocValuesField.java
@@ -16,9 +16,7 @@
*/
package org.apache.lucene.document;
-
import java.io.IOException;
-
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.LeafReader;
@@ -28,32 +26,28 @@ import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
/**
- * <p>
- * Field that stores a per-document <code>long</code> value for scoring,
- * sorting or value retrieval. Here's an example usage:
- *
+ * Field that stores a per-document <code>long</code> value for scoring, sorting or value retrieval.
+ * Here's an example usage:
+ *
* <pre class="prettyprint">
* document.add(new NumericDocValuesField(name, 22L));
* </pre>
- *
- * <p>
- * If you also need to store the value, you should add a
- * separate {@link StoredField} instance.
- * */
-
+ *
+ * <p>If you also need to store the value, you should add a separate {@link StoredField} instance.
+ */
public class NumericDocValuesField extends Field {
- /**
- * Type for numeric DocValues.
- */
+ /** Type for numeric DocValues. */
public static final FieldType TYPE = new FieldType();
+
static {
TYPE.setDocValuesType(DocValuesType.NUMERIC);
TYPE.freeze();
}
- /**
- * Creates a new DocValues field with the specified 64-bit long value
+ /**
+ * Creates a new DocValues field with the specified 64-bit long value
+ *
* @param name field name
* @param value 64-bit long value
* @throws IllegalArgumentException if the field name is null
@@ -64,8 +58,10 @@ public class NumericDocValuesField extends Field {
/**
* Creates a new DocValues field with the specified 64-bit long value
+ *
* @param name field name
- * @param value 64-bit long value or <code>null</code> if the existing fields value should be removed on update
+ * @param value 64-bit long value or <code>null</code> if the existing fields value should be
+ * removed on update
* @throws IllegalArgumentException if the field name is null
*/
public NumericDocValuesField(String name, Long value) {
@@ -74,18 +70,18 @@ public class NumericDocValuesField extends Field {
}
/**
- * Create a range query that matches all documents whose value is between
- * {@code lowerValue} and {@code upperValue} included.
- * <p>
- * You can have half-open ranges (which are in fact </≤ or >/≥ queries)
- * by setting {@code lowerValue = Long.MIN_VALUE} or {@code upperValue = Long.MAX_VALUE}.
- * <p>
- * Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)}
- * or {@code Math.addExact(upperValue, -1)}.
- * <p><b>NOTE</b>: Such queries cannot efficiently advance to the next match,
- * which makes them slow if they are not ANDed with a selective query. As a
- * consequence, they are best used wrapped in an {@link IndexOrDocValuesQuery},
- * alongside a range query that executes on points, such as
+ * Create a range query that matches all documents whose value is between {@code lowerValue} and
+ * {@code upperValue} included.
+ *
+ * <p>You can have half-open ranges (which are in fact </≤ or >/≥ queries) by setting
+ * {@code lowerValue = Long.MIN_VALUE} or {@code upperValue = Long.MAX_VALUE}.
+ *
+ * <p>Ranges are inclusive. For exclusive ranges, pass {@code Math.addExact(lowerValue, 1)} or
+ * {@code Math.addExact(upperValue, -1)}.
+ *
+ * <p><b>NOTE</b>: Such queries cannot efficiently advance to the next match, which makes them
+ * slow if they are not ANDed with a selective query. As a consequence, they are best used wrapped
+ * in an {@link IndexOrDocValuesQuery}, alongside a range query that executes on points, such as
* {@link LongPoint#newRangeQuery}.
*/
public static Query newSlowRangeQuery(String field, long lowerValue, long upperValue) {
@@ -101,12 +97,12 @@ public class NumericDocValuesField extends Field {
... 9615 lines suppressed ...