You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ja...@apache.org on 2025/05/07 00:11:36 UTC
(lucene) branch branch_10x updated (b2fbcd25898 -> af62580a673)
This is an automated email from the ASF dual-hosted git repository.
jainankitk pushed a change to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/lucene.git
from b2fbcd25898 Fix for Windows (spaces in paths) #14608
new a5e5e9af1d7 Move sloppySin into SloppyMath from GeoUtils (#14516)
new 0a354cbd109 Enabling histogram collection for PointRangeQuery (#14560)
new af62580a673 Improve user-facing docs for geo package (#14534)
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
lucene/CHANGES.txt | 9 +-
.../lucene/benchmark/jmh/RectangleBenchmark.java | 122 +++++++++++++++++++++
.../jmh/{Main.java => SloppySinBenchmark.java} | 34 ++++--
.../src/java/org/apache/lucene/geo/Circle.java | 38 +++++--
.../src/java/org/apache/lucene/geo/GeoUtils.java | 48 ++++----
.../src/java/org/apache/lucene/geo/Rectangle.java | 51 +++++++--
.../java/org/apache/lucene/geo/package-info.java | 51 ++++++++-
.../java/org/apache/lucene/util/SloppyMath.java | 26 +++++
.../org/apache/lucene/util/TestSloppyMath.java | 33 +++++-
.../facet/plain/histograms/HistogramCollector.java | 56 +++++++++-
.../plain/histograms/PointTreeBulkCollector.java | 51 +++++++--
.../histograms/TestHistogramCollectorManager.java | 74 +++++++++++++
12 files changed, 522 insertions(+), 71 deletions(-)
create mode 100644 lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/RectangleBenchmark.java
copy lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/{Main.java => SloppySinBenchmark.java} (53%)
(lucene) 03/03: Improve user-facing docs for geo package (#14534)
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jainankitk pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/lucene.git
commit af62580a67349379abf750e95d40931ae45056e7
Author: Ankit Jain <ja...@gmail.com>
AuthorDate: Tue May 6 17:06:15 2025 -0700
Improve user-facing docs for geo package (#14534)
---
lucene/CHANGES.txt | 4 +-
.../src/java/org/apache/lucene/geo/Circle.java | 38 +++++++++++-----
.../src/java/org/apache/lucene/geo/GeoUtils.java | 23 +++++++++-
.../src/java/org/apache/lucene/geo/Rectangle.java | 47 +++++++++++++++++---
.../java/org/apache/lucene/geo/package-info.java | 51 +++++++++++++++++++++-
5 files changed, 142 insertions(+), 21 deletions(-)
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 4da1266d712..2cb76d44ea4 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -22,10 +22,12 @@ New Features
Improvements
---------------------
-* GITHUB#14458 : Add an IndexDeletion policy that retains the last N commits. (Owais Kazi)
+* GITHUB#14458: Add an IndexDeletion policy that retains the last N commits. (Owais Kazi)
* GITHUB#14476: Removing unnecessary splitX in ComponentTree (Ankit Jain)
+* GITHUB#14534: Improve user-facing docs for geo package (Ankit Jain)
+
* GITHUB#14602: Refactor the expressions compiler to use official ClassData BSM with indexed lookup
(Uwe Schindler)
diff --git a/lucene/core/src/java/org/apache/lucene/geo/Circle.java b/lucene/core/src/java/org/apache/lucene/geo/Circle.java
index 9d5357a7111..c079b8000dd 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/Circle.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/Circle.java
@@ -17,27 +17,43 @@
package org.apache.lucene.geo;
/**
- * Represents a circle on the earth's surface.
+ * Represents a circle on the Earth's surface defined by a center point and radius.
*
- * <p>NOTES:
+ * <p>The circle is defined using:
*
- * <ol>
- * <li>Latitude/longitude values must be in decimal degrees.
- * <li>Radius must be in meters.
- * <li>For more advanced GeoSpatial indexing and query operations see the {@code spatial-extras}
- * module
- * </ol>
+ * <ul>
+ * <li>Center point (latitude/longitude in degrees)
+ * <li>Radius in meters
+ * </ul>
+ *
+ * <p>Important Notes:
+ *
+ * <ul>
+ * <li>The circle is approximated on the spherical Earth model
+ * <li>For very large circles or circles near poles, consider using polygons instead
+ * <li>Dateline crossing is handled automatically
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * // Create a circle with 1km radius around the Eiffel Tower
+ * Circle circle = new Circle(48.8584, 2.2945, 1000);
+ *
+ * // Create a query using this circle
+ * Query query = LatLonShape.newDistanceQuery("location", circle);
+ * }</pre>
*
* @lucene.experimental
*/
public final class Circle extends LatLonGeometry {
- /** Center latitude */
+ /** Center latitude of the circle in degrees (-90 to 90) */
private final double lat;
- /** Center longitude */
+ /** Center longitude of the circle in degrees (-180 to 180) */
private final double lon;
- /** radius in meters */
+ /** radius of the circle in meters */
private final double radiusMeters;
/** Creates a new circle from the supplied latitude/longitude center and a radius in meters.. */
diff --git a/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java b/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
index 7f7278d066c..16c2ecd80f4 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
@@ -23,7 +23,28 @@ import org.apache.lucene.index.PointValues.Relation;
import org.apache.lucene.util.SloppyMath;
/**
- * Basic reusable geo-spatial utility methods
+ * Utility methods for geo-spatial calculations and coordinate validation.
+ *
+ * <p>This class provides:
+ *
+ * <ul>
+ * <li>Coordinate validation methods
+ * <li>Earth model constants
+ * <li>Common geometric calculations
+ * <li>Coordinate normalization utilities
+ * </ul>
+ *
+ * <p>Important Constants:
+ *
+ * <ul>
+ * <li>Earth's mean radius: 6,371,008.7714 meters
+ * <li>Latitude range: -90° to +90°
+ * <li>Longitude range: -180° to +180°
+ * </ul>
+ *
+ * <p>Note: This class uses a spherical Earth model for simplicity and performance. For applications
+ * requiring higher precision, consider using a geodetic library that implements the WGS84 ellipsoid
+ * model.
*
* @lucene.experimental
*/
diff --git a/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java b/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
index 6435d745243..63fa0a17422 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
@@ -32,18 +32,51 @@ import static org.apache.lucene.util.SloppyMath.asin;
import static org.apache.lucene.util.SloppyMath.cos;
import static org.apache.lucene.util.SloppyMath.sin;
-/** Represents a lat/lon rectangle. */
+/**
+ * Represents a rectangular bounding box on Earth's surface.
+ *
+ * <p>A rectangle is defined by its minimum and maximum latitude/longitude coordinates. It can cross
+ * the dateline, in which case minLon > maxLon.
+ *
+ * <p>Key Features:
+ *
+ * <ul>
+ * <li>Handles dateline crossing automatically
+ * <li>Supports point-in-box testing
+ * <li>Can be used to create spatial queries
+ * <li>Useful for creating bounding boxes around other shapes
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * // Create a rectangle covering central London
+ * Rectangle bbox = new Rectangle(51.4, 51.6, -0.2, 0.0);
+ *
+ * // Create a rectangle crossing the dateline
+ * Rectangle datelineBox = new Rectangle(20, 30, 170, -170);
+ *
+ * // Create a bounding box around a point with given radius
+ * Rectangle circle = Rectangle.fromPointDistance(lat, lon, radiusMeters);
+ * }</pre>
+ *
+ * <p>Note: When working with areas near poles, consider that rectangles become highly distorted and
+ * may not provide accurate representation of the actual area.
+ */
public class Rectangle extends LatLonGeometry {
- /** maximum longitude value (in degrees) */
+ /** Minimum latitude in degrees (-90 to 90) */
public final double minLat;
- /** minimum longitude value (in degrees) */
- public final double minLon;
-
- /** maximum latitude value (in degrees) */
+ /** Maximum latitude in degrees (-90 to 90) */
public final double maxLat;
- /** minimum latitude value (in degrees) */
+ /**
+ * Minimum longitude in degrees (-180 to 180). May be greater than maxLon when crossing the
+ * dateline.
+ */
+ public final double minLon;
+
+ /** Maximum longitude in degrees (-180 to 180) */
public final double maxLon;
/**
diff --git a/lucene/core/src/java/org/apache/lucene/geo/package-info.java b/lucene/core/src/java/org/apache/lucene/geo/package-info.java
index b0e6d3224e2..bb34fa8daea 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/package-info.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/package-info.java
@@ -15,5 +15,54 @@
* limitations under the License.
*/
-/** Geospatial Utility Implementations for Lucene Core */
+/**
+ * Core geo-spatial types and utilities for handling geographical data and spatial operations in
+ * Lucene.
+ *
+ * <h2>Overview</h2>
+ *
+ * This package provides classes for representing, indexing, and querying geographical data in
+ * Lucene. It uses the WGS84 coordinate system with latitude/longitude pairs to represent points on
+ * Earth.
+ *
+ * <h2>Core Concepts</h2>
+ *
+ * <ul>
+ * <li>Coordinate System: WGS84 (World Geodetic System 1984)
+ * <ul>
+ * <li>Latitude: -90° to +90° (negative for South, positive for North)
+ * <li>Longitude: -180° to +180° (negative for West, positive for East)
+ * </ul>
+ * <li>Distance calculations use haversine formula on a spherical Earth model
+ * <li>Areas near poles and the dateline receive special handling
+ * </ul>
+ *
+ * <h2>Key Components</h2>
+ *
+ * <ul>
+ * <li>{@link org.apache.lucene.geo.Point}: Represents a point on Earth's surface
+ * <li>{@link org.apache.lucene.geo.Rectangle}: Defines a bounding box for spatial queries
+ * <li>{@link org.apache.lucene.geo.Circle}: Represents a circular area with a center point and
+ * radius
+ * <li>{@link org.apache.lucene.geo.Polygon}: Represents an arbitrary polygon shape
+ * <li>{@link org.apache.lucene.geo.Line}: Represents a path or line string
+ * </ul>
+ *
+ * <h2>Common Operations</h2>
+ *
+ * <ul>
+ * <li>Distance calculations between points
+ * <li>Point-in-polygon testing
+ * <li>Rectangle containment and intersection
+ * <li>Creation of bounding boxes
+ * <li>Polygon validation and preprocessing
+ * </ul>
+ *
+ * <h2>Usage Examples</h2>
+ *
+ * <pre>{@code
+ * Rectangle bbox = Rectangle.fromPointDistance(51.5, -0.12, 5000); // 5km around London
+ * Circle circle = new Circle(48.8566, 2.3522, 1000); // 1km around Paris
+ * }</pre>
+ */
package org.apache.lucene.geo;
(lucene) 01/03: Move sloppySin into SloppyMath from GeoUtils (#14516)
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jainankitk pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/lucene.git
commit a5e5e9af1d7207efd1707259a6622feca27df9c1
Author: Ankit Jain <ja...@gmail.com>
AuthorDate: Tue May 6 16:31:47 2025 -0700
Move sloppySin into SloppyMath from GeoUtils (#14516)
---
lucene/CHANGES.txt | 3 +
.../lucene/benchmark/jmh/RectangleBenchmark.java | 122 +++++++++++++++++++++
.../lucene/benchmark/jmh/SloppySinBenchmark.java | 47 ++++++++
.../src/java/org/apache/lucene/geo/GeoUtils.java | 25 -----
.../src/java/org/apache/lucene/geo/Rectangle.java | 4 +-
.../java/org/apache/lucene/util/SloppyMath.java | 26 +++++
.../org/apache/lucene/util/TestSloppyMath.java | 33 +++++-
7 files changed, 231 insertions(+), 29 deletions(-)
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index f947047b439..e6ce6fa80ea 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -54,6 +54,9 @@ Other
* GITHUB#7145: Adding basic unit tests for SpanWithinQuery. (Jakub Slowinski)
+* GITHUB#14516: Move sloppySin into SloppyMath from GeoUtils (Ankit Jain)
+
+
======================= Lucene 10.2.1 =======================
Bug Fixes
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/RectangleBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/RectangleBenchmark.java
new file mode 100644
index 00000000000..801d706b7d9
--- /dev/null
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/RectangleBenchmark.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.benchmark.jmh;
+
+import static java.lang.Math.PI;
+import static java.lang.Math.max;
+import static java.lang.Math.min;
+import static org.apache.lucene.geo.GeoUtils.EARTH_MEAN_RADIUS_METERS;
+import static org.apache.lucene.geo.GeoUtils.MAX_LAT_RADIANS;
+import static org.apache.lucene.geo.GeoUtils.MAX_LON_RADIANS;
+import static org.apache.lucene.geo.GeoUtils.MIN_LAT_RADIANS;
+import static org.apache.lucene.geo.GeoUtils.MIN_LON_RADIANS;
+import static org.apache.lucene.geo.GeoUtils.checkLatitude;
+import static org.apache.lucene.geo.GeoUtils.checkLongitude;
+import static org.apache.lucene.util.SloppyMath.asin;
+import static org.apache.lucene.util.SloppyMath.cos;
+
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.geo.Rectangle;
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@Fork(value = 1, warmups = 1)
+@Warmup(iterations = 1, time = 1)
+@Measurement(iterations = 3, time = 2)
+public class RectangleBenchmark {
+
+ @State(Scope.Benchmark)
+ public static class ExecutionPlan {
+ // Test cases representing different geographical scenarios
+ @Param({
+ "0.0", // Equator
+ "45.0", // Mid-latitude
+ "89.0", // Near pole
+ "-45.0", // Southern hemisphere
+ "-89.0" // Near south pole
+ })
+ private double latitude;
+
+ @Param({
+ "0.0", // Prime meridian
+ "179.0", // Near dateline
+ "-179.0", // Near dateline other side
+ "90.0", // Mid-longitude
+ "-90.0" // Mid-longitude west
+ })
+ private double longitude;
+
+ @Param({
+ "100", // Small radius (100m)
+ "1000", // 1km
+ "10000", // 10km
+ "100000", // 100km
+ "1000000" // 1000km
+ })
+ private double radiusMeters;
+ }
+
+ @Benchmark
+ public Rectangle benchmarkFromPointDistanceSloppySin(ExecutionPlan plan) {
+ return Rectangle.fromPointDistance(plan.latitude, plan.longitude, plan.radiusMeters);
+ }
+
+ @Benchmark
+ public Rectangle benchmarkFromPointDistanceStandardSin(ExecutionPlan plan) {
+ return fromPointDistanceStandardSin(plan.latitude, plan.longitude, plan.radiusMeters);
+ }
+
+ private static Rectangle fromPointDistanceStandardSin(
+ final double centerLat, final double centerLon, final double radiusMeters) {
+ checkLatitude(centerLat);
+ checkLongitude(centerLon);
+ final double radLat = Math.toRadians(centerLat);
+ final double radLon = Math.toRadians(centerLon);
+ // LUCENE-7143
+ double radDistance = (radiusMeters + 7E-2) / EARTH_MEAN_RADIUS_METERS;
+ double minLat = radLat - radDistance;
+ double maxLat = radLat + radDistance;
+ double minLon;
+ double maxLon;
+
+ if (minLat > MIN_LAT_RADIANS && maxLat < MAX_LAT_RADIANS) {
+ double deltaLon = asin(Math.sin(radDistance) / cos(radLat));
+ minLon = radLon - deltaLon;
+ if (minLon < MIN_LON_RADIANS) {
+ minLon += 2d * PI;
+ }
+ maxLon = radLon + deltaLon;
+ if (maxLon > MAX_LON_RADIANS) {
+ maxLon -= 2d * PI;
+ }
+ } else {
+ // a pole is within the distance
+ minLat = max(minLat, MIN_LAT_RADIANS);
+ maxLat = min(maxLat, MAX_LAT_RADIANS);
+ minLon = MIN_LON_RADIANS;
+ maxLon = MAX_LON_RADIANS;
+ }
+
+ return new Rectangle(
+ Math.toDegrees(minLat),
+ Math.toDegrees(maxLat),
+ Math.toDegrees(minLon),
+ Math.toDegrees(maxLon));
+ }
+}
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/SloppySinBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/SloppySinBenchmark.java
new file mode 100644
index 00000000000..337b60bd6a6
--- /dev/null
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/SloppySinBenchmark.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.benchmark.jmh;
+
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.util.SloppyMath;
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@Fork(value = 1, warmups = 1)
+@Warmup(iterations = 1, time = 1)
+@Measurement(iterations = 3, time = 2)
+public class SloppySinBenchmark {
+ @Benchmark
+ public double standardSin(ExecutionPlan plan) {
+ return Math.sin(plan.value);
+ }
+
+ @Benchmark
+ public double sloppySin(ExecutionPlan plan) {
+ return SloppyMath.sin(plan.value);
+ }
+
+ @State(Scope.Benchmark)
+ public static class ExecutionPlan {
+
+ // Test with different input ranges
+ @Param({"0.1", "0.5", "1.0", "2.0", "3.14"})
+ public double value;
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java b/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
index 825961ffa1b..7f7278d066c 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/GeoUtils.java
@@ -16,7 +16,6 @@
*/
package org.apache.lucene.geo;
-import static org.apache.lucene.util.SloppyMath.cos;
import static org.apache.lucene.util.SloppyMath.haversinMeters;
import org.apache.lucene.index.PointValues;
@@ -87,30 +86,6 @@ public final class GeoUtils {
}
}
- // some sloppyish stuff, do we really need this to be done in a sloppy way?
- // unless it is performance sensitive, we should try to remove.
- private static final double PIO2 = Math.PI / 2D;
-
- /**
- * Returns the trigonometric sine of an angle converted as a cos operation.
- *
- * <p>Note that this is not quite right... e.g. sin(0) != 0
- *
- * <p>Special cases:
- *
- * <ul>
- * <li>If the argument is {@code NaN} or an infinity, then the result is {@code NaN}.
- * </ul>
- *
- * @param a an angle, in radians.
- * @return the sine of the argument.
- * @see Math#sin(double)
- */
- // TODO: deprecate/remove this? at least its no longer public.
- public static double sloppySin(double a) {
- return cos(a - PIO2);
- }
-
/**
* binary search to find the exact sortKey needed to match the specified radius any sort key lte
* this is a query match.
diff --git a/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java b/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
index e5406b5d3db..6435d745243 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/Rectangle.java
@@ -28,9 +28,9 @@ import static org.apache.lucene.geo.GeoUtils.MIN_LAT_RADIANS;
import static org.apache.lucene.geo.GeoUtils.MIN_LON_RADIANS;
import static org.apache.lucene.geo.GeoUtils.checkLatitude;
import static org.apache.lucene.geo.GeoUtils.checkLongitude;
-import static org.apache.lucene.geo.GeoUtils.sloppySin;
import static org.apache.lucene.util.SloppyMath.asin;
import static org.apache.lucene.util.SloppyMath.cos;
+import static org.apache.lucene.util.SloppyMath.sin;
/** Represents a lat/lon rectangle. */
public class Rectangle extends LatLonGeometry {
@@ -121,7 +121,7 @@ public class Rectangle extends LatLonGeometry {
double maxLon;
if (minLat > MIN_LAT_RADIANS && maxLat < MAX_LAT_RADIANS) {
- double deltaLon = asin(sloppySin(radDistance) / cos(radLat));
+ double deltaLon = asin(sin(radDistance) / cos(radLat));
minLon = radLon - deltaLon;
if (minLon < MIN_LON_RADIANS) {
minLon += 2d * PI;
diff --git a/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java b/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
index cb8c6cc0273..b992355751b 100644
--- a/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
+++ b/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
@@ -178,6 +178,32 @@ public class SloppyMath {
}
}
+ // some sloppyish stuff, do we really need this to be done in a sloppy way?
+ // unless it is performance sensitive, we should try to remove.
+ // This is performance sensitive, check SloppySinBenchmark and RectangleBenchmark
+ private static final double PIO2 = Math.PI / 2D;
+
+ /**
+ * Returns the trigonometric sine of an angle converted as a cos operation.
+ *
+ * <p>Error is around 1E-12.
+ *
+ * <p>Note that this is not quite right... e.g. sin(0) != 0
+ *
+ * <p>Special cases:
+ *
+ * <ul>
+ * <li>If the argument is {@code NaN} or an infinity, then the result is {@code NaN}.
+ * </ul>
+ *
+ * @param a an angle, in radians.
+ * @return the sine of the argument.
+ * @see Math#sin(double)
+ */
+ public static double sin(double a) {
+ return cos(a - PIO2);
+ }
+
// Earth's mean radius, in meters and kilometers; see
// http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf
private static final double TO_METERS = 6_371_008.7714D; // equatorial radius
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestSloppyMath.java b/lucene/core/src/test/org/apache/lucene/util/TestSloppyMath.java
index cd70093514e..7b96a3e8896 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestSloppyMath.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestSloppyMath.java
@@ -20,6 +20,7 @@ import static org.apache.lucene.util.SloppyMath.asin;
import static org.apache.lucene.util.SloppyMath.cos;
import static org.apache.lucene.util.SloppyMath.haversinMeters;
import static org.apache.lucene.util.SloppyMath.haversinSortKey;
+import static org.apache.lucene.util.SloppyMath.sin;
import java.util.Random;
import org.apache.lucene.tests.geo.GeoTestUtil;
@@ -28,6 +29,8 @@ import org.apache.lucene.tests.util.LuceneTestCase;
public class TestSloppyMath extends LuceneTestCase {
// accuracy for cos()
private static final double COS_DELTA = 1E-15;
+ // accuracy for sin()
+ private static final double SIN_DELTA = 1E-12;
// accuracy for asin()
private static final double ASIN_DELTA = 1E-7;
// accuracy for haversinMeters()
@@ -50,8 +53,8 @@ public class TestSloppyMath extends LuceneTestCase {
assertEquals(StrictMath.cos(Math.PI / 6), cos(Math.PI / 6), COS_DELTA);
assertEquals(StrictMath.cos(-Math.PI / 6), cos(-Math.PI / 6), COS_DELTA);
- // testing purely random longs is inefficent, as for stupid parameters we just
- // pass thru to Math.cos() instead of doing some huperduper arg reduction
+ // testing purely random longs is inefficient, as for stupid parameters we just
+ // pass through to Math.cos() instead of doing some superduper arg reduction
for (int i = 0; i < 10000; i++) {
double d = random().nextDouble() * SloppyMath.SIN_COS_MAX_VALUE_FOR_INT_MODULO;
if (random().nextBoolean()) {
@@ -61,6 +64,32 @@ public class TestSloppyMath extends LuceneTestCase {
}
}
+ public void testSin() {
+ assertTrue(Double.isNaN(sin(Double.NaN)));
+ assertTrue(Double.isNaN(sin(Double.NEGATIVE_INFINITY)));
+ assertTrue(Double.isNaN(sin(Double.POSITIVE_INFINITY)));
+ assertEquals(StrictMath.sin(1), sin(1), SIN_DELTA);
+ assertEquals(StrictMath.sin(0), sin(0), SIN_DELTA);
+ assertEquals(StrictMath.sin(Math.PI / 2), sin(Math.PI / 2), SIN_DELTA);
+ assertEquals(StrictMath.sin(-Math.PI / 2), sin(-Math.PI / 2), SIN_DELTA);
+ assertEquals(StrictMath.sin(Math.PI / 4), sin(Math.PI / 4), SIN_DELTA);
+ assertEquals(StrictMath.sin(-Math.PI / 4), sin(-Math.PI / 4), SIN_DELTA);
+ assertEquals(StrictMath.sin(Math.PI * 2 / 3), sin(Math.PI * 2 / 3), SIN_DELTA);
+ assertEquals(StrictMath.sin(-Math.PI * 2 / 3), sin(-Math.PI * 2 / 3), SIN_DELTA);
+ assertEquals(StrictMath.sin(Math.PI / 6), sin(Math.PI / 6), SIN_DELTA);
+ assertEquals(StrictMath.sin(-Math.PI / 6), sin(-Math.PI / 6), SIN_DELTA);
+
+ // testing purely random longs is inefficient, as for stupid parameters we just
+ // pass through to Math.sin() instead of doing some superduper arg reduction
+ for (int i = 0; i < 10000; i++) {
+ double d = random().nextDouble() * SloppyMath.SIN_COS_MAX_VALUE_FOR_INT_MODULO;
+ if (random().nextBoolean()) {
+ d = -d;
+ }
+ assertEquals(StrictMath.sin(d), sin(d), SIN_DELTA);
+ }
+ }
+
public void testAsin() {
assertTrue(Double.isNaN(asin(Double.NaN)));
assertTrue(Double.isNaN(asin(2)));
(lucene) 02/03: Enabling histogram collection for PointRangeQuery (#14560)
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jainankitk pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/lucene.git
commit 0a354cbd10931c72bd9f6f7114efea8ffbd108f4
Author: Ankit Jain <ja...@gmail.com>
AuthorDate: Tue May 6 16:34:54 2025 -0700
Enabling histogram collection for PointRangeQuery (#14560)
---
lucene/CHANGES.txt | 2 +-
.../facet/plain/histograms/HistogramCollector.java | 56 +++++++++++++++-
.../plain/histograms/PointTreeBulkCollector.java | 51 +++++++++++----
.../histograms/TestHistogramCollectorManager.java | 74 ++++++++++++++++++++++
4 files changed, 169 insertions(+), 14 deletions(-)
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index e6ce6fa80ea..4da1266d712 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -33,7 +33,7 @@ Optimizations
---------------------
* GITHUB#14418: Quick exit on filter query matching no docs when rewriting knn query. (Pan Guixin)
-* GITHUB#14439: Efficient Histogram Collection using multi range traversal over PointTrees (Ankit Jain)
+* GITHUB#14439, GITHUB#14560: Efficient Histogram Collection using multi range traversal over PointTrees (Ankit Jain)
* GITHUB#14268: PointInSetQuery early exit on non-matching segments. (hanbj)
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/HistogramCollector.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/HistogramCollector.java
index ee57ea1e96a..cca4e2b92a4 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/HistogramCollector.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/HistogramCollector.java
@@ -17,7 +17,10 @@
package org.apache.lucene.sandbox.facet.plain.histograms;
import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
import java.util.concurrent.ConcurrentMap;
+import java.util.function.Function;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.DocValuesSkipper;
import org.apache.lucene.index.DocValuesType;
@@ -27,10 +30,16 @@ import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.internal.hppc.LongIntHashMap;
+import org.apache.lucene.queries.function.FunctionScoreQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.CollectionTerminatedException;
import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.DocIdStream;
+import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.LeafCollector;
+import org.apache.lucene.search.PointRangeQuery;
+import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorable;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.Weight;
@@ -67,13 +76,15 @@ final class HistogramCollector implements Collector {
// We can use multi range traversal logic to collect the histogram on numeric
// field indexed as point for MATCH_ALL cases. In future, this can be extended
// for Point Range Query cases as well
- if (weight != null && weight.count(context) == context.reader().maxDoc()) {
+ final PointRangeQuery pointRangeQuery = getPointRangeQuery(field);
+ if (isMatchAll(context) || pointRangeQuery != null) {
final PointValues pointValues = context.reader().getPointValues(field);
if (PointTreeBulkCollector.canCollectEfficiently(pointValues, bucketWidth)) {
// In case of intra segment concurrency, only one collector should collect
// documents for all the partitions to avoid duplications across collectors
if (leafBulkCollected.putIfAbsent(context, true) == null) {
- PointTreeBulkCollector.collect(pointValues, bucketWidth, counts, maxBuckets);
+ PointTreeBulkCollector.collect(
+ pointValues, pointRangeQuery, bucketWidth, counts, maxBuckets);
}
// Either the collection is finished on this collector, or some other collector
// already started that collection, so this collector can finish early!
@@ -330,4 +341,45 @@ final class HistogramCollector implements Collector {
public void setWeight(Weight weight) {
this.weight = weight;
}
+
+ private boolean isMatchAll(LeafReaderContext context) throws IOException {
+ return weight != null && weight.count(context) == context.reader().maxDoc();
+ }
+
+ private static final Map<Class<?>, Function<Query, Query>> queryWrappers;
+
+ // Initialize the wrapper map for unwrapping the query
+ static {
+ queryWrappers = new HashMap<>();
+ queryWrappers.put(BoostQuery.class, q -> ((BoostQuery) q).getQuery());
+ queryWrappers.put(ConstantScoreQuery.class, q -> ((ConstantScoreQuery) q).getQuery());
+ queryWrappers.put(FunctionScoreQuery.class, q -> ((FunctionScoreQuery) q).getWrappedQuery());
+ queryWrappers.put(
+ IndexOrDocValuesQuery.class, q -> ((IndexOrDocValuesQuery) q).getIndexQuery());
+ }
+
+ /** Recursively unwraps query into the concrete form for applying the optimization */
+ private static Query unwrapIntoConcreteQuery(Query query) {
+ while (queryWrappers.containsKey(query.getClass())) {
+ query = queryWrappers.get(query.getClass()).apply(query);
+ }
+
+ return query;
+ }
+
+ private PointRangeQuery getPointRangeQuery(final String field) {
+ if (weight == null || weight.getQuery() == null) {
+ return null;
+ }
+
+ final Query concreteQuery = unwrapIntoConcreteQuery(weight.getQuery());
+
+ if (concreteQuery instanceof PointRangeQuery prq) {
+ if (prq.getField().equals(field)) {
+ return prq;
+ }
+ }
+
+ return null;
+ }
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/PointTreeBulkCollector.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/PointTreeBulkCollector.java
index d70e63237c0..0d664d27e58 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/PointTreeBulkCollector.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/facet/plain/histograms/PointTreeBulkCollector.java
@@ -22,7 +22,9 @@ import java.io.IOException;
import java.util.function.Function;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.internal.hppc.LongIntHashMap;
+import org.apache.lucene.search.CollectionTerminatedException;
import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.util.NumericUtils;
/**
@@ -76,15 +78,23 @@ class PointTreeBulkCollector {
static void collect(
final PointValues pointValues,
+ final PointRangeQuery prq,
final long bucketWidth,
final LongIntHashMap collectorCounts,
final int maxBuckets)
throws IOException {
final Function<byte[], Long> byteToLong = bytesToLong(pointValues.getBytesPerDimension());
+ long leafMin = byteToLong.apply(pointValues.getMinPackedValue());
+ long leafMax = byteToLong.apply(pointValues.getMaxPackedValue());
+ if (prq != null) {
+ leafMin = Math.max(leafMin, byteToLong.apply(prq.getLowerPoint()));
+ leafMax = Math.min(leafMax, byteToLong.apply(prq.getUpperPoint()));
+ }
BucketManager collector =
new BucketManager(
collectorCounts,
- byteToLong.apply(pointValues.getMinPackedValue()),
+ leafMin,
+ leafMax + 1, // the max value is exclusive for collector
bucketWidth,
byteToLong,
maxBuckets);
@@ -135,6 +145,11 @@ class PointTreeBulkCollector {
public void visit(int docID, byte[] packedValue) throws IOException {
if (!collector.withinUpperBound(packedValue)) {
collector.finalizePreviousBucket(packedValue);
+ // If the packedValue is not within upper bound even after updating upper bound,
+ // we have exhausted the max value and should throw early termination error
+ if (!collector.withinUpperBound(packedValue)) {
+ throw new CollectionTerminatedException();
+ }
}
if (collector.withinRange(packedValue)) {
@@ -146,6 +161,11 @@ class PointTreeBulkCollector {
public void visit(DocIdSetIterator iterator, byte[] packedValue) throws IOException {
if (!collector.withinUpperBound(packedValue)) {
collector.finalizePreviousBucket(packedValue);
+ // If the packedValue is not within upper bound even after updating upper bound,
+ // we have exhausted the max value and should throw early termination error
+ if (!collector.withinUpperBound(packedValue)) {
+ throw new CollectionTerminatedException();
+ }
}
if (collector.withinRange(packedValue)) {
@@ -157,9 +177,14 @@ class PointTreeBulkCollector {
@Override
public PointValues.Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
- // try to find the first range that may collect values from this cell
+ // Try to find the first range that may collect values from this cell
if (!collector.withinUpperBound(minPackedValue)) {
collector.finalizePreviousBucket(minPackedValue);
+ // If the minPackedValue is not within upper bound even after updating upper bound,
+ // we have exhausted the max value and should throw early termination error
+ if (!collector.withinUpperBound(minPackedValue)) {
+ throw new CollectionTerminatedException();
+ }
}
// Not possible to have the CELL_OUTSIDE_QUERY, as bucket lower bound is updated
@@ -176,6 +201,7 @@ class PointTreeBulkCollector {
private final LongIntHashMap collectorCounts;
private int counter = 0;
private long startValue;
+ private long maxValue;
private long endValue;
private int nonZeroBuckets = 0;
private int maxBuckets;
@@ -185,13 +211,16 @@ class PointTreeBulkCollector {
public BucketManager(
LongIntHashMap collectorCounts,
long minValue,
+ long maxValue,
long bucketWidth,
Function<byte[], Long> byteToLong,
int maxBuckets) {
this.collectorCounts = collectorCounts;
this.bucketWidth = bucketWidth;
- this.startValue = Math.floorDiv(minValue, bucketWidth) * bucketWidth;
- this.endValue = startValue + bucketWidth;
+ this.startValue = minValue;
+ this.endValue =
+ Math.min((Math.floorDiv(startValue, bucketWidth) + 1) * bucketWidth, maxValue);
+ this.maxValue = maxValue;
this.byteToLong = byteToLong;
this.maxBuckets = maxBuckets;
}
@@ -205,19 +234,19 @@ class PointTreeBulkCollector {
}
private void finalizePreviousBucket(byte[] packedValue) {
- // TODO: Can counter ever be 0?
+ // counter can be 0 for first bucket in case
+ // of Point Range Query
if (counter > 0) {
collectorCounts.addTo(Math.floorDiv(startValue, bucketWidth), counter);
- if (packedValue != null) {
- startValue = byteToLong.apply(packedValue);
- // Align the start value with bucket width
- startValue = Math.floorDiv(startValue, bucketWidth) * bucketWidth;
- endValue = startValue + bucketWidth;
- }
nonZeroBuckets++;
counter = 0;
HistogramCollector.checkMaxBuckets(nonZeroBuckets, maxBuckets);
}
+
+ if (packedValue != null) {
+ startValue = byteToLong.apply(packedValue);
+ endValue = Math.min((Math.floorDiv(startValue, bucketWidth) + 1) * bucketWidth, maxValue);
+ }
}
private boolean withinLowerBound(byte[] value) {
diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/facet/plain/histograms/TestHistogramCollectorManager.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/facet/plain/histograms/TestHistogramCollectorManager.java
index ffa5e825f6f..7632031f041 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/facet/plain/histograms/TestHistogramCollectorManager.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/facet/plain/histograms/TestHistogramCollectorManager.java
@@ -26,16 +26,23 @@ import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.internal.hppc.LongIntHashMap;
+import org.apache.lucene.queries.function.FunctionScoreQuery;
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.DoubleValuesSource;
+import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
+import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
+import org.apache.lucene.util.NumericUtils;
public class TestHistogramCollectorManager extends LuceneTestCase {
@@ -136,6 +143,8 @@ public class TestHistogramCollectorManager extends LuceneTestCase {
DirectoryReader reader = DirectoryReader.open(w);
w.close();
IndexSearcher searcher = newSearcher(reader);
+
+ // Validate the MATCH_ALL case
LongIntHashMap actualCounts =
searcher.search(new MatchAllDocsQuery(), new HistogramCollectorManager("f", 1000));
LongIntHashMap expectedCounts = new LongIntHashMap();
@@ -144,6 +153,71 @@ public class TestHistogramCollectorManager extends LuceneTestCase {
}
assertEquals(expectedCounts, actualCounts);
+ // Validate the Point Range Query case
+ int lowerBound = random().nextInt(0, 1500);
+ int upperBound = random().nextInt(3500, 5000);
+
+ byte[] lowerPoint = new byte[Long.BYTES];
+ byte[] upperPoint = new byte[Long.BYTES];
+ NumericUtils.longToSortableBytes(lowerBound, lowerPoint, 0);
+ NumericUtils.longToSortableBytes(upperBound, upperPoint, 0);
+ final PointRangeQuery prq =
+ new PointRangeQuery("f", lowerPoint, upperPoint, 1) {
+ @Override
+ protected String toString(int dimension, byte[] value) {
+ return Long.toString(NumericUtils.sortableBytesToLong(value, 0));
+ }
+ };
+
+ actualCounts = searcher.search(prq, new HistogramCollectorManager("f", 1000));
+ expectedCounts = new LongIntHashMap();
+ for (long value : values) {
+ if (value >= lowerBound && value <= upperBound) {
+ expectedCounts.addTo(Math.floorDiv(value, 1000), 1);
+ }
+ }
+ assertEquals(expectedCounts, actualCounts);
+
+ // Validate the BoostQuery case
+ actualCounts =
+ searcher.search(new BoostQuery(prq, 1.5f), new HistogramCollectorManager("f", 1000));
+ // Don't need to compute expectedCounts again as underlying point range
+ // query is not changing
+ assertEquals(expectedCounts, actualCounts);
+
+ // Validate the ConstantScoreQuery case
+ actualCounts =
+ searcher.search(new ConstantScoreQuery(prq), new HistogramCollectorManager("f", 1000));
+ // Don't need to compute expectedCounts again as underlying point range query is not changing
+ assertEquals(expectedCounts, actualCounts);
+
+ // Validate the FunctionScoreQuery case
+ actualCounts =
+ searcher.search(
+ new FunctionScoreQuery(prq, DoubleValuesSource.SCORES),
+ new HistogramCollectorManager("f", 1000));
+ // Don't need to compute expectedCounts again as underlying point range query is not changing
+ assertEquals(expectedCounts, actualCounts);
+
+ // Validate the IndexOrDocValuesQuery case
+ actualCounts =
+ searcher.search(
+ new IndexOrDocValuesQuery(prq, prq), new HistogramCollectorManager("f", 1000));
+ // Don't need to compute expectedCounts again as underlying point range query is not changing
+ assertEquals(expectedCounts, actualCounts);
+
+ // Validate the recursive wrapping case
+ actualCounts =
+ searcher.search(
+ new ConstantScoreQuery(
+ new BoostQuery(
+ new FunctionScoreQuery(
+ new IndexOrDocValuesQuery(prq, prq), DoubleValuesSource.SCORES),
+ 1.5f)),
+ new HistogramCollectorManager("f", 1000));
+ // Don't need to compute expectedCounts again as underlying point range query is not changing
+ assertEquals(expectedCounts, actualCounts);
+
reader.close();
dir.close();
}