Apache Lucene open-source search software
Add `NumericFieldStats` for unified numeric field statistics retreival (#15760)
Salvatore Campagna6345fef41458
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 7d140997d55..219cfda4c6c 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -199,7 +199,11 @@ API ChangesNew Features----------------------(No changes)++* GITHUB#15740: Add NumericFieldStats utility for retrieving global numeric field statistics+ (min, max, doc count) from index metadata structures. Migrate SortedNumericDocValuesRangeQuery+ to use this API, fixing the rewrite optimization for fields with PointValues but no skip index.+ (Salvatore Campagna)Improvements---------------------diff --git a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.javaindex 94f248b903e..813b52ab72a 100644--- a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java@@ -34,6 +34,8 @@ import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.MatchNoDocsQuery;import org.apache.lucene.search.NumericDocValuesRangeQuery;+import org.apache.lucene.search.NumericFieldStats;+import org.apache.lucene.search.NumericFieldStats.Stats;import org.apache.lucene.search.Query;import org.apache.lucene.search.QueryVisitor;import org.apache.lucene.search.ScoreMode;@@ -93,16 +95,16 @@ final class SortedNumericDocValuesRangeQuery extends NumericDocValuesRangeQueryif (lowerValue > upperValue) {return MatchNoDocsQuery.INSTANCE;}- long globalMin = DocValuesSkipper.globalMinValue(indexSearcher.getIndexReader(), field);- long globalMax = DocValuesSkipper.globalMaxValue(indexSearcher.getIndexReader(), field);- if (lowerValue > globalMax || upperValue < globalMin) {- return MatchNoDocsQuery.INSTANCE;- }- if (lowerValue <= globalMin- && upperValue >= globalMax- && DocValuesSkipper.globalDocCount(indexSearcher.getIndexReader(), field)- == indexSearcher.getIndexReader().maxDoc()) {- return MatchAllDocsQuery.INSTANCE;+ final Stats stats = NumericFieldStats.getStats(indexSearcher.getIndexReader(), field);+ if (stats != null) {+ if (lowerValue > stats.max() || upperValue < stats.min()) {+ return MatchNoDocsQuery.INSTANCE;+ }+ if (lowerValue <= stats.min()+ && upperValue >= stats.max()+ && stats.docCount() == indexSearcher.getIndexReader().maxDoc()) {+ return MatchAllDocsQuery.INSTANCE;+ }}return super.rewrite(indexSearcher);}diff --git a/lucene/core/src/java/org/apache/lucene/search/NumericFieldStats.java b/lucene/core/src/java/org/apache/lucene/search/NumericFieldStats.javanew file mode 100644index 00000000000..2074155e2f9--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/NumericFieldStats.java@@ -0,0 +1,131 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search;++import java.io.IOException;+import org.apache.lucene.index.DocValuesSkipper;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.PointValues;+import org.apache.lucene.util.NumericUtils;++/**+ * Utility class for retrieving global numeric field statistics from index metadata structures,+ * without accessing individual documents. It probes {@link PointValues} first and falls back to+ * {@link DocValuesSkipper}. Returns {@code null} when neither structure is available for the field.+ *+ * @lucene.experimental+ */+public final class NumericFieldStats {++ private NumericFieldStats() {}++ /**+ * Holds the global statistics for a numeric field.+ *+ * @param min the global minimum value+ * @param max the global maximum value+ * @param docCount the total number of documents containing the field+ */+ public record Stats(long min, long max, int docCount) {}++ /**+ * Returns the global statistics for the given numeric field across all segments. Probes {@link+ * PointValues} first; if unavailable, falls back to {@link DocValuesSkipper}.+ *+ * @param reader the {@link IndexReader} to query+ * @param field the name of the numeric field+ * @return a {@link Stats} containing the global min, max, and doc count, or {@code null} if+ * neither {@link PointValues} nor {@link DocValuesSkipper} are available for the field+ * @throws IOException if an I/O error occurs+ */+ public static Stats getStats(IndexReader reader, String field) throws IOException {+ final Stats result = getStatsFromPoints(reader, field);+ if (result != null) {+ return result;+ }+ return getStatsFromSkipper(reader, field);+ }++ private static Stats getStatsFromPoints(IndexReader reader, String field) throws IOException {+ final byte[] minPacked = PointValues.getMinPackedValue(reader, field);+ final byte[] maxPacked = PointValues.getMaxPackedValue(reader, field);+ if (minPacked == null || maxPacked == null) {+ return null;+ }+ final int docCount = PointValues.getDocCount(reader, field);+ return new Stats(decodeLong(minPacked), decodeLong(maxPacked), docCount);+ }++ private static Stats getStatsFromSkipper(IndexReader reader, String field) throws IOException {+ Long min = null;+ Long max = null;+ int docCount = 0;+ for (LeafReaderContext ctx : reader.leaves()) {+ final LeafReader leafReader = ctx.reader();+ if (leafReader.getFieldInfos().fieldInfo(field) == null) {+ continue;+ }+ final DocValuesSkipper skipper = leafReader.getDocValuesSkipper(field);+ if (skipper == null) {+ return null;+ }+ if (min == null && max == null) {+ min = skipper.minValue();+ max = skipper.maxValue();+ } else {+ min = Math.min(min, skipper.minValue());+ max = Math.max(max, skipper.maxValue());+ }+ docCount += skipper.docCount();+ }+ if (min == null || max == null) {+ return null;+ }+ return new Stats(min, max, docCount);+ }++ /**+ * Decodes a packed {@code byte[]} point value into a {@code long}. {@link PointValues} stores+ * numeric values as big-endian byte arrays with the sign bit flipped for sortable ordering.+ * {@code IntField} produces 4-byte arrays and {@code LongField} produces 8-byte arrays, so we+ * dispatch on length to call the appropriate {@link NumericUtils} decoder. The {@code int} case+ * widens to {@code long} via standard Java sign extension, which preserves the original value.+ *+ * <p>We return {@code long} unconditionally because the query layer already works with {@code+ * long} bounds (e.g. {@code SortedNumericDocValuesRangeQuery} stores its range as {@code long}+ * even for {@code IntField} queries). Callers that need the original {@code int} value can safely+ * narrow with {@code Math.toIntExact()}, which will never throw for values originating from an+ * {@code IntField}.+ */+ private static long decodeLong(byte[] packed) {+ return switch (packed.length) {+ case Integer.BYTES -> NumericUtils.sortableBytesToInt(packed, 0);+ case Long.BYTES -> NumericUtils.sortableBytesToLong(packed, 0);+ default ->+ throw new IllegalArgumentException(+ "Unsupported packed value length: "+ + packed.length+ + " (expected "+ + Long.BYTES+ + " or "+ + Integer.BYTES+ + ")");+ };+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesQueries.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesQueries.javaindex ecdd545779c..22183591c1d 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesQueries.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesQueries.java@@ -29,6 +29,7 @@ import org.apache.lucene.codecs.Codec;import org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.lucene.document.LongField;import org.apache.lucene.document.LongPoint;import org.apache.lucene.document.NumericDocValuesField;import org.apache.lucene.document.SortedDocValuesField;@@ -723,4 +724,30 @@ public class TestDocValuesQueries extends LuceneTestCase {}}}++ public void testRewriteWorksWithPointsButNoSkipIndex() throws IOException {+ try (Directory dir = newDirectory()) {+ try (RandomIndexWriter iw = new RandomIndexWriter(random(), dir)) {+ for (int i = 0; i < 100; i++) {+ final Document doc = new Document();+ doc.add(new LongField("field", 100 + i, Field.Store.NO));+ iw.addDocument(doc);+ }+ iw.commit();+ try (IndexReader reader = iw.getReader()) {+ final IndexSearcher searcher = new IndexSearcher(reader);+ // Query range [0, 50] is entirely below field range [100, 199]+ Query query = SortedNumericDocValuesField.newSlowRangeQuery("field", 0, 50);+ Query rewritten = searcher.rewrite(query);+ assertThat(rewritten, instanceOf(MatchNoDocsQuery.class));++ // Query range [0, 250] covers entire field range [100, 199]+ // and all docs have a value+ query = SortedNumericDocValuesField.newSlowRangeQuery("field", 0, 250);+ rewritten = searcher.rewrite(query);+ assertThat(rewritten, instanceOf(MatchAllDocsQuery.class));+ }+ }+ }+ }}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNumericFieldStats.java b/lucene/core/src/test/org/apache/lucene/search/TestNumericFieldStats.javanew file mode 100644index 00000000000..a316181265b--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestNumericFieldStats.java@@ -0,0 +1,266 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search;++import java.io.IOException;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.IntField;+import org.apache.lucene.document.LongField;+import org.apache.lucene.document.SortedNumericDocValuesField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.search.NumericFieldStats.Stats;+import org.apache.lucene.store.Directory;+import org.apache.lucene.tests.util.LuceneTestCase;++public class TestNumericFieldStats extends LuceneTestCase {++ public void testGetStatsWithLongField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (long value : new long[] {10L, 20L, 30L}) {+ final Document doc = new Document();+ doc.add(new LongField("field", value, Field.Store.NO));+ w.addDocument(doc);+ }+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(10L, stats.min());+ assertEquals(30L, stats.max());+ }+ }+ }++ public void testGetStatsWithIntField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (int value : new int[] {-5, 0, 42}) {+ final Document doc = new Document();+ doc.add(new IntField("field", value, Field.Store.NO));+ w.addDocument(doc);+ }+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(-5L, stats.min());+ assertEquals(42L, stats.max());+ }+ }+ }++ public void testGetStatsFromDocValuesSkipper() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (long value : new long[] {100L, 200L, 300L}) {+ final Document doc = new Document();+ doc.add(SortedNumericDocValuesField.indexedField("field", value));+ w.addDocument(doc);+ }+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(100L, stats.min());+ assertEquals(300L, stats.max());+ }+ }+ }++ public void testGetStatsEmptyIndex() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertNull(NumericFieldStats.getStats(reader, "field"));+ }+ }+ }++ public void testGetStatsNonexistentField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc = new Document();+ doc.add(new LongField("other_field", 42L, Field.Store.NO));+ w.addDocument(doc);+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertNull(NumericFieldStats.getStats(reader, "field"));+ }+ }+ }++ public void testGetStatsDocValuesWithoutSkipIndex() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (long value : new long[] {10L, 20L, 30L}) {+ final Document doc = new Document();+ doc.add(new SortedNumericDocValuesField("field", value));+ w.addDocument(doc);+ }+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNull(stats);+ }+ }+ }++ public void testDocCountWithLongField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (long value : new long[] {10L, 20L, 30L}) {+ final Document doc = new Document();+ doc.add(new LongField("field", value, Field.Store.NO));+ w.addDocument(doc);+ }+ w.addDocument(new Document());+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertEquals(3, NumericFieldStats.getStats(reader, "field").docCount());+ }+ }+ }++ public void testDocCountFromDocValuesSkipper() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (long value : new long[] {10L, 20L, 30L}) {+ final Document doc = new Document();+ doc.add(SortedNumericDocValuesField.indexedField("field", value));+ w.addDocument(doc);+ }+ w.addDocument(new Document());+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertEquals(3, NumericFieldStats.getStats(reader, "field").docCount());+ }+ }+ }++ public void testGetStatsWithExtremeLongValues() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc1 = new Document();+ doc1.add(new LongField("field", Long.MIN_VALUE, Field.Store.NO));+ w.addDocument(doc1);+ final Document doc2 = new Document();+ doc2.add(new LongField("field", Long.MAX_VALUE, Field.Store.NO));+ w.addDocument(doc2);+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(Long.MIN_VALUE, stats.min());+ assertEquals(Long.MAX_VALUE, stats.max());+ }+ }+ }++ public void testGetStatsWithExtremeIntValues() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc1 = new Document();+ doc1.add(new IntField("field", Integer.MIN_VALUE, Field.Store.NO));+ w.addDocument(doc1);+ final Document doc2 = new Document();+ doc2.add(new IntField("field", Integer.MAX_VALUE, Field.Store.NO));+ w.addDocument(doc2);+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(Integer.MIN_VALUE, stats.min());+ assertEquals(Integer.MAX_VALUE, stats.max());+ }+ }+ }++ public void testGetStatsMultiValuedField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc1 = new Document();+ doc1.add(SortedNumericDocValuesField.indexedField("field", 5L));+ doc1.add(SortedNumericDocValuesField.indexedField("field", 50L));+ w.addDocument(doc1);+ final Document doc2 = new Document();+ doc2.add(SortedNumericDocValuesField.indexedField("field", 25L));+ w.addDocument(doc2);+ w.commit();+ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(5L, stats.min());+ assertEquals(50L, stats.max());+ }+ }+ }++ public void testGetStatsMultipleSegments() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc1 = new Document();+ doc1.add(new LongField("field", 100L, Field.Store.NO));+ w.addDocument(doc1);+ w.commit();++ final Document doc2 = new Document();+ doc2.add(new LongField("field", 50L, Field.Store.NO));+ w.addDocument(doc2);+ w.commit();++ final Document doc3 = new Document();+ doc3.add(new LongField("field", 200L, Field.Store.NO));+ w.addDocument(doc3);+ w.commit();++ try (IndexReader reader = DirectoryReader.open(w)) {+ assertTrue(reader.leaves().size() > 1);+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(50L, stats.min());+ assertEquals(200L, stats.max());+ assertEquals(3, stats.docCount());+ }+ }+ }++ public void testGetStatsWithSegmentsWithAndWithoutField() throws IOException {+ try (Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ final Document doc = new Document();+ doc.add(new LongField("field", 100L, Field.Store.NO));+ w.addDocument(doc);+ w.commit();++ w.addDocument(new Document());+ w.commit();++ try (IndexReader reader = DirectoryReader.open(w)) {+ final Stats stats = NumericFieldStats.getStats(reader, "field");+ assertNotNull(stats);+ assertEquals(100L, stats.min());+ assertEquals(100L, stats.max());+ assertEquals(1, stats.docCount());+ }+ }+ }+}