Skip to content

Apache Lucene open-source search software

LUCENE-8007: Make scoring statistics mandatory

Robert Muirca5f9b345765
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 9237eb5beda..84e9da3b8d5 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -5,6 +5,14 @@ http://s.apache.org/luceneversions
======================= Lucene 8.0.0 =======================
+API Changes
+
+* LUCENE-8007: Index statistics Terms.getSumDocFreq(), Terms.getDocCount() are
+ now required to be stored by codecs. Additionally, TermsEnum.totalTermFreq()
+ and Terms.getSumTotalTermFreq() are now required: if frequencies are not
+ stored they are equal to TermsEnum.docFreq() and Terms.getSumDocFreq(),
+ respectively, because all freq() values equal 1. (Adrien Grand, Robert Muir)
+
Changes in Runtime Behavior
* LUCENE-7837: Indices that were created before the previous major version
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
index b8d23bdb3d6..17024d8a9f1 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
@@ -139,8 +139,9 @@ public class BlockTermsReader extends FieldsProducer {
assert numTerms >= 0;
final long termsStartPointer = in.readVLong();
final FieldInfo fieldInfo = state.fieldInfos.fieldInfo(field);
- final long sumTotalTermFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? -1 : in.readVLong();
- final long sumDocFreq = in.readVLong();
+ final long sumTotalTermFreq = in.readVLong();
+ // when frequencies are omitted, sumDocFreq=totalTermFreq and we only write one value
+ final long sumDocFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? sumTotalTermFreq : in.readVLong();
final int docCount = in.readVInt();
final int longsSize = in.readVInt();
if (docCount < 0 || docCount > state.segmentInfo.maxDoc()) { // #docs with field must be <= #docs
@@ -149,7 +150,7 @@ public class BlockTermsReader extends FieldsProducer {
if (sumDocFreq < docCount) { // #postings must be >= #docs with field
throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount, in);
}
- if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
+ if (sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq, in);
}
FieldReader previous = fields.put(fieldInfo.name, new FieldReader(fieldInfo, numTerms, termsStartPointer, sumTotalTermFreq, sumDocFreq, docCount, longsSize));
@@ -810,7 +811,9 @@ public class BlockTermsReader extends FieldsProducer {
// docFreq, totalTermFreq
state.docFreq = freqReader.readVInt();
//System.out.println(" dF=" + state.docFreq);
- if (fieldInfo.getIndexOptions() != IndexOptions.DOCS) {
+ if (fieldInfo.getIndexOptions() == IndexOptions.DOCS) {
+ state.totalTermFreq = state.docFreq; // all postings have tf=1
+ } else {
state.totalTermFreq = state.docFreq + freqReader.readVLong();
//System.out.println(" totTF=" + state.totalTermFreq);
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java
index afdaf5aad17..e07cee099de 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsReader.java
@@ -126,8 +126,9 @@ public final class OrdsBlockTreeTermsReader extends FieldsProducer {
final FieldInfo fieldInfo = state.fieldInfos.fieldInfo(field);
assert fieldInfo != null: "field=" + field;
assert numTerms <= Integer.MAX_VALUE;
- final long sumTotalTermFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? -1 : in.readVLong();
- final long sumDocFreq = in.readVLong();
+ final long sumTotalTermFreq = in.readVLong();
+ // when frequencies are omitted, sumDocFreq=totalTermFreq and we only write one value
+ final long sumDocFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? sumTotalTermFreq : in.readVLong();
final int docCount = in.readVInt();
final int longsSize = in.readVInt();
// System.out.println(" longsSize=" + longsSize);
@@ -140,7 +141,7 @@ public final class OrdsBlockTreeTermsReader extends FieldsProducer {
if (sumDocFreq < docCount) { // #postings must be >= #docs with field
throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount, in);
}
- if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
+ if (sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq, in);
}
final long indexStartFP = indexIn.readVLong();
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java
index 9312ff9ed3a..a34f0fda1d0 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsIntersectTermsEnumFrame.java
@@ -292,7 +292,9 @@ final class OrdsIntersectTermsEnumFrame {
// stats
termState.docFreq = statsReader.readVInt();
//if (DEBUG) System.out.println(" dF=" + state.docFreq);
- if (ite.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS) {
+ if (ite.fr.fieldInfo.getIndexOptions() == IndexOptions.DOCS) {
+ termState.totalTermFreq = termState.docFreq; // all tf values are 1
+ } else {
termState.totalTermFreq = termState.docFreq + statsReader.readVLong();
//if (DEBUG) System.out.println(" totTF=" + state.totalTermFreq);
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
index 76a30c4c11e..ee3782f29cd 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
@@ -499,7 +499,9 @@ final class OrdsSegmentTermsEnumFrame {
// stats
state.docFreq = statsReader.readVInt();
//if (DEBUG) System.out.println(" dF=" + state.docFreq);
- if (ste.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS) {
+ if (ste.fr.fieldInfo.getIndexOptions() == IndexOptions.DOCS) {
+ state.totalTermFreq = state.docFreq; // all tf values are 1
+ } else {
state.totalTermFreq = state.docFreq + statsReader.readVLong();
//if (DEBUG) System.out.println(" totTF=" + state.totalTermFreq);
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
index 97bbea3ddef..5ba4c5ff0a3 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
@@ -19,7 +19,6 @@ package org.apache.lucene.codecs.memory;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
@@ -111,8 +110,9 @@ public class FSTOrdTermsReader extends FieldsProducer {
FieldInfo fieldInfo = fieldInfos.fieldInfo(blockIn.readVInt());
boolean hasFreq = fieldInfo.getIndexOptions() != IndexOptions.DOCS;
long numTerms = blockIn.readVLong();
- long sumTotalTermFreq = hasFreq ? blockIn.readVLong() : -1;
- long sumDocFreq = blockIn.readVLong();
+ long sumTotalTermFreq = blockIn.readVLong();
+ // if freqs are omitted, sumDocFreq=sumTotalTermFreq and we only write one value
+ long sumDocFreq = hasFreq ? blockIn.readVLong() : sumTotalTermFreq;
int docCount = blockIn.readVInt();
int longsSize = blockIn.readVInt();
FST<Long> index = new FST<>(indexIn, PositiveIntOutputs.getSingleton());
@@ -146,7 +146,7 @@ public class FSTOrdTermsReader extends FieldsProducer {
throw new CorruptIndexException("invalid sumDocFreq: " + field.sumDocFreq + " docCount: " + field.docCount + " (blockIn=" + blockIn + ")", indexIn);
}
// #positions must be >= #postings
- if (field.sumTotalTermFreq != -1 && field.sumTotalTermFreq < field.sumDocFreq) {
+ if (field.sumTotalTermFreq < field.sumDocFreq) {
throw new CorruptIndexException("invalid sumTotalTermFreq: " + field.sumTotalTermFreq + " sumDocFreq: " + field.sumDocFreq + " (blockIn=" + blockIn + ")", indexIn);
}
if (previous != null) {
@@ -343,9 +343,6 @@ public class FSTOrdTermsReader extends FieldsProducer {
this.totalTermFreq = new long[INTERVAL];
this.statsBlockOrd = -1;
this.metaBlockOrd = -1;
- if (!hasFreqs()) {
- Arrays.fill(totalTermFreq, -1);
- }
}
/** Decodes stats data into term state */
@@ -388,6 +385,7 @@ public class FSTOrdTermsReader extends FieldsProducer {
}
} else {
docFreq[i] = code;
+ totalTermFreq[i] = code;
}
}
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
index b120656688c..8dda05c3805 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
@@ -94,8 +94,9 @@ public class FSTTermsReader extends FieldsProducer {
int fieldNumber = in.readVInt();
FieldInfo fieldInfo = fieldInfos.fieldInfo(fieldNumber);
long numTerms = in.readVLong();
- long sumTotalTermFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? -1 : in.readVLong();
- long sumDocFreq = in.readVLong();
+ long sumTotalTermFreq = in.readVLong();
+ // if frequencies are omitted, sumTotalTermFreq=sumDocFreq and we only write one value
+ long sumDocFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? sumTotalTermFreq : in.readVLong();
int docCount = in.readVInt();
int longsSize = in.readVInt();
TermsReader current = new TermsReader(fieldInfo, in, numTerms, sumTotalTermFreq, sumDocFreq, docCount, longsSize);
@@ -126,7 +127,7 @@ public class FSTTermsReader extends FieldsProducer {
throw new CorruptIndexException("invalid sumDocFreq: " + field.sumDocFreq + " docCount: " + field.docCount, in);
}
// #positions must be >= #postings
- if (field.sumTotalTermFreq != -1 && field.sumTotalTermFreq < field.sumDocFreq) {
+ if (field.sumTotalTermFreq < field.sumDocFreq) {
throw new CorruptIndexException("invalid sumTotalTermFreq: " + field.sumTotalTermFreq + " sumDocFreq: " + field.sumDocFreq, in);
}
if (previous != null) {
@@ -288,7 +289,7 @@ public class FSTTermsReader extends FieldsProducer {
@Override
public long totalTermFreq() throws IOException {
- return state.totalTermFreq;
+ return state.totalTermFreq == -1 ? state.docFreq : state.totalTermFreq;
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
index dff445eb114..21983c6429b 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
@@ -733,10 +733,10 @@ public final class MemoryPostingsFormat extends PostingsFormat {
if (!didDecode) {
buffer.reset(current.output.bytes, current.output.offset, current.output.length);
docFreq = buffer.readVInt();
- if (field.getIndexOptions() != IndexOptions.DOCS) {
- totalTermFreq = docFreq + buffer.readVLong();
+ if (field.getIndexOptions() == IndexOptions.DOCS) {
+ totalTermFreq = docFreq;
} else {
- totalTermFreq = -1;
+ totalTermFreq = docFreq + buffer.readVLong();
}
postingsSpare.bytes = current.output.bytes;
postingsSpare.offset = buffer.getPosition();
@@ -873,12 +873,15 @@ public final class MemoryPostingsFormat extends PostingsFormat {
field = fieldInfos.fieldInfo(fieldNumber);
if (field == null) {
throw new CorruptIndexException("invalid field number: " + fieldNumber, in);
- } else if (field.getIndexOptions() != IndexOptions.DOCS) {
+ } else {
sumTotalTermFreq = in.readVLong();
+ }
+ // if frequencies are omitted, sumDocFreq = sumTotalTermFreq and we only write one value.
+ if (field.getIndexOptions() == IndexOptions.DOCS) {
+ sumDocFreq = sumTotalTermFreq;
} else {
- sumTotalTermFreq = -1;
+ sumDocFreq = in.readVLong();
}
- sumDocFreq = in.readVLong();
docCount = in.readVInt();
fst = new FST<>(in, outputs);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
index faab7885f6c..f5504b3151e 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
@@ -202,7 +202,7 @@ class SimpleTextFieldsReader extends FieldsProducer {
@Override
public long totalTermFreq() {
- return indexOptions == IndexOptions.DOCS ? -1 : totalTermFreq;
+ return indexOptions == IndexOptions.DOCS ? docFreq : totalTermFreq;
}
@Override
@@ -568,12 +568,13 @@ class SimpleTextFieldsReader extends FieldsProducer {
} else if (StringHelper.startsWith(scratch.get(), DOC)) {
docFreq++;
sumDocFreq++;
+ totalTermFreq++;
scratchUTF16.copyUTF8Bytes(scratch.bytes(), DOC.length, scratch.length()-DOC.length);
int docID = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
visitedDocs.set(docID);
} else if (StringHelper.startsWith(scratch.get(), FREQ)) {
scratchUTF16.copyUTF8Bytes(scratch.bytes(), FREQ.length, scratch.length()-FREQ.length);
- totalTermFreq += ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
+ totalTermFreq += ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length()) - 1;
} else if (StringHelper.startsWith(scratch.get(), TERM)) {
if (lastDocsStart != -1) {
b.add(Util.toIntsRef(lastTerm.get(), scratchIntsRef), outputs.newPair(lastDocsStart,
@@ -637,7 +638,7 @@ class SimpleTextFieldsReader extends FieldsProducer {
@Override
public long getSumTotalTermFreq() {
- return fieldInfo.getIndexOptions() == IndexOptions.DOCS ? -1 : sumTotalTermFreq;
+ return sumTotalTermFreq;
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
index 873aaeffe5b..25f2a4d0c08 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
@@ -288,7 +288,13 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
@Override
public long getSumTotalTermFreq() throws IOException {
- return -1;
+ // TODO: make it constant-time
+ long ttf = 0;
+ TermsEnum iterator = iterator();
+ for (BytesRef b = iterator.next(); b != null; b = iterator.next()) {
+ ttf += iterator.totalTermFreq();
+ }
+ return ttf;
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsReader.java
index 0e14bf74182..0ef21292c04 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsReader.java
@@ -180,8 +180,9 @@ public final class BlockTreeTermsReader extends FieldsProducer {
if (fieldInfo == null) {
throw new CorruptIndexException("invalid field number: " + field, termsIn);
}
- final long sumTotalTermFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? -1 : termsIn.readVLong();
- final long sumDocFreq = termsIn.readVLong();
+ final long sumTotalTermFreq = termsIn.readVLong();
+ // when frequencies are omitted, sumDocFreq=sumTotalTermFreq and only one value is written.
+ final long sumDocFreq = fieldInfo.getIndexOptions() == IndexOptions.DOCS ? sumTotalTermFreq : termsIn.readVLong();
final int docCount = termsIn.readVInt();
final int longsSize = termsIn.readVInt();
if (longsSize < 0) {
@@ -195,7 +196,7 @@ public final class BlockTreeTermsReader extends FieldsProducer {
if (sumDocFreq < docCount) { // #postings must be >= #docs with field
throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount, termsIn);
}
- if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
+ if (sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq, termsIn);
}
final long indexStartFP = indexIn.readVLong();
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/IntersectTermsEnumFrame.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/IntersectTermsEnumFrame.java
index 578e1453007..236e77a7f67 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/IntersectTermsEnumFrame.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/IntersectTermsEnumFrame.java
@@ -288,7 +288,9 @@ final class IntersectTermsEnumFrame {
// stats
termState.docFreq = statsReader.readVInt();
- if (ite.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS) {
+ if (ite.fr.fieldInfo.getIndexOptions() == IndexOptions.DOCS) {
+ termState.totalTermFreq = termState.docFreq; // all postings have freq=1
+ } else {
termState.totalTermFreq = termState.docFreq + statsReader.readVLong();
}
// metadata
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
index 0860b30cbf5..a32bdac427c 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
@@ -417,7 +417,9 @@ final class SegmentTermsEnumFrame {
// stats
state.docFreq = statsReader.readVInt();
//if (DEBUG) System.out.println(" dF=" + state.docFreq);
- if (ste.fr.fieldInfo.getIndexOptions() != IndexOptions.DOCS) {
+ if (ste.fr.fieldInfo.getIndexOptions() == IndexOptions.DOCS) {
+ state.totalTermFreq = state.docFreq; // all postings have freq=1
+ } else {
state.totalTermFreq = state.docFreq + statsReader.readVLong();
//if (DEBUG) System.out.println(" totTF=" + state.totalTermFreq);
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java
index 2e8ed630307..f5318baffe9 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java
@@ -745,6 +745,7 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implem
private static class TVTerms extends Terms {
private final int numTerms, flags;
+ private final long totalTermFreq;
private final int[] prefixLengths, suffixLengths, termFreqs, positionIndex, positions, startOffsets, lengths, payloadIndex;
private final BytesRef termBytes, payloadBytes;
@@ -764,6 +765,11 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implem
this.payloadIndex = payloadIndex;
this.payloadBytes = payloadBytes;
this.termBytes = termBytes;
+ long ttf = 0;
+ for (int tf : termFreqs) {
+ ttf += tf;
+ }
+ this.totalTermFreq = ttf;
}
@Override
@@ -782,7 +788,7 @@ public final class CompressingTermVectorsReader extends TermVectorsReader implem
@Override
public long getSumTotalTermFreq() throws IOException {
- return -1L;
+ return totalTermFreq;
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/index/BaseCompositeReader.java b/lucene/core/src/java/org/apache/lucene/index/BaseCompositeReader.java
index 3256107d426..8a19fe14120 100644
--- a/lucene/core/src/java/org/apache/lucene/index/BaseCompositeReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/BaseCompositeReader.java
@@ -123,7 +123,10 @@ public abstract class BaseCompositeReader<R extends IndexReader> extends Composi
ensureOpen();
int total = 0; // sum freqs in subreaders
for (int i = 0; i < subReaders.length; i++) {
- total += subReaders[i].docFreq(term);
+ int sub = subReaders[i].docFreq(term);
+ assert sub >= 0;
+ assert sub <= subReaders[i].getDocCount(term.field());
+ total += sub;
}
return total;
}
@@ -134,9 +137,8 @@ public abstract class BaseCompositeReader<R extends IndexReader> extends Composi
long total = 0; // sum freqs in subreaders
for (int i = 0; i < subReaders.length; i++) {
long sub = subReaders[i].totalTermFreq(term);
- if (sub == -1) {
- return -1;
- }
+ assert sub >= 0;
+ assert sub <= subReaders[i].getSumTotalTermFreq(term.field());
total += sub;
}
return total;
@@ -148,9 +150,8 @@ public abstract class BaseCompositeReader<R extends IndexReader> extends Composi
long total = 0; // sum doc freqs in subreaders
for (R reader : subReaders) {
long sub = reader.getSumDocFreq(field);
- if (sub == -1) {
- return -1; // if any of the subs doesn't support it, return -1
- }
+ assert sub >= 0;
+ assert sub <= reader.getSumTotalTermFreq(field);
total += sub;
}
return total;
@@ -162,9 +163,8 @@ public abstract class BaseCompositeReader<R extends IndexReader> extends Composi
int total = 0; // sum doc counts in subreaders
for (R reader : subReaders) {
int sub = reader.getDocCount(field);
- if (sub == -1) {
- return -1; // if any of the subs doesn't support it, return -1
- }
+ assert sub >= 0;
+ assert sub <= reader.maxDoc();
total += sub;
}
return total;
@@ -176,9 +176,8 @@ public abstract class BaseCompositeReader<R extends IndexReader> extends Composi
long total = 0; // sum doc total term freqs in subreaders
for (R reader : subReaders) {
long sub = reader.getSumTotalTermFreq(field);
- if (sub == -1) {
- return -1; // if any of the subs doesn't support it, return -1
- }
+ assert sub >= 0;
+ assert sub >= reader.getSumDocFreq(field);
total += sub;
}
return total;
diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
index 552e83d42d3..028da241fb3 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
@@ -1253,6 +1253,10 @@ public final class CheckIndex implements Closeable {
continue;
}
+ if (terms.getDocCount() > maxDoc) {
+ throw new RuntimeException("docCount > maxDoc for field: " + field + ", docCount=" + terms.getDocCount() + ", maxDoc=" + maxDoc);
+ }
+
final boolean hasFreqs = terms.hasFreqs();
final boolean hasPositions = terms.hasPositions();
final boolean hasPayloads = terms.hasPayloads();
@@ -1295,12 +1299,6 @@ public final class CheckIndex implements Closeable {
throw new RuntimeException("field \"" + field + "\" should have hasFreqs=" + expectedHasFreqs + " but got " + hasFreqs);
}
- if (hasFreqs == false) {
- if (terms.getSumTotalTermFreq() != -1) {
- throw new RuntimeException("field \"" + field + "\" hasFreqs is false, but Terms.getSumTotalTermFreq()=" + terms.getSumTotalTermFreq() + " (should be -1)");
- }
- }
-
if (!isVectors) {
final boolean expectedHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
if (hasPositions != expectedHasPositions) {
@@ -1375,8 +1373,8 @@ public final class CheckIndex implements Closeable {
postings = termsEnum.postings(postings, PostingsEnum.ALL);
if (hasFreqs == false) {
- if (termsEnum.totalTermFreq() != -1) {
- throw new RuntimeException("field \"" + field + "\" hasFreqs is false, but TermsEnum.totalTermFreq()=" + termsEnum.totalTermFreq() + " (should be -1)");
+ if (termsEnum.totalTermFreq() != termsEnum.docFreq()) {
+ throw new RuntimeException("field \"" + field + "\" hasFreqs is false, but TermsEnum.totalTermFreq()=" + termsEnum.totalTermFreq() + " (should be " + termsEnum.docFreq() + ")");
}
}
@@ -1406,14 +1404,11 @@ public final class CheckIndex implements Closeable {
break;
}
visitedDocs.set(doc);
- int freq = -1;
- if (hasFreqs) {
- freq = postings.freq();
- if (freq <= 0) {
- throw new RuntimeException("term " + term + ": doc " + doc + ": freq " + freq + " is out of bounds");
- }
- totalTermFreq += freq;
- } else {
+ int freq = postings.freq();
+ if (freq <= 0) {
+ throw new RuntimeException("term " + term + ": doc " + doc + ": freq " + freq + " is out of bounds");
+ }
+ if (hasFreqs == false) {
// When a field didn't index freq, it must
// consistently "lie" and pretend that freq was
// 1:
@@ -1421,6 +1416,8 @@ public final class CheckIndex implements Closeable {
throw new RuntimeException("term " + term + ": doc " + doc + ": freq " + freq + " != 1 when Terms.hasFreqs() is false");
}
}
+ totalTermFreq += freq;
+
if (liveDocs == null || liveDocs.get(doc)) {
hasNonDeletedDocs = true;
status.totFreq++;
@@ -1490,19 +1487,25 @@ public final class CheckIndex implements Closeable {
}
final long totalTermFreq2 = termsEnum.totalTermFreq();
- final boolean hasTotalTermFreq = hasFreqs && totalTermFreq2 != -1;
if (docCount != docFreq) {
throw new RuntimeException("term " + term + " docFreq=" + docFreq + " != tot docs w/o deletions " + docCount);
}
- if (hasTotalTermFreq) {
- if (totalTermFreq2 <= 0) {
- throw new RuntimeException("totalTermFreq: " + totalTermFreq2 + " is out of bounds");
- }
- sumTotalTermFreq += totalTermFreq;
- if (totalTermFreq != totalTermFreq2) {
- throw new RuntimeException("term " + term + " totalTermFreq=" + totalTermFreq2 + " != recomputed totalTermFreq=" + totalTermFreq);
- }
+ if (docFreq > terms.getDocCount()) {
+ throw new RuntimeException("term " + term + " docFreq=" + docFreq + " > docCount=" + terms.getDocCount());
+ }
+ if (totalTermFreq2 <= 0) {
+ throw new RuntimeException("totalTermFreq: " + totalTermFreq2 + " is out of bounds");
+ }
+ sumTotalTermFreq += totalTermFreq;
+ if (totalTermFreq != totalTermFreq2) {
+ throw new RuntimeException("term " + term + " totalTermFreq=" + totalTermFreq2 + " != recomputed totalTermFreq=" + totalTermFreq);
+ }
+ if (totalTermFreq2 < docFreq) {
+ throw new RuntimeException("totalTermFreq: " + totalTermFreq2 + " is out of bounds, docFreq=" + docFreq);
+ }
+ if (hasFreqs == false && totalTermFreq != docFreq) {
+ throw new RuntimeException("term " + term + " totalTermFreq=" + totalTermFreq + " != docFreq=" + docFreq);
}
// Test skipping
@@ -1626,22 +1629,22 @@ public final class CheckIndex implements Closeable {
}
status.blockTreeStats.put(field, stats);
- if (sumTotalTermFreq != 0) {
- final long v = fields.terms(field).getSumTotalTermFreq();
- if (v != -1 && sumTotalTermFreq != v) {
- throw new RuntimeException("sumTotalTermFreq for field " + field + "=" + v + " != recomputed sumTotalTermFreq=" + sumTotalTermFreq);
- }
+ final long actualSumDocFreq = fields.terms(field).getSumDocFreq();
+ if (sumDocFreq != actualSumDocFreq) {
+ throw new RuntimeException("sumDocFreq for field " + field + "=" + actualSumDocFreq + " != recomputed sumDocFreq=" + sumDocFreq);
}
+
+ final long actualSumTotalTermFreq = fields.terms(field).getSumTotalTermFreq();
+ if (sumTotalTermFreq != actualSumTotalTermFreq) {
+ throw new RuntimeException("sumTotalTermFreq for field " + field + "=" + actualSumTotalTermFreq + " != recomputed sumTotalTermFreq=" + sumTotalTermFreq);
+ }
- if (sumDocFreq != 0) {
- final long v = fields.terms(field).getSumDocFreq();
- if (v != -1 && sumDocFreq != v) {
- throw new RuntimeException("sumDocFreq for field " + field + "=" + v + " != recomputed sumDocFreq=" + sumDocFreq);
- }
+ if (hasFreqs == false && sumTotalTermFreq != sumDocFreq) {
+ throw new RuntimeException("sumTotalTermFreq for field " + field + " should be " + sumDocFreq + ", got sumTotalTermFreq=" + sumTotalTermFreq);
}
final int v = fieldTerms.getDocCount();
- if (v != -1 && visitedDocs.cardinality() != v) {
+ if (visitedDocs.cardinality() != v) {
throw new RuntimeException("docCount for field " + field + "=" + v + " != recomputed docCount=" + visitedDocs.cardinality());
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexReader.java b/lucene/core/src/java/org/apache/lucene/index/IndexReader.java
index 3efd5874e62..8b9a83b27d3 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexReader.java
@@ -450,25 +450,25 @@ public abstract class IndexReader implements Closeable {
/**
* Returns the total number of occurrences of {@code term} across all
- * documents (the sum of the freq() for each doc that has this term). This
- * will be -1 if the codec doesn't support this measure. Note that, like other
- * term measures, this measure does not take deleted documents into account.
+ * documents (the sum of the freq() for each doc that has this term).
+ * Note that, like other term measures, this measure does not take
+ * deleted documents into account.
*/
public abstract long totalTermFreq(Term term) throws IOException;
/**
- * Returns the sum of {@link TermsEnum#docFreq()} for all terms in this field,
- * or -1 if this measure isn't stored by the codec. Note that, just like other
- * term measures, this measure does not take deleted documents into account.
+ * Returns the sum of {@link TermsEnum#docFreq()} for all terms in this field.
+ * Note that, just like other term measures, this measure does not take deleted
+ * documents into account.
*
* @see Terms#getSumDocFreq()
*/
public abstract long getSumDocFreq(String field) throws IOException;
/**
- * Returns the number of documents that have at least one term for this field,
- * or -1 if this measure isn't stored by the codec. Note that, just like other
- * term measures, this measure does not take deleted documents into account.
+ * Returns the number of documents that have at least one term for this field.
+ * Note that, just like other term measures, this measure does not take deleted
+ * documents into account.
*
* @see Terms#getDocCount()
*/
@@ -476,9 +476,8 @@ public abstract class IndexReader implements Closeable {
/**
* Returns the sum of {@link TermsEnum#totalTermFreq} for all terms in this
- * field, or -1 if this measure isn't stored by the codec (or if this fields
- * omits term freq and positions). Note that, just like other term measures,
- * this measure does not take deleted documents into account.
+ * field. Note that, just like other term measures, this measure does not take
+ * deleted documents into account.
*
* @see Terms#getSumTotalTermFreq()
*/
diff --git a/lucene/core/src/java/org/apache/lucene/index/MultiTerms.java b/lucene/core/src/java/org/apache/lucene/index/MultiTerms.java
index 79e11c45eee..203e366d28e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/MultiTerms.java
+++ b/lucene/core/src/java/org/apache/lucene/index/MultiTerms.java
@@ -149,9 +149,7 @@ public final class MultiTerms extends Terms {
long sum = 0;
for(Terms terms : subs) {
final long v = terms.getSumTotalTermFreq();
- if (v == -1) {
- return -1;
- }
+ assert v != -1;
sum += v;
}
return sum;
@@ -162,9 +160,7 @@ public final class MultiTerms extends Terms {
long sum = 0;
for(Terms terms : subs) {
final long v = terms.getSumDocFreq();
- if (v == -1) {
- return -1;
- }
+ assert v != -1;
sum += v;
}
return sum;
@@ -175,9 +171,7 @@ public final class MultiTerms extends Terms {
int sum = 0;
for(Terms terms : subs) {
final int v = terms.getDocCount();
- if (v == -1) {
- return -1;
- }
+ assert v != -1;
sum += v;
}
return sum;
diff --git a/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
index 51f495817fd..7db838b91a4 100644
--- a/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
@@ -326,9 +326,7 @@ public final class MultiTermsEnum extends TermsEnum {
long sum = 0;
for(int i=0;i<numTop;i++) {
final long v = top[i].terms.totalTermFreq();
- if (v == -1) {
- return v;
- }
+ assert v != -1;
sum += v;
}
return sum;
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
index 58247be13d1..ccee7a38e62 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
@@ -101,7 +101,7 @@ class SortedDocValuesTermsEnum extends TermsEnum {
@Override
public long totalTermFreq() {
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
index d2b1b96dac8..eba95c92795 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
@@ -101,7 +101,7 @@ class SortedSetDocValuesTermsEnum extends TermsEnum {
@Override
public long totalTermFreq() {
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/index/TermContext.java b/lucene/core/src/java/org/apache/lucene/index/TermContext.java
index ed25564e461..3ba8dd9d848 100644
--- a/lucene/core/src/java/org/apache/lucene/index/TermContext.java
+++ b/lucene/core/src/java/org/apache/lucene/index/TermContext.java
@@ -141,11 +141,11 @@ public final class TermContext {
/** Expert: Accumulate term statistics. */
public void accumulateStatistics(final int docFreq, final long totalTermFreq) {
+ assert docFreq >= 0;
+ assert totalTermFreq >= 0;
+ assert docFreq <= totalTermFreq;
this.docFreq += docFreq;
- if (this.totalTermFreq >= 0 && totalTermFreq >= 0)
- this.totalTermFreq += totalTermFreq;
- else
- this.totalTermFreq = -1;
+ this.totalTermFreq += totalTermFreq;
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/index/Terms.java b/lucene/core/src/java/org/apache/lucene/index/Terms.java
index 7197e25e549..dca8a276bbf 100644
--- a/lucene/core/src/java/org/apache/lucene/index/Terms.java
+++ b/lucene/core/src/java/org/apache/lucene/index/Terms.java
@@ -99,25 +99,21 @@ public abstract class Terms {
* other term measures, this measure does not take deleted
* documents into account. */
public abstract long size() throws IOException;
-
+
/** Returns the sum of {@link TermsEnum#totalTermFreq} for
- * all terms in this field, or -1 if this measure isn't
- * stored by the codec (or if this fields omits term freq
- * and positions). Note that, just like other term
+ * all terms in this field. Note that, just like other term
* measures, this measure does not take deleted documents
* into account. */
public abstract long getSumTotalTermFreq() throws IOException;
/** Returns the sum of {@link TermsEnum#docFreq()} for
- * all terms in this field, or -1 if this measure isn't
- * stored by the codec. Note that, just like other term
+ * all terms in this field. Note that, just like other term
* measures, this measure does not take deleted documents
* into account. */
public abstract long getSumDocFreq() throws IOException;
/** Returns the number of documents that have at least one
- * term for this field, or -1 if this measure isn't
- * stored by the codec. Note that, just like other term
+ * term for this field. Note that, just like other term
* measures, this measure does not take deleted documents
* into account. */
public abstract int getDocCount() throws IOException;
diff --git a/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java
index c4b1017b079..4b5755a330d 100644
--- a/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/TermsEnum.java
@@ -131,8 +131,7 @@ public abstract class TermsEnum implements BytesRefIterator {
/** Returns the total number of occurrences of this term
* across all documents (the sum of the freq() for each
- * doc that has this term). This will be -1 if the
- * codec doesn't support this measure. Note that, like
+ * doc that has this term). Note that, like
* other term measures, this measure does not take
* deleted documents into account. */
public abstract long totalTermFreq() throws IOException;
diff --git a/lucene/core/src/java/org/apache/lucene/index/package-info.java b/lucene/core/src/java/org/apache/lucene/index/package-info.java
index f5a86d1cb37..d7d337cc78a 100644
--- a/lucene/core/src/java/org/apache/lucene/index/package-info.java
+++ b/lucene/core/src/java/org/apache/lucene/index/package-info.java
@@ -148,12 +148,8 @@
* deleted documents, when segments are merged the statistic is updated as
* those deleted documents are merged away.
* <li>{@link org.apache.lucene.index.TermsEnum#totalTermFreq}: Returns the number
- * of occurrences of this term across all documents. Note that this statistic
- * is unavailable (returns <code>-1</code>) if term frequencies were omitted
- * from the index
- * ({@link org.apache.lucene.index.IndexOptions#DOCS DOCS})
- * for the field. Like docFreq(), it will also count occurrences that appear in
- * deleted documents.
+ * of occurrences of this term across all documents. Like docFreq(), it will
+ * also count occurrences that appear in deleted documents.
* </ul>
* <a name="fieldstats"></a>
* <h3>
@@ -180,10 +176,7 @@
* of tokens for the field. This can be thought of as the sum of
* {@link org.apache.lucene.index.TermsEnum#totalTermFreq} across all terms in the
* field, and like totalTermFreq() it will also count occurrences that appear in
- * deleted documents, and will be unavailable (returns <code>-1</code>) if term
- * frequencies were omitted from the index
- * ({@link org.apache.lucene.index.IndexOptions#DOCS DOCS})
- * for the field.
+ * deleted documents.
* </ul>
* <a name="segmentstats"></a>
* <h3>
diff --git a/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
index 3a0cdc5a1ef..219d4535827 100644
--- a/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
@@ -277,11 +277,7 @@ public final class BlendedTermQuery extends Query {
long ttf = 0;
for (TermContext ctx : contexts) {
df = Math.max(df, ctx.docFreq());
- if (ctx.totalTermFreq() == -1L) {
- ttf = -1L;
- } else if (ttf != -1L) {
- ttf += ctx.totalTermFreq();
- }
+ ttf += ctx.totalTermFreq();
}
for (int i = 0; i < contexts.length; ++i) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/CollectionStatistics.java b/lucene/core/src/java/org/apache/lucene/search/CollectionStatistics.java
index a6a1e190c25..2dac05985d6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/CollectionStatistics.java
+++ b/lucene/core/src/java/org/apache/lucene/search/CollectionStatistics.java
@@ -23,7 +23,27 @@ import org.apache.lucene.index.Terms; // javadocs
/**
- * Contains statistics for a collection (field)
+ * Contains statistics for a collection (field).
+ * <p>
+ * This class holds statistics across all documents for scoring purposes:
+ * <ul>
+ * <li> {@link #maxDoc()}: number of documents.
+ * <li> {@link #docCount()}: number of documents that contain this field.
+ * <li> {@link #sumDocFreq()}: number of postings-list entries.
+ * <li> {@link #sumTotalTermFreq()}: number of tokens.
+ * </ul>
+ * <p>
+ * The following conditions are always true:
+ * <ul>
+ * <li> All statistics are positive integers: never zero or negative.
+ * <li> {@code docCount} &lt;= {@code maxDoc}
+ * <li> {@code docCount} &lt;= {@code sumDocFreq} &lt;= {@code sumTotalTermFreq}
+ * </ul>
+ * <p>
+ * Values may include statistics on deleted documents that have not yet been merged away.
+ * <p>
+ * Be careful when performing calculations on these values because they are represented
+ * as 64-bit integer values, you may need to cast to {@code double} for your use.
* @lucene.experimental
*/
public class CollectionStatistics {
@@ -51,33 +71,23 @@ public class CollectionStatistics {
if (maxDoc <= 0) {
throw new IllegalArgumentException("maxDoc must be positive, maxDoc: " + maxDoc);
}
- if (docCount != -1) {
- if (docCount <= 0) {
- throw new IllegalArgumentException("docCount must be positive, docCount: " + docCount);
- }
- if (docCount > maxDoc) {
- throw new IllegalArgumentException("docCount must not exceed maxDoc, docCount: " + docCount + ", maxDoc: " + maxDoc);
- }
+ if (docCount <= 0) {
+ throw new IllegalArgumentException("docCount must be positive, docCount: " + docCount);
}
- if (sumDocFreq != -1) {
- if (sumDocFreq <= 0) {
- throw new IllegalArgumentException("sumDocFreq must be positive, sumDocFreq: " + sumDocFreq);
- }
- if (docCount != -1) {
- if (sumDocFreq < docCount) {
- throw new IllegalArgumentException("sumDocFreq must be at least docCount, sumDocFreq: " + sumDocFreq + ", docCount: " + docCount);
- }
- }
+ if (docCount > maxDoc) {
+ throw new IllegalArgumentException("docCount must not exceed maxDoc, docCount: " + docCount + ", maxDoc: " + maxDoc);
}
- if (sumTotalTermFreq != -1) {
- if (sumTotalTermFreq <= 0) {
- throw new IllegalArgumentException("sumTotalTermFreq must be positive, sumTotalTermFreq: " + sumTotalTermFreq);
- }
- if (sumDocFreq != -1) {
- if (sumTotalTermFreq < sumDocFreq) {
- throw new IllegalArgumentException("sumTotalTermFreq must be at least sumDocFreq, sumTotalTermFreq: " + sumTotalTermFreq + ", sumDocFreq: " + sumDocFreq);
- }
- }
+ if (sumDocFreq <= 0) {
+ throw new IllegalArgumentException("sumDocFreq must be positive, sumDocFreq: " + sumDocFreq);
+ }
+ if (sumDocFreq < docCount) {
+ throw new IllegalArgumentException("sumDocFreq must be at least docCount, sumDocFreq: " + sumDocFreq + ", docCount: " + docCount);
+ }
+ if (sumTotalTermFreq <= 0) {
+ throw new IllegalArgumentException("sumTotalTermFreq must be positive, sumTotalTermFreq: " + sumTotalTermFreq);
+ }
+ if (sumTotalTermFreq < sumDocFreq) {
+ throw new IllegalArgumentException("sumTotalTermFreq must be at least sumDocFreq, sumTotalTermFreq: " + sumTotalTermFreq + ", sumDocFreq: " + sumDocFreq);
}
this.field = field;
this.maxDoc = maxDoc;
@@ -86,33 +96,65 @@ public class CollectionStatistics {
this.sumDocFreq = sumDocFreq;
}
- /** returns the field name */
+ /**
+ * The field's name.
+ * <p>
+ * This value is never {@code null}.
+ * @return field's name, not {@code null}
+ */
public final String field() {
return field;
}
- /** returns the total number of documents, regardless of
- * whether they all contain values for this field.
- * @see IndexReader#maxDoc() */
+ /**
+ * The total number of documents, regardless of
+ * whether they all contain values for this field.
+ * <p>
+ * This value is always a positive number.
+ * @return total number of documents, in the range [1 .. {@link Long#MAX_VALUE}]
+ * @see IndexReader#maxDoc()
+ */
public final long maxDoc() {
return maxDoc;
}
- /** returns the total number of documents that
- * have at least one term for this field.
- * @see Terms#getDocCount() */
+ /**
+ * The total number of documents that have at least
+ * one term for this field.
+ * <p>
+ * This value is always a positive number, and never
+ * exceeds {@link #maxDoc()}.
+ * @return total number of documents containing this field, in the range [1 .. {@link #maxDoc()}]
+ * @see Terms#getDocCount()
+ */
public final long docCount() {
return docCount;
}
- /** returns the total number of tokens for this field
- * @see Terms#getSumTotalTermFreq() */
+ /**
+ * The total number of tokens for this field.
+ * This is the "word count" for this field across all documents.
+ * It is the sum of {@link TermStatistics#totalTermFreq()} across all terms.
+ * It is also the sum of each document's field length across all documents.
+ * <p>
+ * This value is always a positive number, and always at least {@link #sumDocFreq()}.
+ * @return total number of tokens in the field, in the range [{@link #sumDocFreq()} .. {@link Long#MAX_VALUE}]
+ * @see Terms#getSumTotalTermFreq()
+ */
public final long sumTotalTermFreq() {
return sumTotalTermFreq;
}
- /** returns the total number of postings for this field
- * @see Terms#getSumDocFreq() */
+ /**
+ * The total number of posting list entries for this field.
+ * This is the sum of term-document pairs: the sum of {@link TermStatistics#docFreq()} across all terms.
+ * It is also the sum of each document's unique term count for this field across all documents.
+ * <p>
+ * This value is always a positive number, always at least {@link #docCount()}, and never
+ * exceeds {@link #sumTotalTermFreq()}.
+ * @return number of posting list entries, in the range [{@link #docCount()} .. {@link #sumTotalTermFreq()}]
+ * @see Terms#getSumDocFreq()
+ */
public final long sumDocFreq() {
return sumDocFreq;
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
index 20266781d03..a2eae926801 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
@@ -86,17 +86,17 @@ public final class DocValuesRewriteMethod extends MultiTermQuery.RewriteMethod {
@Override
public long getSumTotalTermFreq() {
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
public long getSumDocFreq() {
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
public int getDocCount() {
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 79703f5908a..7fc5e5fc926 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -492,14 +492,13 @@ public class PhraseQuery extends Query {
* of processing the occurrences of a term
* in a document that contains the term.
* This is for use by {@link TwoPhaseIterator#matchCost} implementations.
- * <br>This may be inaccurate when {@link TermsEnum#totalTermFreq()} is not available.
* @param termsEnum The term is the term at which this TermsEnum is positioned.
*/
static float termPositionsCost(TermsEnum termsEnum) throws IOException {
int docFreq = termsEnum.docFreq();
assert docFreq > 0;
- long totalTermFreq = termsEnum.totalTermFreq(); // -1 when not available
- float expOccurrencesInMatchingDoc = (totalTermFreq < docFreq) ? 1 : (totalTermFreq / (float) docFreq);
+ long totalTermFreq = termsEnum.totalTermFreq();
+ float expOccurrencesInMatchingDoc = totalTermFreq / (float) docFreq;
return TERM_POSNS_SEEK_OPS_PER_DOC + expOccurrencesInMatchingDoc * TERM_OPS_PER_POS;
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java b/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
index e9e663683df..fedb89ed78d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SynonymQuery.java
@@ -140,11 +140,7 @@ public final class SynonymQuery extends Query {
TermStatistics termStats = searcher.termStatistics(terms[i], termContexts[i]);
if (termStats != null) {
docFreq = Math.max(termStats.docFreq(), docFreq);
- if (termStats.totalTermFreq() == -1) {
- totalTermFreq = -1;
- } else if (totalTermFreq != -1) {
- totalTermFreq += termStats.totalTermFreq();
- }
+ totalTermFreq += termStats.totalTermFreq();
}
}
this.similarity = searcher.getSimilarity(true);
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
index 587c5138355..e5156866b13 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
@@ -65,9 +65,9 @@ public class TermQuery extends Query {
collectionStats = searcher.collectionStatistics(term.field());
termStats = searcher.termStatistics(term, termStates);
} else {
- // we do not need the actual stats, use fake stats with docFreq=maxDoc=1 and ttf=-1
- collectionStats = new CollectionStatistics(term.field(), 1, -1, -1, -1);
- termStats = new TermStatistics(term.bytes(), 1, -1);
+ // we do not need the actual stats, use fake stats with docFreq=maxDoc=ttf=1
+ collectionStats = new CollectionStatistics(term.field(), 1, 1, 1, 1);
+ termStats = new TermStatistics(term.bytes(), 1, 1);
}
if (termStats == null) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermStatistics.java b/lucene/core/src/java/org/apache/lucene/search/TermStatistics.java
index 7d4f03a7d34..be9669feef0 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermStatistics.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermStatistics.java
@@ -24,8 +24,29 @@ import org.apache.lucene.index.TermsEnum; // javadocs
import org.apache.lucene.util.BytesRef;
/**
* Contains statistics for a specific term
+ * <p>
+ * This class holds statistics for this term across all documents for scoring purposes:
+ * <ul>
+ * <li> {@link #docFreq}: number of documents this term occurs in.
+ * <li> {@link #totalTermFreq}: number of tokens for this term.
+ * </ul>
+ * <p>
+ * The following conditions are always true:
+ * <ul>
+ * <li> All statistics are positive integers: never zero or negative.
+ * <li> {@code docFreq} &lt;= {@code totalTermFreq}
+ * <li> {@code docFreq} &lt;= {@code sumDocFreq} of the collection
+ * <li> {@code totalTermFreq} &lt;= {@code sumTotalTermFreq} of the collection
+ * </ul>
+ * <p>
+ * Values may include statistics on deleted documents that have not yet been merged away.
+ * <p>
+ * Be careful when performing calculations on these values because they are represented
+ * as 64-bit integer values, you may need to cast to {@code double} for your use.
* @lucene.experimental
*/
+// TODO: actually add missing cross-checks to guarantee TermStatistics is in bounds of CollectionStatistics,
+// otherwise many similarity functions will implode.
public class TermStatistics {
private final BytesRef term;
private final long docFreq;
@@ -45,29 +66,52 @@ public class TermStatistics {
if (docFreq <= 0) {
throw new IllegalArgumentException("docFreq must be positive, docFreq: " + docFreq);
}
- if (totalTermFreq != -1) {
- if (totalTermFreq < docFreq) {
- throw new IllegalArgumentException("totalTermFreq must be at least docFreq, totalTermFreq: " + totalTermFreq + ", docFreq: " + docFreq);
- }
+ if (totalTermFreq <= 0) {
+ throw new IllegalArgumentException("totalTermFreq must be positive, totalTermFreq: " + totalTermFreq);
+ }
+ if (totalTermFreq < docFreq) {
+ throw new IllegalArgumentException("totalTermFreq must be at least docFreq, totalTermFreq: " + totalTermFreq + ", docFreq: " + docFreq);
}
this.term = term;
this.docFreq = docFreq;
this.totalTermFreq = totalTermFreq;
}
- /** returns the term text */
+ /**
+ * The term text.
+ * <p>
+ * This value is never {@code null}.
+ * @return term's text, not {@code null}
+ */
public final BytesRef term() {
return term;
}
- /** returns the number of documents this term occurs in
- * @see TermsEnum#docFreq() */
+ /**
+ * The number of documents this term occurs in.
+ * <p>
+ * This is the document-frequency for the term: the count of documents
+ * where the term appears at least one time.
+ * <p>
+ * This value is always a positive number, and never
+ * exceeds {@link #totalTermFreq}. It also cannot exceed {@link CollectionStatistics#sumDocFreq()}.
+ * @return document frequency, in the range [1 .. {@link #totalTermFreq()}]
+ * @see TermsEnum#docFreq()
+ */
public final long docFreq() {
return docFreq;
}
- /** returns the total number of occurrences of this term
- * @see TermsEnum#totalTermFreq() */
+ /**
+ * The total number of occurrences of this term.
+ * <p>
+ * This is the token count for the term: the number of times it appears in the field across all documents.
+ * <p>
+ * This value is always a positive number, always at least {@link #docFreq()},
+ * and never exceeds {@link CollectionStatistics#sumTotalTermFreq()}.
+ * @return number of occurrences, in the range [{@link #docFreq()} .. {@link CollectionStatistics#sumTotalTermFreq()}]
+ * @see TermsEnum#totalTermFreq()
+ */
public final long totalTermFreq() {
return totalTermFreq;
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
index 47561e43ceb..812f9cece4e 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
@@ -85,19 +85,7 @@ public class BM25Similarity extends Similarity {
/** The default implementation computes the average as <code>sumTotalTermFreq / docCount</code> */
protected float avgFieldLength(CollectionStatistics collectionStats) {
- final long sumTotalTermFreq;
- if (collectionStats.sumTotalTermFreq() == -1) {
- // frequencies are omitted (tf=1), its # of postings
- if (collectionStats.sumDocFreq() == -1) {
- // theoretical case only: remove!
- return 1f;
- }
- sumTotalTermFreq = collectionStats.sumDocFreq();
- } else {
- sumTotalTermFreq = collectionStats.sumTotalTermFreq();
- }
- final long docCount = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
- return (float) (sumTotalTermFreq / (double) docCount);
+ return (float) (collectionStats.sumTotalTermFreq() / (double) collectionStats.docCount());
}
/**
@@ -161,7 +149,7 @@ public class BM25Similarity extends Similarity {
*/
public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics termStats) {
final long df = termStats.docFreq();
- final long docCount = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
+ final long docCount = collectionStats.docCount();
final float idf = idf(df, docCount);
return Explanation.match(idf, "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:",
Explanation.match(df, "n, number of documents containing term"),
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java
index f33abdbf774..c7edf706ec7 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java
@@ -62,7 +62,7 @@ public class ClassicSimilarity extends TFIDFSimilarity {
@Override
public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics termStats) {
final long df = termStats.docFreq();
- final long docCount = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
+ final long docCount = collectionStats.docCount();
final float idf = idf(df, docCount);
return Explanation.match(idf, "idf, computed as log((docCount+1)/(docFreq+1)) + 1 from:",
Explanation.match(df, "docFreq, number of documents containing term"),
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
index babef8f5e03..9407b5cd122 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
@@ -100,42 +100,16 @@ public abstract class SimilarityBase extends Similarity {
/** Fills all member fields defined in {@code BasicStats} in {@code stats}.
* Subclasses can override this method to fill additional stats. */
protected void fillBasicStats(BasicStats stats, CollectionStatistics collectionStats, TermStatistics termStats) {
- // #positions(field) must be >= #positions(term)
- assert collectionStats.sumTotalTermFreq() == -1 || collectionStats.sumTotalTermFreq() >= termStats.totalTermFreq();
- long numberOfDocuments = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
-
- long docFreq = termStats.docFreq();
- long totalTermFreq = termStats.totalTermFreq();
-
- // frequencies are omitted, all postings have tf=1, so totalTermFreq = docFreq
- if (totalTermFreq == -1) {
- totalTermFreq = docFreq;
- }
-
- final long numberOfFieldTokens;
- final double avgFieldLength;
-
- if (collectionStats.sumTotalTermFreq() == -1) {
- // frequencies are omitted, so sumTotalTermFreq = # postings
- if (collectionStats.sumDocFreq() == -1) {
- // theoretical case only: remove!
- numberOfFieldTokens = docFreq;
- avgFieldLength = 1f;
- } else {
- numberOfFieldTokens = collectionStats.sumDocFreq();
- avgFieldLength = (float) (collectionStats.sumDocFreq() / (double)numberOfDocuments);
- }
- } else {
- numberOfFieldTokens = collectionStats.sumTotalTermFreq();
- avgFieldLength = (float) (collectionStats.sumTotalTermFreq() / (double)numberOfDocuments);
- }
+ // TODO: validate this for real, somewhere else
+ assert termStats.totalTermFreq() <= collectionStats.sumTotalTermFreq();
+ assert termStats.docFreq() <= collectionStats.sumDocFreq();
// TODO: add sumDocFreq for field (numberOfFieldPostings)
- stats.setNumberOfDocuments(numberOfDocuments);
- stats.setNumberOfFieldTokens(numberOfFieldTokens);
- stats.setAvgFieldLength(avgFieldLength);
- stats.setDocFreq(docFreq);
- stats.setTotalTermFreq(totalTermFreq);
+ stats.setNumberOfDocuments(collectionStats.docCount());
+ stats.setNumberOfFieldTokens(collectionStats.sumTotalTermFreq());
+ stats.setAvgFieldLength(collectionStats.sumTotalTermFreq() / (double) collectionStats.docCount());
+ stats.setDocFreq(termStats.docFreq());
+ stats.setTotalTermFreq(termStats.totalTermFreq());
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
index 5765e6bfae3..54744cecb2f 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
@@ -448,7 +448,7 @@ public abstract class TFIDFSimilarity extends Similarity {
*/
public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics termStats) {
final long df = termStats.docFreq();
- final long docCount = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
+ final long docCount = collectionStats.docCount();
final float idf = idf(df, docCount);
return Explanation.match(idf, "idf(docFreq, docCount)",
Explanation.match(df, "docFreq, number of documents containing term"),
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/package-info.java b/lucene/core/src/java/org/apache/lucene/search/similarities/package-info.java
index 1ed9669147c..34a014badd5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/package-info.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/package-info.java
@@ -32,14 +32,14 @@
* <a name="sims"></a>
* <h2>Summary of the Ranking Methods</h2>
*
+ * <p>{@link org.apache.lucene.search.similarities.BM25Similarity} is an optimized
+ * implementation of the successful Okapi BM25 model.
+ *
* <p>{@link org.apache.lucene.search.similarities.ClassicSimilarity} is the original Lucene
- * scoring function. It is based on a highly optimized
+ * scoring function. It is based on the
* <a href="http://en.wikipedia.org/wiki/Vector_Space_Model">Vector Space Model</a>. For more
* information, see {@link org.apache.lucene.search.similarities.TFIDFSimilarity}.
*
- * <p>{@link org.apache.lucene.search.similarities.BM25Similarity} is an optimized
- * implementation of the successful Okapi BM25 model.
- *
* <p>{@link org.apache.lucene.search.similarities.SimilarityBase} provides a basic
* implementation of the Similarity contract and exposes a highly simplified
* interface, which makes it an ideal starting point for new ranking functions.
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
index 3e13be7ecb1..621f4e6d8fa 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
@@ -135,7 +135,6 @@ public class SpanTermQuery extends SpanQuery {
/** Returns an expected cost in simple operations
* of processing the occurrences of a term
* in a document that contains the term.
- * <br>This may be inaccurate when {@link TermsEnum#totalTermFreq()} is not available.
* @param termsEnum The term is the term at which this TermsEnum is positioned.
* <p>
* This is a copy of org.apache.lucene.search.PhraseQuery.termPositionsCost().
@@ -146,8 +145,9 @@ public class SpanTermQuery extends SpanQuery {
static float termPositionsCost(TermsEnum termsEnum) throws IOException {
int docFreq = termsEnum.docFreq();
assert docFreq > 0;
- long totalTermFreq = termsEnum.totalTermFreq(); // -1 when not available
- float expOccurrencesInMatchingDoc = (totalTermFreq < docFreq) ? 1 : (totalTermFreq / (float) docFreq);
+ long totalTermFreq = termsEnum.totalTermFreq();
+ assert totalTermFreq > 0;
+ float expOccurrencesInMatchingDoc = totalTermFreq / (float) docFreq;
return TERM_POSNS_SEEK_OPS_PER_DOC + expOccurrencesInMatchingDoc * TERM_OPS_PER_POS;
}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
index 1b3b9affdf3..3b99ee17105 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
@@ -172,10 +172,11 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
// NOTE: we don't assert hasOffsets/hasPositions/hasPayloads because they are allowed to be different
+ boolean bothHaveFreqs = leftTerms.hasFreqs() && rightTerms.hasFreqs();
boolean bothHavePositions = leftTerms.hasPositions() && rightTerms.hasPositions();
TermsEnum leftTermsEnum = leftTerms.iterator();
TermsEnum rightTermsEnum = rightTerms.iterator();
- assertTermsEnum(leftTermsEnum, rightTermsEnum, true, bothHavePositions);
+ assertTermsEnum(leftTermsEnum, rightTermsEnum, true, bothHaveFreqs, bothHavePositions);
assertTermsSeeking(leftTerms, rightTerms);
@@ -188,7 +189,7 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
// TODO: test start term too
TermsEnum leftIntersection = leftTerms.intersect(automaton, null);
TermsEnum rightIntersection = rightTerms.intersect(automaton, null);
- assertTermsEnum(leftIntersection, rightIntersection, rarely(), bothHavePositions);
+ assertTermsEnum(leftIntersection, rightIntersection, rarely(), bothHaveFreqs, bothHavePositions);
}
}
}
@@ -263,13 +264,9 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
* checks collection-level statistics on Terms
*/
public void assertTermsStatistics(Terms leftTerms, Terms rightTerms) throws Exception {
- if (leftTerms.getDocCount() != -1 && rightTerms.getDocCount() != -1) {
- assertEquals(leftTerms.getDocCount(), rightTerms.getDocCount());
- }
- if (leftTerms.getSumDocFreq() != -1 && rightTerms.getSumDocFreq() != -1) {
- assertEquals(leftTerms.getSumDocFreq(), rightTerms.getSumDocFreq());
- }
- if (leftTerms.getSumTotalTermFreq() != -1 && rightTerms.getSumTotalTermFreq() != -1) {
+ assertEquals(leftTerms.getDocCount(), rightTerms.getDocCount());
+ assertEquals(leftTerms.getSumDocFreq(), rightTerms.getSumDocFreq());
+ if (leftTerms.hasFreqs() && rightTerms.hasFreqs()) {
assertEquals(leftTerms.getSumTotalTermFreq(), rightTerms.getSumTotalTermFreq());
}
if (leftTerms.size() != -1 && rightTerms.size() != -1) {
@@ -281,7 +278,7 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
* checks the terms enum sequentially
* if deep is false, it does a 'shallow' test that doesnt go down to the docsenums
*/
- public void assertTermsEnum(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum, boolean deep, boolean hasPositions) throws Exception {
+ public void assertTermsEnum(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum, boolean deep, boolean hasFreqs, boolean hasPositions) throws Exception {
BytesRef term;
PostingsEnum leftPositions = null;
PostingsEnum rightPositions = null;
@@ -290,7 +287,7 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
while ((term = leftTermsEnum.next()) != null) {
assertEquals(term, rightTermsEnum.next());
- assertTermStats(leftTermsEnum, rightTermsEnum);
+ assertTermStats(leftTermsEnum, rightTermsEnum, hasFreqs);
if (deep) {
if (hasPositions) {
// with payloads + off
@@ -350,9 +347,9 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
/**
* checks term-level statistics
*/
- public void assertTermStats(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum) throws Exception {
+ public void assertTermStats(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum, boolean bothHaveFreqs) throws Exception {
assertEquals(leftTermsEnum.docFreq(), rightTermsEnum.docFreq());
- if (leftTermsEnum.totalTermFreq() != -1 && rightTermsEnum.totalTermFreq() != -1) {
+ if (bothHaveFreqs) {
assertEquals(leftTermsEnum.totalTermFreq(), rightTermsEnum.totalTermFreq());
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestMultiTermsEnum.java b/lucene/core/src/test/org/apache/lucene/index/TestMultiTermsEnum.java
index a265c9c174e..dbd685ac77e 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestMultiTermsEnum.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestMultiTermsEnum.java
@@ -148,26 +148,22 @@ public class TestMultiTermsEnum extends LuceneTestCase {
@Override
public long size() throws IOException {
- // Docs say we can return -1 if we don't know.
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
public long getSumTotalTermFreq() throws IOException {
- // Docs say we can return -1 if we don't know.
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
public long getSumDocFreq() throws IOException {
- // Docs say we can return -1 if we don't know.
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
public int getDocCount() throws IOException {
- // Docs say we can return -1 if we don't know.
- return -1;
+ throw new UnsupportedOperationException();
}
@Override
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java
index 8af744f78c3..e0f618b9a07 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java
@@ -445,7 +445,7 @@ public class TestOmitTf extends LuceneTestCase {
}
}
- /** test that when freqs are omitted, that totalTermFreq and sumTotalTermFreq are -1 */
+ /** test that when freqs are omitted, that totalTermFreq and sumTotalTermFreq are docFreq, and sumDocFreq */
public void testStats() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter iw = new RandomIndexWriter(random(), dir,
@@ -459,8 +459,8 @@ public class TestOmitTf extends LuceneTestCase {
iw.addDocument(doc);
IndexReader ir = iw.getReader();
iw.close();
- assertEquals(-1, ir.totalTermFreq(new Term("foo", new BytesRef("bar"))));
- assertEquals(-1, ir.getSumTotalTermFreq("foo"));
+ assertEquals(ir.docFreq(new Term("foo", new BytesRef("bar"))), ir.totalTermFreq(new Term("foo", new BytesRef("bar"))));
+ assertEquals(ir.getSumDocFreq("foo"), ir.getSumTotalTermFreq("foo"));
ir.close();
dir.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
index e52c9742f65..8a6227c9552 100644
--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
@@ -40,6 +40,7 @@ import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.Version;
/**
@@ -183,7 +184,17 @@ public class TestSimilarityBase extends LuceneTestCase {
}
private CollectionStatistics toCollectionStats(BasicStats stats) {
- return new CollectionStatistics(stats.field, stats.getNumberOfDocuments(), -1, stats.getNumberOfFieldTokens(), -1);
+ long sumTtf = stats.getNumberOfFieldTokens();
+ long sumDf;
+ if (sumTtf == -1) {
+ sumDf = TestUtil.nextLong(random(), stats.getNumberOfDocuments(), 2L * stats.getNumberOfDocuments());
+ } else {
+ sumDf = TestUtil.nextLong(random(), Math.min(stats.getNumberOfDocuments(), sumTtf), sumTtf);
+ }
+ int docCount = Math.toIntExact(Math.min(sumDf, stats.getNumberOfDocuments()));
+ int maxDoc = TestUtil.nextInt(random(), docCount, docCount + 10);
+
+ return new CollectionStatistics(stats.field, maxDoc, docCount, sumTtf, sumDf);
}
private TermStatistics toTermStats(BasicStats stats) {
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
index 346ecba013d..135bfe88e2b 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TokenStreamFromTermVector.java
@@ -238,13 +238,8 @@ public final class TokenStreamFromTermVector extends TokenStream {
// Estimate the number of position slots we need from term stats. We use some estimation factors taken from
// Wikipedia that reduce the likelihood of needing to expand the array.
int sumTotalTermFreq = (int) vector.getSumTotalTermFreq();
- if (sumTotalTermFreq == -1) {//unfortunately term vectors seem to not have this stat
- int size = (int) vector.size();
- if (size == -1) {//doesn't happen with term vectors, it seems, but pick a default any way
- size = 128;
- }
- sumTotalTermFreq = (int)(size * 2.4);
- }
+ assert sumTotalTermFreq != -1;
+
final int originalPositionEstimate = (int) (sumTotalTermFreq * 1.5);//less than 1 in 10 docs exceed this
// This estimate is based on maxStartOffset. Err on the side of this being larger than needed.
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/SumTotalTermFreqValueSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/SumTotalTermFreqValueSource.java
index 746ad8e9d18..716d3045397 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/SumTotalTermFreqValueSource.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/SumTotalTermFreqValueSource.java
@@ -29,8 +29,6 @@ import java.util.Map;
/**
* <code>SumTotalTermFreqValueSource</code> returns the number of tokens.
* (sum of term freqs across all documents, across all terms).
- * Returns -1 if frequencies were omitted for the field, or if
- * the codec doesn't support this statistic.
* @lucene.internal
*/
public class SumTotalTermFreqValueSource extends ValueSource {
@@ -61,12 +59,8 @@ public class SumTotalTermFreqValueSource extends ValueSource {
Terms terms = readerContext.reader().terms(indexedField);
if (terms == null) continue;
long v = terms.getSumTotalTermFreq();
- if (v == -1) {
- sumTotalTermFreq = -1;
- break;
- } else {
- sumTotalTermFreq += v;
- }
+ assert v != -1;
+ sumTotalTermFreq += v;
}
final long ttf = sumTotalTermFreq;
context.put(this, new LongDocValues(this) {
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/TotalTermFreqValueSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/TotalTermFreqValueSource.java
index aabe45f6d8f..5a69e42fcd2 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/TotalTermFreqValueSource.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/TotalTermFreqValueSource.java
@@ -30,8 +30,6 @@ import java.util.Map;
/**
* <code>TotalTermFreqValueSource</code> returns the total term freq
* (sum of term freqs across all documents).
- * Returns -1 if frequencies were omitted for the field, or if
- * the codec doesn't support this statistic.
* @lucene.internal
*/
public class TotalTermFreqValueSource extends ValueSource {
@@ -66,12 +64,8 @@ public class TotalTermFreqValueSource extends ValueSource {
long totalTermFreq = 0;
for (LeafReaderContext readerContext : searcher.getTopReaderContext().leaves()) {
long val = readerContext.reader().totalTermFreq(new Term(indexedField, indexedBytes));
- if (val == -1) {
- totalTermFreq = -1;
- break;
- } else {
- totalTermFreq += val;
- }
+ assert val != -1;
+ totalTermFreq += val;
}
final long ttf = totalTermFreq;
context.put(this, new LongDocValues(this) {
diff --git a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsReader.java b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsReader.java
index 167bb4808e4..b33b258f562 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsReader.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsReader.java
@@ -137,7 +137,7 @@ public final class VersionBlockTreeTermsReader extends FieldsProducer {
if (sumDocFreq < docCount) { // #postings must be >= #docs with field
throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount, in);
}
- if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
+ if (sumTotalTermFreq < sumDocFreq) { // #positions must be >= #postings
throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq, in);
}
final long indexStartFP = indexIn.readVLong();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/AssertingLeafReader.java b/lucene/test-framework/src/java/org/apache/lucene/index/AssertingLeafReader.java
index 42ddb0e1aa8..c87697bcc11 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/AssertingLeafReader.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/AssertingLeafReader.java
@@ -117,7 +117,7 @@ public class AssertingLeafReader extends FilterLeafReader {
TermsEnum termsEnum = in.intersect(automaton, bytes);
assert termsEnum != null;
assert bytes == null || bytes.isValid();
- return new AssertingTermsEnum(termsEnum);
+ return new AssertingTermsEnum(termsEnum, hasFreqs());
}
@Override
@@ -134,11 +134,35 @@ public class AssertingLeafReader extends FilterLeafReader {
return v;
}
+ @Override
+ public int getDocCount() throws IOException {
+ final int docCount = in.getDocCount();
+ assert docCount > 0;
+ return docCount;
+ }
+
+ @Override
+ public long getSumDocFreq() throws IOException {
+ final long sumDf = in.getSumDocFreq();
+ assert sumDf >= getDocCount();
+ return sumDf;
+ }
+
+ @Override
+ public long getSumTotalTermFreq() throws IOException {
+ final long sumTtf = in.getSumTotalTermFreq();
+ if (hasFreqs() == false) {
+ assert sumTtf == in.getSumDocFreq();
+ }
+ assert sumTtf >= getSumDocFreq();
+ return sumTtf;
+ }
+
@Override
public TermsEnum iterator() throws IOException {
TermsEnum termsEnum = super.iterator();
assert termsEnum != null;
- return new AssertingTermsEnum(termsEnum);
+ return new AssertingTermsEnum(termsEnum, hasFreqs());
}
@Override
@@ -154,10 +178,12 @@ public class AssertingLeafReader extends FilterLeafReader {
private enum State {INITIAL, POSITIONED, UNPOSITIONED};
private State state = State.INITIAL;
private final boolean delegateOverridesSeekExact;
+ private final boolean hasFreqs;
- public AssertingTermsEnum(TermsEnum in) {
+ public AssertingTermsEnum(TermsEnum in, boolean hasFreqs) {
super(in);
delegateOverridesSeekExact = SEEK_EXACT.isOverriddenAsOf(in.getClass());
+ this.hasFreqs = hasFreqs;
}
@Override
@@ -210,14 +236,22 @@ public class AssertingLeafReader extends FilterLeafReader {
public int docFreq() throws IOException {
assertThread("Terms enums", creationThread);
assert state == State.POSITIONED : "docFreq() called on unpositioned TermsEnum";
- return super.docFreq();
+ final int df = super.docFreq();
+ assert df > 0;
+ return df;
}
@Override
public long totalTermFreq() throws IOException {
assertThread("Terms enums", creationThread);
assert state == State.POSITIONED : "totalTermFreq() called on unpositioned TermsEnum";
- return super.totalTermFreq();
+ final long ttf = super.totalTermFreq();
+ if (hasFreqs) {
+ assert ttf >= docFreq();
+ } else {
+ assert ttf == docFreq();
+ }
+ return ttf;
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/ShardSearchingTestBase.java b/lucene/test-framework/src/java/org/apache/lucene/search/ShardSearchingTestBase.java
index a6b44b0a92f..918811f0db7 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/ShardSearchingTestBase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/ShardSearchingTestBase.java
@@ -281,18 +281,10 @@ public abstract class ShardSearchingTestBase extends LuceneTestCase {
}
long nodeDocFreq = subStats.docFreq();
- if (docFreq >= 0 && nodeDocFreq >= 0) {
- docFreq += nodeDocFreq;
- } else {
- docFreq = -1;
- }
+ docFreq += nodeDocFreq;
long nodeTotalTermFreq = subStats.totalTermFreq();
- if (totalTermFreq >= 0 && nodeTotalTermFreq >= 0) {
- totalTermFreq += nodeTotalTermFreq;
- } else {
- totalTermFreq = -1;
- }
+ totalTermFreq += nodeTotalTermFreq;
}
if (docFreq == 0) {
@@ -325,25 +317,13 @@ public abstract class ShardSearchingTestBase extends LuceneTestCase {
}
long nodeDocCount = nodeStats.docCount();
- if (docCount >= 0 && nodeDocCount >= 0) {
- docCount += nodeDocCount;
- } else {
- docCount = -1;
- }
+ docCount += nodeDocCount;
long nodeSumTotalTermFreq = nodeStats.sumTotalTermFreq();
- if (sumTotalTermFreq >= 0 && nodeSumTotalTermFreq >= 0) {
- sumTotalTermFreq += nodeSumTotalTermFreq;
- } else {
- sumTotalTermFreq = -1;
- }
+ sumTotalTermFreq += nodeSumTotalTermFreq;
long nodeSumDocFreq = nodeStats.sumDocFreq();
- if (sumDocFreq >= 0 && nodeSumDocFreq >= 0) {
- sumDocFreq += nodeSumDocFreq;
- } else {
- sumDocFreq = -1;
- }
+ sumDocFreq += nodeSumDocFreq;
assert nodeStats.maxDoc() >= 0;
maxDoc += nodeStats.maxDoc();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/similarities/BaseSimilarityTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/search/similarities/BaseSimilarityTestCase.java
index d93594d884c..a0f2ece9a43 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/similarities/BaseSimilarityTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/similarities/BaseSimilarityTestCase.java
@@ -200,7 +200,6 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
// yuge collection
maxDoc = TestUtil.nextLong(random, 1, MAXDOC_FORTESTING);
}
- // TODO: make this a mandatory statistic, or test it with -1
final long docCount;
if (random.nextBoolean()) {
// sparse field
@@ -216,7 +215,6 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
} catch (ArithmeticException overflow) {
upperBound = MAXTOKENS_FORTESTING;
}
- // TODO: make this a mandatory statistic, or test it with -1
final long sumDocFreq;
if (random.nextBoolean()) {
// shortest possible docs
@@ -228,8 +226,8 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
final long sumTotalTermFreq;
switch (random.nextInt(3)) {
case 0:
- // unsupported (e.g. omitTF)
- sumTotalTermFreq = -1;
+ // term frequencies were omitted
+ sumTotalTermFreq = sumDocFreq;
break;
case 1:
// no repetition of terms (except to satisfy this norm)
@@ -259,9 +257,9 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
docFreq = TestUtil.nextLong(random, 1, corpus.docCount());
}
final long totalTermFreq;
- if (corpus.sumTotalTermFreq() == -1) {
+ if (corpus.sumTotalTermFreq() == corpus.sumDocFreq()) {
// omitTF
- totalTermFreq = -1;
+ totalTermFreq = docFreq;
} else if (random.nextBoolean()) {
// no repetition
totalTermFreq = docFreq;
@@ -307,7 +305,7 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
for (int l = 0; l < 10; l++) {
TermStatistics term = newTerm(random, corpus);
final float freq;
- if (term.totalTermFreq() == -1) {
+ if (term.totalTermFreq() == term.docFreq()) {
// omit TF
freq = 1;
} else if (term.docFreq() == 1) {
@@ -427,14 +425,8 @@ public abstract class BaseSimilarityTestCase extends LuceneTestCase {
}
// check score(term-1), given the same freq/norm it should be >= score(term) [scores non-decreasing as terms get rarer]
- if (term.docFreq() > 1 && (term.totalTermFreq() == -1 || freq < term.totalTermFreq())) {
- final long prevTotalTermFreq;
- if (term.totalTermFreq() == -1) {
- prevTotalTermFreq = -1;
- } else {
- prevTotalTermFreq = term.totalTermFreq() - 1;
- }
- TermStatistics prevTerm = new TermStatistics(term.term(), term.docFreq() - 1, prevTotalTermFreq);
+ if (term.docFreq() > 1 && freq < term.totalTermFreq()) {
+ TermStatistics prevTerm = new TermStatistics(term.term(), term.docFreq() - 1, term.totalTermFreq() - 1);
SimWeight prevWeight = similarity.computeWeight(boost, corpus, term);
SimScorer prevTermScorer = similarity.simScorer(prevWeight, NORM_VALUES.get(norm).getContext());
float prevTermScore = prevTermScorer.score(0, freq);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
index 3a87c1e24c4..ecdd6111b67 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
@@ -2025,15 +2025,9 @@ public abstract class LuceneTestCase extends Assert {
* checks collection-level statistics on Terms
*/
public void assertTermsStatisticsEquals(String info, Terms leftTerms, Terms rightTerms) throws IOException {
- if (leftTerms.getDocCount() != -1 && rightTerms.getDocCount() != -1) {
- assertEquals(info, leftTerms.getDocCount(), rightTerms.getDocCount());
- }
- if (leftTerms.getSumDocFreq() != -1 && rightTerms.getSumDocFreq() != -1) {
- assertEquals(info, leftTerms.getSumDocFreq(), rightTerms.getSumDocFreq());
- }
- if (leftTerms.getSumTotalTermFreq() != -1 && rightTerms.getSumTotalTermFreq() != -1) {
- assertEquals(info, leftTerms.getSumTotalTermFreq(), rightTerms.getSumTotalTermFreq());
- }
+ assertEquals(info, leftTerms.getDocCount(), rightTerms.getDocCount());
+ assertEquals(info, leftTerms.getSumDocFreq(), rightTerms.getSumDocFreq());
+ assertEquals(info, leftTerms.getSumTotalTermFreq(), rightTerms.getSumTotalTermFreq());
if (leftTerms.size() != -1 && rightTerms.size() != -1) {
assertEquals(info, leftTerms.size(), rightTerms.size());
}
@@ -2312,9 +2306,7 @@ public abstract class LuceneTestCase extends Assert {
*/
public void assertTermStatsEquals(String info, TermsEnum leftTermsEnum, TermsEnum rightTermsEnum) throws IOException {
assertEquals(info, leftTermsEnum.docFreq(), rightTermsEnum.docFreq());
- if (leftTermsEnum.totalTermFreq() != -1 && rightTermsEnum.totalTermFreq() != -1) {
- assertEquals(info, leftTermsEnum.totalTermFreq(), rightTermsEnum.totalTermFreq());
- }
+ assertEquals(info, leftTermsEnum.totalTermFreq(), rightTermsEnum.totalTermFreq());
}
/**
diff --git a/solr/core/src/java/org/apache/solr/search/stats/CollectionStats.java b/solr/core/src/java/org/apache/solr/search/stats/CollectionStats.java
index e57f768cfdc..1ef75397e29 100644
--- a/solr/core/src/java/org/apache/solr/search/stats/CollectionStats.java
+++ b/solr/core/src/java/org/apache/solr/search/stats/CollectionStats.java
@@ -50,27 +50,11 @@ public class CollectionStats {
this.sumDocFreq = stats.sumDocFreq();
}
- /*
- * If any stats being added uses -1 then reset the total stats to -1
- * as that parameter becomes unknowable.
- */
public void add(CollectionStats stats) {
this.maxDoc += stats.maxDoc;
- if (this.docCount < 0 || stats.docCount < 0) {
- this.docCount = -1;
- } else {
- this.docCount += stats.docCount;
- }
- if (this.sumTotalTermFreq < 0 || stats.sumTotalTermFreq < 0) {
- this.sumTotalTermFreq = -1;
- } else {
- this.sumTotalTermFreq += stats.sumTotalTermFreq;
- }
- if (this.sumDocFreq < 0 || stats.sumDocFreq < 0) {
- this.sumDocFreq = -1;
- } else {
- this.sumDocFreq += stats.sumDocFreq;
- }
+ this.docCount += stats.docCount;
+ this.sumTotalTermFreq += stats.sumTotalTermFreq;
+ this.sumDocFreq += stats.sumDocFreq;
}
public CollectionStatistics toCollectionStatistics() {
diff --git a/solr/core/src/java/org/apache/solr/search/stats/TermStats.java b/solr/core/src/java/org/apache/solr/search/stats/TermStats.java
index 62b311e6756..9977b285d56 100644
--- a/solr/core/src/java/org/apache/solr/search/stats/TermStats.java
+++ b/solr/core/src/java/org/apache/solr/search/stats/TermStats.java
@@ -55,20 +55,9 @@ public class TermStats {
this.totalTermFreq = stats.totalTermFreq();
}
- /*
- * If any of the stats is -1 then reset total stats to -1.
- */
public void add(TermStats stats) {
- if (this.docFreq < 0 || stats.docFreq < 0) {
- this.docFreq = -1;
- } else {
- this.docFreq += stats.docFreq;
- }
- if (this.totalTermFreq < 0 || stats.totalTermFreq < 0) {
- this.totalTermFreq = -1;
- } else {
- this.totalTermFreq += stats.totalTermFreq;
- }
+ this.docFreq += stats.docFreq;
+ this.totalTermFreq += stats.totalTermFreq;
}
public TermStatistics toTermStatistics() {
diff --git a/solr/core/src/test/org/apache/solr/legacy/TestLegacyTerms.java b/solr/core/src/test/org/apache/solr/legacy/TestLegacyTerms.java
index d91ba88b35d..69d135c23cd 100644
--- a/solr/core/src/test/org/apache/solr/legacy/TestLegacyTerms.java
+++ b/solr/core/src/test/org/apache/solr/legacy/TestLegacyTerms.java
@@ -153,9 +153,9 @@ public class TestLegacyTerms extends LuceneTestCase {
private static Terms EMPTY_TERMS = new Terms() {
public TermsEnum iterator() { return TermsEnum.EMPTY; }
public long size() { return -1; }
- public long getSumTotalTermFreq() { return -1; }
- public long getSumDocFreq() { return -1; }
- public int getDocCount() { return -1; }
+ public long getSumTotalTermFreq() { return 0; }
+ public long getSumDocFreq() { return 0; }
+ public int getDocCount() { return 0; }
public boolean hasFreqs() { return false; }
public boolean hasOffsets() { return false; }
public boolean hasPositions() { return false; }