You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by at...@apache.org on 2025/04/10 19:46:05 UTC
(lucene) branch new_index_query_include updated: Update benchmarks, introduce approx and add near duplicate detection
This is an automated email from the ASF dual-hosted git repository.
atri pushed a commit to branch new_index_query_include
in repository https://gitbox.apache.org/repos/asf/lucene.git
The following commit(s) were added to refs/heads/new_index_query_include by this push:
new e9508ac5073 Update benchmarks, introduce approx and add near duplicate detection
e9508ac5073 is described below
commit e9508ac50736adfdedd3ee514671a92511db0234
Author: Atri Sharma <at...@Atris-MacBook-Pro.local>
AuthorDate: Fri Apr 11 01:15:47 2025 +0530
Update benchmarks, introduce approx and add near duplicate detection
---
.../jmh/BinningIndexingLatencyBenchmark.java | 15 ++-
.../codecs/lucene101/Lucene101PostingsFormat.java | 29 ++++-
.../org/apache/lucene/search/DuplicateCluster.java | 28 +++++
.../apache/lucene/search/NearDuplicateFinder.java | 130 +++++++++++++++++++++
.../lucene/search/TestNearDuplicateFinder.java | 111 ++++++++++++++++++
5 files changed, 302 insertions(+), 11 deletions(-)
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/BinningIndexingLatencyBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/BinningIndexingLatencyBenchmark.java
index 4735d6b1760..a4f8340344a 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/BinningIndexingLatencyBenchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/BinningIndexingLatencyBenchmark.java
@@ -49,6 +49,7 @@ 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.AverageTime)
@@ -65,6 +66,9 @@ public class BinningIndexingLatencyBenchmark {
@Param({"true", "false"})
private boolean binningEnabled;
+ @Param({"exact", "approx", "auto"})
+ private String graphBuilder;
+
private Path tempDir;
private FieldType fieldType;
@@ -73,11 +77,14 @@ public class BinningIndexingLatencyBenchmark {
fieldType = new FieldType(TextField.TYPE_NOT_STORED);
fieldType.setTokenized(true);
fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
+
if (binningEnabled) {
fieldType.putAttribute("postingsFormat", "Lucene101");
fieldType.putAttribute("doBinning", "true");
fieldType.putAttribute("bin.count", "4");
+ fieldType.putAttribute("graph.builder", graphBuilder);
}
+
fieldType.freeze();
}
@@ -88,6 +95,7 @@ public class BinningIndexingLatencyBenchmark {
IndexWriterConfig config = new IndexWriterConfig(new SingleTokenAnalyzer());
config.setCodec(new Lucene101Codec());
config.setUseCompoundFile(false);
+
try (IndexWriter writer = new IndexWriter(dir, config)) {
for (int i = 0; i < docCount; i++) {
Document doc = new Document();
@@ -110,14 +118,11 @@ public class BinningIndexingLatencyBenchmark {
}
}
- /**
- * Minimal custom analyzer to avoid dependency on analyzer modules.
- */
private static final class SingleTokenAnalyzer extends Analyzer {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new Tokenizer() {
- private final CharTermAttribute termAttr = addAttribute(CharTermAttribute.class);
+ private final CharTermAttribute attr = addAttribute(CharTermAttribute.class);
private boolean emitted = false;
@Override
@@ -126,7 +131,7 @@ public class BinningIndexingLatencyBenchmark {
return false;
}
clearAttributes();
- termAttr.append("lucene");
+ attr.append("lucene");
emitted = true;
return true;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene101/Lucene101PostingsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene101/Lucene101PostingsFormat.java
index 15f4c78ad04..3751d3d6354 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene101/Lucene101PostingsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene101/Lucene101PostingsFormat.java
@@ -447,6 +447,7 @@ public final class Lucene101PostingsFormat extends PostingsFormat {
final FieldInfos fieldInfos = state.fieldInfos;
String binningField = null;
+ String graphBuilderType = null;
int binCount = -1;
for (FieldInfo fi : fieldInfos) {
@@ -455,6 +456,8 @@ public final class Lucene101PostingsFormat extends PostingsFormat {
String binCountAttr = fi.getAttribute("bin.count");
binCount = (binCountAttr != null) ? Integer.parseInt(binCountAttr)
: Math.max(1, Integer.highestOneBit(maxDoc >>> 4));
+ String graphBuilderAttr = fi.getAttribute("bin.builder");
+ graphBuilderType = (graphBuilderAttr != null) ? graphBuilderAttr : "auto";
break;
}
}
@@ -475,16 +478,30 @@ public final class Lucene101PostingsFormat extends PostingsFormat {
try (LeafReader reader = new FieldsLeafReader(
java.util.Collections.singletonMap(binningField, terms), maxDoc)) {
+
final int[] docToBin;
- if (maxDoc > MAX_DOC_FOR_EXACT_BINNING) {
- ApproximateDocGraphBuilder builder = new ApproximateDocGraphBuilder(
- binningField, ApproximateDocGraphBuilder.DEFAULT_MAX_EDGES);
- SparseEdgeGraph graph = builder.build(reader);
+
+ final SparseEdgeGraph graph;
+
+ if ("approx".equalsIgnoreCase(graphBuilderType)) {
+ ApproximateDocGraphBuilder builder = new ApproximateDocGraphBuilder(binningField, ApproximateDocGraphBuilder.DEFAULT_MAX_EDGES);
+ graph = builder.build(reader);
docToBin = ApproximateDocBinner.assign(graph, maxDoc, binCount);
- } else {
+ } else if ("exact".equalsIgnoreCase(graphBuilderType)) {
DocGraphBuilder builder = new DocGraphBuilder(binningField, DocGraphBuilder.DEFAULT_MAX_EDGES);
- SparseEdgeGraph graph = builder.build(reader);
+ graph = builder.build(reader);
docToBin = DocBinningGraphBuilder.computeBins(graph, maxDoc, binCount);
+ } else {
+ // default: auto fallback based on doc count
+ if (maxDoc > MAX_DOC_FOR_EXACT_BINNING) {
+ ApproximateDocGraphBuilder builder = new ApproximateDocGraphBuilder(binningField, ApproximateDocGraphBuilder.DEFAULT_MAX_EDGES);
+ graph = builder.build(reader);
+ docToBin = ApproximateDocBinner.assign(graph, maxDoc, binCount);
+ } else {
+ DocGraphBuilder builder = new DocGraphBuilder(binningField, DocGraphBuilder.DEFAULT_MAX_EDGES);
+ graph = builder.build(reader);
+ docToBin = DocBinningGraphBuilder.computeBins(graph, maxDoc, binCount);
+ }
}
BinMapWriter writer = new BinMapWriter(state.directory, state, docToBin, binCount);
diff --git a/lucene/core/src/java/org/apache/lucene/search/DuplicateCluster.java b/lucene/core/src/java/org/apache/lucene/search/DuplicateCluster.java
new file mode 100644
index 00000000000..99e24f24b8b
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/DuplicateCluster.java
@@ -0,0 +1,28 @@
+package org.apache.lucene.search;
+
+import java.util.Collections;
+import java.util.Set;
+
+/**
+ * Represents a group of near-duplicate documents.
+ */
+public final class DuplicateCluster {
+
+ private final Set<Integer> docIDs;
+
+ public DuplicateCluster(Set<Integer> docIDs) {
+ this.docIDs = Collections.unmodifiableSet(docIDs);
+ }
+
+ /**
+ * Returns the set of global document IDs in this cluster.
+ */
+ public Set<Integer> docIds() {
+ return docIDs;
+ }
+
+ @Override
+ public String toString() {
+ return "DuplicateCluster" + docIDs;
+ }
+}
\ No newline at end of file
diff --git a/lucene/core/src/java/org/apache/lucene/search/NearDuplicateFinder.java b/lucene/core/src/java/org/apache/lucene/search/NearDuplicateFinder.java
new file mode 100644
index 00000000000..d3baa521f38
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/NearDuplicateFinder.java
@@ -0,0 +1,130 @@
+package org.apache.lucene.search;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.HashSet;
+
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Terms;
+import org.apache.lucene.index.TermsEnum;
+import org.apache.lucene.index.PostingsEnum;
+import org.apache.lucene.util.BytesRef;
+
+/**
+ * Identifies clusters of near-duplicate documents based on term overlap using Jaccard similarity.
+ */
+public final class NearDuplicateFinder {
+
+ private final String field;
+ private final float threshold;
+
+ /**
+ * Create a new finder.
+ *
+ * @param field the field to analyze
+ * @param threshold similarity threshold between 0 and 1
+ */
+ public NearDuplicateFinder(String field, float threshold) {
+ this.field = field;
+ this.threshold = threshold;
+ }
+
+ /**
+ * Computes near-duplicate clusters across all segments using global docIDs.
+ *
+ * @param reader top-level reader
+ * @return list of duplicate clusters
+ */
+ public List<DuplicateCluster> findNearDuplicates(DirectoryReader reader) throws IOException {
+ final int maxDoc = reader.maxDoc();
+ final Map<Integer, Set<String>> docToTerms = new HashMap<>();
+ final Map<String, Set<Integer>> termToDocs = new HashMap<>();
+
+ int docBase = 0;
+ for (LeafReaderContext ctx : reader.leaves()) {
+ Terms terms = ctx.reader().terms(field);
+ if (terms == null) {
+ docBase += ctx.reader().maxDoc();
+ continue;
+ }
+
+ TermsEnum termsEnum = terms.iterator();
+ BytesRef term;
+ while ((term = termsEnum.next()) != null) {
+ PostingsEnum postings = termsEnum.postings(null, PostingsEnum.NONE);
+ if (postings == null) {
+ continue;
+ }
+
+ String termStr = term.utf8ToString();
+ while (postings.nextDoc() != PostingsEnum.NO_MORE_DOCS) {
+ int globalDocID = docBase + postings.docID();
+ docToTerms.computeIfAbsent(globalDocID, k -> new HashSet<>()).add(termStr);
+ termToDocs.computeIfAbsent(termStr, k -> new HashSet<>()).add(globalDocID);
+ }
+ }
+
+ docBase += ctx.reader().maxDoc();
+ }
+
+ final BitSet visited = new BitSet(maxDoc);
+ final List<DuplicateCluster> clusters = new ArrayList<>();
+
+ for (Map.Entry<Integer, Set<String>> entry : docToTerms.entrySet()) {
+ final int docID = entry.getKey();
+ if (visited.get(docID)) {
+ continue;
+ }
+
+ final Set<Integer> cluster = new HashSet<>();
+ final Set<String> termsA = entry.getValue();
+ cluster.add(docID);
+ visited.set(docID);
+
+ // Include all documents with no terms as potential duplicates of this one
+ for (Map.Entry<Integer, Set<String>> otherEntry : docToTerms.entrySet()) {
+ final int candidate = otherEntry.getKey();
+ if (candidate == docID || visited.get(candidate)) {
+ continue;
+ }
+
+ final Set<String> termsB = otherEntry.getValue();
+
+ if (termsA.isEmpty() && termsB.isEmpty()) {
+ cluster.add(candidate);
+ visited.set(candidate);
+ continue;
+ }
+
+ float score = jaccard(termsA, termsB);
+ if (score >= threshold) {
+ cluster.add(candidate);
+ visited.set(candidate);
+ }
+ }
+
+ if (cluster.size() > 1) {
+ clusters.add(new DuplicateCluster(cluster));
+ }
+ }
+
+ return clusters;
+ }
+
+ private static float jaccard(Set<String> a, Set<String> b) {
+ int intersection = 0;
+ for (String s : a) {
+ if (b.contains(s)) {
+ intersection++;
+ }
+ }
+ int union = a.size() + b.size() - intersection;
+ return union == 0 ? 0.0f : (float) intersection / union;
+ }
+}
\ No newline at end of file
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNearDuplicateFinder.java b/lucene/core/src/test/org/apache/lucene/search/TestNearDuplicateFinder.java
new file mode 100644
index 00000000000..1a69bad9c39
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/search/TestNearDuplicateFinder.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.
+ */
+package org.apache.lucene.search;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.FieldType;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexOptions;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.MMapDirectory;
+import org.apache.lucene.tests.analysis.MockAnalyzer;
+import org.apache.lucene.tests.store.MockDirectoryWrapper;
+import org.apache.lucene.tests.util.LuceneTestCase;
+
+public class TestNearDuplicateFinder extends LuceneTestCase {
+
+ private FieldType buildTextType() {
+ FieldType type = new FieldType(TextField.TYPE_STORED);
+ type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
+ type.setStoreTermVectors(true);
+ type.setStoreTermVectorPositions(true);
+ type.freeze();
+ return type;
+ }
+
+ private Directory buildIndex(String... docs) throws IOException {
+ Directory dir = new MockDirectoryWrapper(random(), new MMapDirectory(createTempDir("TestNearDuplicateFinder")));
+ IndexWriterConfig config = new IndexWriterConfig(new MockAnalyzer(random()));
+ try (IndexWriter writer = new IndexWriter(dir, config)) {
+ FieldType fieldType = buildTextType();
+ for (String content : docs) {
+ Document doc = new Document();
+ doc.add(new Field("body", content, fieldType));
+ writer.addDocument(doc);
+ }
+ }
+ return dir;
+ }
+
+ public void testExactDuplicates() throws IOException {
+ Directory dir = buildIndex("alpha beta gamma", "alpha beta gamma", "delta epsilon");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finder = new NearDuplicateFinder("body", 0.95f);
+ List<DuplicateCluster> clusters = finder.findNearDuplicates(reader);
+ assertEquals(1, clusters.size());
+ Set<Integer> dup = clusters.get(0).docIds();
+ assertTrue(dup.contains(0));
+ assertTrue(dup.contains(1));
+ }
+ }
+
+ public void testPartialOverlap() throws IOException {
+ Directory dir = buildIndex("quick brown fox", "quick brown dog", "lazy dog sleeps");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finder = new NearDuplicateFinder("body", 0.5f);
+ List<DuplicateCluster> clusters = finder.findNearDuplicates(reader);
+ assertEquals(1, clusters.size());
+ }
+ }
+
+ public void testThresholdSensitivity() throws IOException {
+ Directory dir = buildIndex("a b c d e", "a b c", "x y z");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finderHigh = new NearDuplicateFinder("body", 0.9f);
+ NearDuplicateFinder finderLow = new NearDuplicateFinder("body", 0.3f);
+ List<DuplicateCluster> high = finderHigh.findNearDuplicates(reader);
+ List<DuplicateCluster> low = finderLow.findNearDuplicates(reader);
+ assertEquals(0, high.size());
+ assertTrue(low.size() >= 1);
+ }
+ }
+
+ public void testEmptyDocs() throws IOException {
+ Directory dir = buildIndex("", "", "filled text content");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finder = new NearDuplicateFinder("body", 0.9f);
+ List<DuplicateCluster> clusters = finder.findNearDuplicates(reader);
+ assertEquals(1, clusters.size());
+ }
+ }
+
+ public void testMultipleClusters() throws IOException {
+ Directory dir = buildIndex("apple orange", "apple orange", "car bus", "car bus", "train");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finder = new NearDuplicateFinder("body", 0.95f);
+ List<DuplicateCluster> clusters = finder.findNearDuplicates(reader);
+ assertEquals(2, clusters.size());
+ }
+ }
+
+ public void testNoDuplicates() throws IOException {
+ Directory dir = buildIndex("one", "two", "three", "four");
+ try (DirectoryReader reader = DirectoryReader.open(dir)) {
+ NearDuplicateFinder finder = new NearDuplicateFinder("body", 0.95f);
+ List<DuplicateCluster> clusters = finder.findNearDuplicates(reader);
+ assertEquals(0, clusters.size());
+ }
+ }
+}
\ No newline at end of file