Skip to content

Apache Lucene open-source search software

Use Lucene's PriorityQueue in NearestNeighbor to replace poll/offer with updateTop (#16154)

Prithvi Sf5622b061ce2
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index a8d9bff22fd..bc49af53e04 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -381,6 +381,8 @@ Optimizations
---------------------
* GITHUB#15861: Optimise PhraseScorer by short circuiting non competitive documents in TOP_SCORES mode. (Prithvi S)
+* GITHUB#16154: Use Lucene's PriorityQueue in NearestNeighbor to avoid poll/offer overhead on the hot path. (Prithvi S)
+
* GITHUB#15868: Optimize DisjunctionMaxBulkScorer by reusing the inner LeafCollector across
sub-scorers and resetting windowScores inline during replay instead of Arrays.fill. (Prithvi S)
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/NearestNeighborBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/NearestNeighborBenchmark.java
new file mode 100644
index 00000000000..1d685888e71
--- /dev/null
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/NearestNeighborBenchmark.java
@@ -0,0 +1,111 @@
+/*
+ * 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.io.IOException;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.LatLonPoint;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.MMapDirectory;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@State(Scope.Benchmark)
+@Warmup(iterations = 5, time = 3)
+@Measurement(iterations = 10, time = 5)
+@Fork(
+ value = 3,
+ jvmArgsAppend = {"-Xmx2g", "-Xms2g"})
+public class NearestNeighborBenchmark {
+
+ @Param({"1", "10", "100"})
+ private int topN;
+
+ @Param({"100000", "1000000"})
+ private int numDocs;
+
+ private static final int NUM_QUERY_POINTS = 1000;
+ private static final long SEED = 0xDEADBEEFCAFEBABEL;
+
+ private Directory dir;
+ private IndexReader reader;
+ private IndexSearcher searcher;
+ private double[] queryLats;
+ private double[] queryLons;
+ private int queryIndex;
+
+ @Setup(Level.Trial)
+ public void setUp() throws IOException {
+ Random random = new Random(SEED);
+ dir = new MMapDirectory(java.nio.file.Files.createTempDirectory("benchmark"));
+ IndexWriterConfig config = new IndexWriterConfig();
+ try (IndexWriter writer = new IndexWriter(dir, config)) {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ double lat = (random.nextDouble() * 180.0) - 90.0;
+ double lon = (random.nextDouble() * 360.0) - 180.0;
+ doc.add(new LatLonPoint("point", lat, lon));
+ writer.addDocument(doc);
+ }
+ }
+ reader = DirectoryReader.open(dir);
+ searcher = new IndexSearcher(reader);
+
+ queryLats = new double[NUM_QUERY_POINTS];
+ queryLons = new double[NUM_QUERY_POINTS];
+ for (int i = 0; i < NUM_QUERY_POINTS; i++) {
+ queryLats[i] = (random.nextDouble() * 180.0) - 90.0;
+ queryLons[i] = (random.nextDouble() * 360.0) - 180.0;
+ }
+ queryIndex = 0;
+ }
+
+ @TearDown(Level.Trial)
+ public void tearDown() throws IOException {
+ reader.close();
+ dir.close();
+ }
+
+ @Benchmark
+ public TopDocs benchmarkNearest() throws IOException {
+ double queryLat = queryLats[queryIndex];
+ double queryLon = queryLons[queryIndex];
+ queryIndex = (queryIndex + 1) % NUM_QUERY_POINTS;
+ return LatLonPoint.nearest(searcher, "point", queryLat, queryLon, topN);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/document/NearestNeighbor.java b/lucene/core/src/java/org/apache/lucene/document/NearestNeighbor.java
index d1431e59075..dedf9ed07f8 100644
--- a/lucene/core/src/java/org/apache/lucene/document/NearestNeighbor.java
+++ b/lucene/core/src/java/org/apache/lucene/document/NearestNeighbor.java
@@ -21,7 +21,6 @@ import static org.apache.lucene.geo.GeoEncodingUtils.decodeLongitude;
import java.io.IOException;
import java.util.List;
-import java.util.PriorityQueue;
import org.apache.lucene.geo.Rectangle;
import org.apache.lucene.index.PointValues;
import org.apache.lucene.index.PointValues.IntersectVisitor;
@@ -29,6 +28,7 @@ import org.apache.lucene.index.PointValues.PointTree;
import org.apache.lucene.index.PointValues.Relation;
import org.apache.lucene.internal.hppc.IntArrayList;
import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.SloppyMath;
/** KNN search on top of 2D lat/lon indexed points. */
@@ -77,12 +77,29 @@ class NearestNeighbor {
}
}
+ private static class NearestHitQueue extends PriorityQueue<NearestHit> {
+ NearestHitQueue(int maxSize) {
+ super(
+ maxSize,
+ (a, b) -> {
+ // Keep the worst hit (highest distance) at the top so it can be evicted when a
+ // better hit arrives.
+ int cmp = Double.compare(a.distanceSortKey, b.distanceSortKey);
+ if (cmp != 0) {
+ return cmp > 0;
+ }
+ // tie-break by higher docID (higher docID = worse)
+ return a.docID > b.docID;
+ });
+ }
+ }
+
private static class NearestVisitor implements IntersectVisitor {
public int curDocBase;
public Bits curLiveDocs;
final int topN;
- final PriorityQueue<NearestHit> hitQueue;
+ final NearestHitQueue hitQueue;
final double pointLat;
final double pointLon;
private int setBottomCounter;
@@ -95,8 +112,7 @@ class NearestNeighbor {
// second set of longitude ranges to check (for cross-dateline case)
private double minLon2 = Double.POSITIVE_INFINITY;
- public NearestVisitor(
- PriorityQueue<NearestHit> hitQueue, int topN, double pointLat, double pointLon) {
+ public NearestVisitor(NearestHitQueue hitQueue, int topN, double pointLat, double pointLon) {
this.hitQueue = hitQueue;
this.topN = topN;
this.pointLat = pointLat;
@@ -110,7 +126,7 @@ class NearestNeighbor {
private void maybeUpdateBBox() {
if (setBottomCounter < 1024 || (setBottomCounter & 0x3F) == 0x3F) {
- NearestHit hit = hitQueue.peek();
+ NearestHit hit = hitQueue.top();
Rectangle box =
Rectangle.fromPointDistance(
pointLat, pointLon, SloppyMath.haversinMeters(hit.distanceSortKey));
@@ -164,15 +180,14 @@ class NearestNeighbor {
if (hitQueue.size() == topN) {
// queue already full
- NearestHit hit = hitQueue.peek();
+ NearestHit hit = hitQueue.top();
// System.out.println(" bottom distanceSortKey=" + hit.distanceSortKey);
// we don't collect docs in order here, so we must also test the tie-break case ourselves:
if (distanceSortKey < hit.distanceSortKey
|| (distanceSortKey == hit.distanceSortKey && fullDocID < hit.docID)) {
- hitQueue.poll();
hit.docID = fullDocID;
hit.distanceSortKey = distanceSortKey;
- hitQueue.offer(hit);
+ hitQueue.updateTop();
// System.out.println(" ** keep2, now bottom=" + hit);
maybeUpdateBBox();
}
@@ -181,7 +196,7 @@ class NearestNeighbor {
NearestHit hit = new NearestHit();
hit.docID = fullDocID;
hit.distanceSortKey = distanceSortKey;
- hitQueue.offer(hit);
+ hitQueue.add(hit);
// System.out.println(" ** keep1, now bottom=" + hit);
}
}
@@ -234,24 +249,12 @@ class NearestNeighbor {
// System.out.println("NEAREST: readers=" + readers + " liveDocs=" + liveDocs + " pointLat=" +
// pointLat + " pointLon=" + pointLon);
+
// Holds closest collected points seen so far:
- // TODO: if we used lucene's PQ we could just updateTop instead of poll/offer:
- final PriorityQueue<NearestHit> hitQueue =
- new PriorityQueue<>(
- n,
- (a, b) -> {
- // sort by opposite distanceSortKey natural order
- int cmp = Double.compare(a.distanceSortKey, b.distanceSortKey);
- if (cmp != 0) {
- return -cmp;
- }
-
- // tie-break by higher docID:
- return b.docID - a.docID;
- });
+ final NearestHitQueue hitQueue = new NearestHitQueue(n);
// Holds all cells, sorted by closest to the point:
- PriorityQueue<Cell> cellQueue = new PriorityQueue<>();
+ java.util.PriorityQueue<Cell> cellQueue = new java.util.PriorityQueue<>();
NearestVisitor visitor = new NearestVisitor(hitQueue, n, pointLat, pointLon);
@@ -327,7 +330,7 @@ class NearestNeighbor {
NearestHit[] hits = new NearestHit[hitQueue.size()];
int downTo = hitQueue.size() - 1;
while (hitQueue.size() != 0) {
- hits[downTo] = hitQueue.poll();
+ hits[downTo] = hitQueue.pop();
downTo--;
}