This is an automated email from the ASF dual-hosted git repository.
airborne12 pushed a commit to branch clucene
in repository https://gitbox.apache.org/repos/asf/doris-thirdparty.git
The following commit(s) were added to refs/heads/clucene by this push:
new 55d614d81f4 [opt](inverted index) Store norms only for the documents
that hold a field (#444)
55d614d81f4 is described below
commit 55d614d81f47dedbe8271967d249868a1dcd261e
Author: Jack <[email protected]>
AuthorDate: Mon Nov 30 20:57:59 2026 +0800
[opt](inverted index) Store norms only for the documents that hold a field
(#444)
A field with FlagBits::SPARSE_NORMS keeps its BM25 norms in a .nrs file that
lists only the documents that hold the field (a roaring bitmap plus their
norm
bytes) instead of one byte for every document in .nrm. A document outside
the
bitmap reads the default norm, the byte .nrm stores for it, so every decoded
norm, the total term count and the block-max data are unchanged.
- SDocumentsWriter: a sparse BufferedNorms skips the fill for absent
documents;
the block-max data reads a dense view rebuilt at flush.
- SegmentReader: decodes .nrs into the same dense norms array.
- .fnm: the field is persisted with OMIT_NORMS set plus the flag (kV3+), so
a
reader without this change sees a field without norms instead of
misreading
.nrs. A field without norms never persists the flag.
- indexCompaction: sources may mix layouts; the merge writes dense norms.
- TestSparseNorms: dense and sparse writes decode to the same norms, token
count and postings files; the sparse .fnm carries OMIT_NORMS; compaction
of
mixed sources equals compaction of dense ones.
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
src/core/CLucene/index/FieldConfig.h | 5 +
src/core/CLucene/index/FieldInfos.cpp | 15 +-
src/core/CLucene/index/IndexWriter.cpp | 11 +-
src/core/CLucene/index/SDocumentWriter.cpp | 130 ++++++++++---
src/core/CLucene/index/SDocumentWriter.h | 18 +-
src/core/CLucene/index/SegmentReader.cpp | 49 ++++-
src/core/CLucene/index/SparseNorms.cpp | 96 ++++++++++
src/core/CLucene/index/_FieldInfos.h | 8 +
src/core/CLucene/index/_SegmentHeader.h | 2 +
src/core/CLucene/index/_SparseNorms.h | 51 ++++++
src/core/CMakeLists.txt | 1 +
src/test/CMakeLists.txt | 1 +
src/test/index/TestSparseNorms.cpp | 281 +++++++++++++++++++++++++++++
src/test/test.h | 1 +
src/test/tests.cpp | 1 +
15 files changed, 633 insertions(+), 37 deletions(-)
diff --git a/src/core/CLucene/index/FieldConfig.h
b/src/core/CLucene/index/FieldConfig.h
index 41c4d5ebf2c..73296072bae 100644
--- a/src/core/CLucene/index/FieldConfig.h
+++ b/src/core/CLucene/index/FieldConfig.h
@@ -4,6 +4,11 @@
enum class FlagBits : uint32_t {
DICT_COMPRESS = 1 << 0, // 00000000 00000000 00000000 00000001
+ // Norms are kept only for the documents that hold the field, in a .nrs
file. The field
+ // is persisted with OMIT_NORMS set, so a reader that does not know this
flag sees a
+ // field without norms instead of misreading the .nrs layout as dense .nrm
norms.
+ // Only persisted by IndexVersion::kV3 and later, which store the flags.
+ SPARSE_NORMS = 1 << 1, // 00000000 00000000 00000000 00000010
};
static inline bool isFlagSet(uint32_t flags, FlagBits flag) {
diff --git a/src/core/CLucene/index/FieldInfos.cpp
b/src/core/CLucene/index/FieldInfos.cpp
index 205ebb17be7..04967789f8a 100644
--- a/src/core/CLucene/index/FieldInfos.cpp
+++ b/src/core/CLucene/index/FieldInfos.cpp
@@ -255,7 +255,8 @@ void FieldInfos::write(IndexOutput* output) const{
if (fi->storeTermVector) bits |= STORE_TERMVECTOR;
if (fi->storePositionWithTermVector) bits |=
STORE_POSITIONS_WITH_TERMVECTOR;
if (fi->storeOffsetWithTermVector) bits |=
STORE_OFFSET_WITH_TERMVECTOR;
- if (fi->omitNorms) bits |= OMIT_NORMS;
+ // Sparse norms are persisted as omitted, see
FlagBits::SPARSE_NORMS.
+ if (fi->omitNorms || fi->hasSparseNorms()) bits |= OMIT_NORMS;
if (fi->storePayloads) bits |= STORE_PAYLOADS;
if (fi->hasProx) bits |= TERM_FREQ_AND_POSITIONS;
@@ -270,7 +271,13 @@ void FieldInfos::write(IndexOutput* output) const{
output->writeVInt(static_cast<int32_t>(fi->getIndexVersion()));
}
if (fi->getIndexVersion() >= IndexVersion::kV3) {
- output->writeVInt(fi->getFlags());
+ // Keep SPARSE_NORMS only for a field that writes .nrs:
read() takes the flag as
+ // proof that the norms exist, so a field without norms
must not carry it.
+ uint32_t flags = fi->getFlags();
+ if (!fi->hasSparseNorms()) {
+ flags &=
~static_cast<uint32_t>(FlagBits::SPARSE_NORMS);
+ }
+ output->writeVInt(flags);
}
}
}
@@ -298,6 +305,10 @@ void FieldInfos::read(IndexInput* input) {
fi->setIndexVersion(indexVersion);
if (indexVersion >= IndexVersion::kV3) {
fi->setFlags(input->readVInt());
+ // The norms exist, in .nrs; OMIT_NORMS
only hides them from older readers.
+ if (fi->isIndexed &&
isFlagSet(fi->getFlags(), FlagBits::SPARSE_NORMS)) {
+ fi->omitNorms = false;
+ }
}
}
_CLDELETE_CARRAY(name);
diff --git a/src/core/CLucene/index/IndexWriter.cpp
b/src/core/CLucene/index/IndexWriter.cpp
index 1d7210db619..bc38b49e0e4 100644
--- a/src/core/CLucene/index/IndexWriter.cpp
+++ b/src/core/CLucene/index/IndexWriter.cpp
@@ -1334,7 +1334,10 @@ void
IndexWriter::indexCompactionImpl(std::vector<lucene::store::Directory*>& sr
IndexReader* reader = readers[0];
hasProx = reader->getFieldInfos()->hasProx();
indexVersion = reader->getFieldInfos()->getIndexVersion();
- flags = reader->getFieldInfos()->getFlags();
+ // Sources may store their norms dense or sparse; the merge
reads both as
+ // dense and writes dense norms, so the norms layout is not
compared.
+ const uint32_t layoutFlags =
static_cast<uint32_t>(FlagBits::SPARSE_NORMS);
+ flags = reader->getFieldInfos()->getFlags() & ~layoutFlags;
for (int32_t i = 1; i < readers.size(); i++) {
if (hasProx != readers[i]->getFieldInfos()->hasProx()) {
_CLTHROWA(CL_ERR_IllegalArgument, "src_dirs hasProx
inconformity");
@@ -1342,7 +1345,7 @@ void
IndexWriter::indexCompactionImpl(std::vector<lucene::store::Directory*>& sr
if (indexVersion !=
readers[i]->getFieldInfos()->getIndexVersion()) {
_CLTHROWA(CL_ERR_IllegalArgument, "src_dirs
indexVersion inconformity");
}
- if (flags != readers[i]->getFieldInfos()->getFlags()) {
+ if (flags != (readers[i]->getFieldInfos()->getFlags() &
~layoutFlags)) {
_CLTHROWA(CL_ERR_IllegalArgument, "src_dirs flags
inconformity");
}
}
@@ -1669,7 +1672,9 @@ void IndexWriter::mergeFields(bool hasProx, IndexVersion
indexVersion) {
fieldInfos->add(fi->name, fi->isIndexed, fi->storeTermVector,
fi->storePositionWithTermVector,
fi->storeOffsetWithTermVector,
!reader->hasNorms(fi->name), hasProx,
fi->storePayloads,
- fi->indexVersion_, fi->flags_);
+ fi->indexVersion_,
+ // mergeNorms() writes dense .nrm norms, even from
sparse sources.
+ fi->flags_ &
~static_cast<uint32_t>(FlagBits::SPARSE_NORMS));
}
}
diff --git a/src/core/CLucene/index/SDocumentWriter.cpp
b/src/core/CLucene/index/SDocumentWriter.cpp
index b4ded79b029..3987710cf89 100644
--- a/src/core/CLucene/index/SDocumentWriter.cpp
+++ b/src/core/CLucene/index/SDocumentWriter.cpp
@@ -19,6 +19,7 @@
#include "_SkipListWriter.h"
#include "_IndexFileNames.h"
#include "_SegmentMerger.h"
+#include "_SparseNorms.h"
#include <algorithm>
#include <vector>
@@ -210,7 +211,7 @@ void SDocumentsWriter<T>::ThreadState::init(Document *doc,
int32_t doc_id) {
}
if (_parent->norms[fi->number] == NULL)
- _parent->norms.values[fi->number] = _CLNEW BufferedNorms();
+ _parent->norms.values[fi->number] = _CLNEW
BufferedNorms(fi->hasSparseNorms());
_parent->hasNorms = true;
}
@@ -988,36 +989,83 @@ void SDocumentsWriter<T>::getPostings(ValueArray<Posting
*> &postings) {
template<typename T>
-void SDocumentsWriter<T>::writeNorms(const std::string &segmentName, int32_t
totalNumDoc) {
- IndexOutput *normsOut = directory->createOutput((segmentName + "." +
IndexFileNames::NORMS_EXTENSION).c_str());
+void SDocumentsWriter<T>::writeNorms(const std::string &segmentName, int32_t
totalNumDoc,
+ std::vector<std::string> &flushedFiles) {
+ const int32_t numField = fieldInfos->size();
+ bool hasDenseNorms = false;
+ bool hasSparseNorms = false;
+ for (int32_t fieldIdx = 0; fieldIdx < numField; fieldIdx++) {
+ FieldInfo *fi = fieldInfos->fieldInfo(fieldIdx);
+ if (fi->isIndexed && !fi->omitNorms) {
+ if (fi->hasSparseNorms()) {
+ hasSparseNorms = true;
+ } else {
+ hasDenseNorms = true;
+ }
+ }
+ }
- try {
- normsOut->writeBytes(SegmentMerger::NORMS_HEADER,
SegmentMerger::NORMS_HEADER_length);
+ if (hasDenseNorms) {
+ IndexOutput *normsOut = directory->createOutput((segmentName + "." +
IndexFileNames::NORMS_EXTENSION).c_str());
+
+ try {
+ normsOut->writeBytes(SegmentMerger::NORMS_HEADER,
SegmentMerger::NORMS_HEADER_length);
+
+ for (int32_t fieldIdx = 0; fieldIdx < numField; fieldIdx++) {
+ FieldInfo *fi = fieldInfos->fieldInfo(fieldIdx);
+ if (fi->isIndexed && !fi->omitNorms && !fi->hasSparseNorms()) {
+ BufferedNorms *n = norms[fieldIdx];
+ int64_t v;
+ if (n == nullptr) {
+ normsOut->writeLong(0);
+ v = 0;
+ } else {
+ normsOut->writeLong(n->total_term_count_);
+ v = n->norms_buffer.size();
+ normsOut->writeBytes(n->norms_buffer.data(),
n->norms_buffer.size());
+ n->reset();
+ }
+ if (v < totalNumDoc)
+ fillBytes(normsOut, defaultNorm, (int32_t)
(totalNumDoc - v));
+ }
+ }
+ }
+ _CLFINALLY(
+ normsOut->close();
+ _CLDELETE(normsOut);)
+
flushedFiles.push_back(segmentFileName(IndexFileNames::NORMS_EXTENSION));
+ }
+
+ if (hasSparseNorms) {
+ IndexOutput *normsOut = directory->createOutput((segmentName + "." +
SparseNorms::EXTENSION).c_str());
- const int32_t numField = fieldInfos->size();
+ try {
+ SparseNorms::writeHeader(normsOut);
- for (int32_t fieldIdx = 0; fieldIdx < numField; fieldIdx++) {
- FieldInfo *fi = fieldInfos->fieldInfo(fieldIdx);
- if (fi->isIndexed && !fi->omitNorms) {
+ for (int32_t fieldIdx = 0; fieldIdx < numField; fieldIdx++) {
+ FieldInfo *fi = fieldInfos->fieldInfo(fieldIdx);
+ if (!fi->hasSparseNorms()) {
+ continue;
+ }
BufferedNorms *n = norms[fieldIdx];
- int64_t v;
if (n == nullptr) {
- normsOut->writeLong(0);
- v = 0;
- } else {
- normsOut->writeLong(n->total_term_count_);
- v = n->norms_buffer.size();
- normsOut->writeBytes(n->norms_buffer.data(),
n->norms_buffer.size());
- n->reset();
+ roaring::Roaring noDocs;
+ SparseNorms::writeField(normsOut, 0, noDocs, {});
+ continue;
+ }
+ // The buffer took its mode from the same flags when the field
was first seen.
+ if (!n->sparse_) {
+ _CLTHROWA(CL_ERR_IllegalState, "sparse norms field has a
dense norms buffer");
}
- if (v < totalNumDoc)
- fillBytes(normsOut, defaultNorm, (int32_t) (totalNumDoc -
v));
+ SparseNorms::writeField(normsOut, n->total_term_count_,
n->docs_, n->norms_buffer);
+ n->reset();
}
}
+ _CLFINALLY(
+ normsOut->close();
+ _CLDELETE(normsOut);)
+ flushedFiles.push_back(segmentFileName(SparseNorms::EXTENSION));
}
- _CLFINALLY(
- normsOut->close();
- _CLDELETE(normsOut);)
}
template<typename T>
@@ -1113,8 +1161,7 @@ void
SDocumentsWriter<T>::writeSegment(std::vector<std::string> &flushedFiles) {
flushedFiles.push_back(segmentFileName(IndexFileNames::TERMS_INDEX_EXTENSION));
if (hasNorms) {
- writeNorms(segmentName, numDocsInRAM);
-
flushedFiles.push_back(segmentFileName(IndexFileNames::NORMS_EXTENSION));
+ writeNorms(segmentName, numDocsInRAM, flushedFiles);
}
resetPostingsData();
@@ -1251,7 +1298,7 @@ void
SDocumentsWriter<T>::appendPostings(ArrayBase<typename ThreadState::FieldDa
int32_t maxBlockNorm = -1;
if (enableBlockMaxWand) {
- const auto& nb = blockMaxNorms->norms_buffer;
+ const auto& nb = blockMaxNorms->normsByDoc();
auto* bm25 = blockMaxNorms->bm25_similarity_.get();
float maxTFFactor = -1.0F;
@@ -1489,7 +1536,7 @@ int32_t
SDocumentsWriter<T>::ThreadState::FieldData::compareTo(NamedObject *o) {
}
template<typename T>
-SDocumentsWriter<T>::BufferedNorms::BufferedNorms() {
+SDocumentsWriter<T>::BufferedNorms::BufferedNorms(bool sparse) :
sparse_(sparse) {
this->upto = 0;
}
template<typename T>
@@ -1501,6 +1548,10 @@ template<typename T>
void SDocumentsWriter<T>::BufferedNorms::add(int32_t norm) {
total_term_count_ += norm;
uint8_t b = search::Similarity::encodeNorm(norm);
+ if (sparse_) {
+ // fill() has moved upto to the document being added.
+ docs_.add(static_cast<uint32_t>(upto));
+ }
norms_buffer.push_back(b);
upto++;
}
@@ -1510,6 +1561,27 @@ void SDocumentsWriter<T>::BufferedNorms::reset() {
upto = 0;
total_term_count_ = 0;
norms_buffer.clear();
+ if (sparse_) {
+ docs_ = roaring::Roaring();
+ std::vector<uint8_t>().swap(norms_by_doc_);
+ }
+}
+
+template<typename T>
+const std::vector<uint8_t>& SDocumentsWriter<T>::BufferedNorms::normsByDoc() {
+ if (!sparse_) {
+ return norms_buffer;
+ }
+ // Rebuild the dense view the norms would have had, e.g. docs_ {1, 4} with
norms {3, 7}
+ // and upto 5 become [d, 3, d, d, 7] where d is the default norm.
+ if (norms_by_doc_.size() != static_cast<size_t>(upto)) {
+ norms_by_doc_.assign(upto, defaultNorm);
+ size_t i = 0;
+ for (const uint32_t doc : docs_) {
+ norms_by_doc_[doc] = norms_buffer[i++];
+ }
+ }
+ return norms_by_doc_;
}
template<typename T>
void SDocumentsWriter<T>::BufferedNorms::fill(int32_t docID) {
@@ -1519,7 +1591,11 @@ void SDocumentsWriter<T>::BufferedNorms::fill(int32_t
docID) {
// varying different fields, because we are not
// storing the norms sparsely (see LUCENE-830)
if (upto < docID) {
- norms_buffer.insert(norms_buffer.end(), docID - upto, defaultNorm);
+ // A sparse buffer records no norm for the skipped documents: they
decode to the
+ // default norm, the byte a dense buffer would have filled in.
+ if (!sparse_) {
+ norms_buffer.insert(norms_buffer.end(), docID - upto, defaultNorm);
+ }
upto = docID;
}
}
diff --git a/src/core/CLucene/index/SDocumentWriter.h
b/src/core/CLucene/index/SDocumentWriter.h
index 5d475a19df7..06e064413b2 100644
--- a/src/core/CLucene/index/SDocumentWriter.h
+++ b/src/core/CLucene/index/SDocumentWriter.h
@@ -16,6 +16,8 @@
#include "_TermInfosWriter.h"
#include "BlockMaxBM25Similarity.h"
+#include <roaring/roaring.hh>
+
CL_CLASS_DEF(analysis, Analyzer)
CL_CLASS_DEF(analysis, Token)
CL_CLASS_DEF(analysis, TokenStream)
@@ -84,13 +86,16 @@ public:
* to a partial segment. */
class BufferedNorms {
public:
- BufferedNorms();
+ explicit BufferedNorms(bool sparse = false);
~BufferedNorms() = default;
void add(float_t norm);
void add(int32_t norm);
void reset();
void fill(int32_t docID);
+ // The norm of every document before upto, by docID. A sparse buffer
builds this
+ // view on first use and keeps it until reset().
+ const std::vector<uint8_t>& normsByDoc();
void createBM25Similarity(float avgdl) {
bm25_similarity_ =
std::make_unique<lucene::index::BlockMaxBM25Similarity>(avgdl);
@@ -98,8 +103,14 @@ public:
int32_t upto {};
int64_t total_term_count_ = 0;
+ // Dense: one norm per document before upto. Sparse: the norms of the
documents in
+ // docs_, in document order.
std::vector<uint8_t> norms_buffer;
std::unique_ptr<lucene::index::BlockMaxBM25Similarity>
bm25_similarity_;
+ // Sparse buffers keep only the documents that hold the field
(FlagBits::SPARSE_NORMS).
+ const bool sparse_;
+ roaring::Roaring docs_;
+ std::vector<uint8_t> norms_by_doc_;
};
template<typename T2>
class BlockPool {
@@ -725,7 +736,10 @@ public:
void writeSegment(std::vector<std::string> &flushedFiles);
void recyclePostings(CL_NS(util)::ValueArray<Posting *> &postings, int32_t
numPostings);
- void writeNorms(const std::string &segmentName, int32_t totalNumDoc);
+ // Writes the dense norms to .nrm and the sparse ones to .nrs, adding each
file it
+ // writes to flushedFiles.
+ void writeNorms(const std::string &segmentName, int32_t totalNumDoc,
+ std::vector<std::string> &flushedFiles);
int32_t compareText(const T *text1, const T *text2);
void resetPostingsData() {
// All ThreadStates should be idle when we are called
diff --git a/src/core/CLucene/index/SegmentReader.cpp
b/src/core/CLucene/index/SegmentReader.cpp
index beb357fc3d5..d5226e8bcd0 100644
--- a/src/core/CLucene/index/SegmentReader.cpp
+++ b/src/core/CLucene/index/SegmentReader.cpp
@@ -5,6 +5,7 @@
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include <assert.h>
+#include <memory>
#include "CLucene/_ApiHeader.h"
#include "CLucene/search/Similarity.h"
@@ -18,6 +19,7 @@
#include "_MultiSegmentReader.h"
#include "_SegmentHeader.h"
#include "_SegmentMerger.h"
+#include "_SparseNorms.h"
#include "_TermInfosReader.h"
CL_NS_USE(util)
@@ -702,7 +704,11 @@ void SegmentReader::norms(const TCHAR *field, uint8_t
*bytes) {
normStream = norm->in;
}
normStream->seek(norm->normSeek);
- normStream->readBytes(bytes, maxDoc());
+ if (norm->sparse) {
+ SparseNorms::readNorms(normStream, maxDoc(), bytes);
+ } else {
+ normStream->readBytes(bytes, maxDoc());
+ }
}
}
uint8_t* SegmentReader::norms(const TCHAR *field) const {
@@ -749,7 +755,11 @@ void SegmentReader::norms(const TCHAR *field, uint8_t*
bytes) const {
normStream = norm->in;
}
normStream->seek(norm->normSeek);
- normStream->readBytes(bytes, maxDoc());
+ if (norm->sparse) {
+ SparseNorms::readNorms(normStream, maxDoc(), bytes);
+ } else {
+ normStream->readBytes(bytes, maxDoc());
+ }
}
}
@@ -840,6 +850,11 @@ void SegmentReader::doSetNorm(int32_t doc, const TCHAR
*field, uint8_t value) {
Norm *norm = _norms.get(field);
if (norm == NULL)// not an indexed field
return;
+ // A rewrite would store dense norms in a separate norms file, which
openNorms() does not
+ // read for a field whose norms are in .nrs.
+ if (norm->sparse) {
+ _CLTHROWA(CL_ERR_UnsupportedOperation, "setNorm is not supported for
sparse norms");
+ }
norm->dirty = true;// mark it dirty
normsDirty = true;
@@ -870,8 +885,33 @@ void SegmentReader::openNorms(Directory *cfsDir, int32_t
readBufferSize) {
// a corresponding norm file ready to be read
int64_t nextNormSeek = SegmentMerger::NORMS_HEADER_length;//skip header
(header unused for now)
int32_t _maxDoc = maxDoc();
+ // Walks the .nrs entries in field order. Every entry is stepped over,
also for a reused
+ // norm, so that the next field starts at its own entry.
+ std::unique_ptr<IndexInput> sparseNormEntries;
+ int64_t nextSparseNormEntry = 0;
+ const std::string sparseNormFile = segment + "." + SparseNorms::EXTENSION;
for (size_t i = 0; i < _fieldInfos->size(); i++) {
FieldInfo *fi = _fieldInfos->fieldInfo(i);
+ if (fi->hasSparseNorms()) {
+ if (sparseNormEntries == nullptr) {
+
sparseNormEntries.reset(cfsDir->openInput(sparseNormFile.c_str(),
readBufferSize));
+ nextSparseNormEntry =
SparseNorms::readHeader(sparseNormEntries.get());
+ }
+ int64_t total_term_count = 0;
+ int64_t normSeek = 0;
+ SparseNorms::readEntry(sparseNormEntries.get(),
nextSparseNormEntry, &total_term_count,
+ &normSeek, &nextSparseNormEntry);
+ if (_norms.find(fi->name) != _norms.end()) {
+ continue;
+ }
+ sum_total_term_freq[*fi->name] = total_term_count;
+ // The norm owns its own stream, as a norm outside the single .nrm
stream does.
+ auto *norm = _CLNEW Norm(cfsDir->openInput(sparseNormFile.c_str(),
readBufferSize),
+ false, fi->number, normSeek, this,
segment.c_str());
+ norm->sparse = true;
+ _norms[fi->name] = norm;
+ continue;
+ }
if (_norms.find(fi->name) != _norms.end()) {
// in case this SegmentReader is being re-opened, we might be able
to
// reuse some norm instances and skip loading them here
@@ -914,6 +954,9 @@ void SegmentReader::openNorms(Directory *cfsDir, int32_t
readBufferSize) {
nextNormSeek += (_maxDoc + sizeof(int64_t));// increment also if
some norms are separate
}
}
+ if (sparseNormEntries != nullptr) {
+ sparseNormEntries->close();
+ }
}
@@ -1107,7 +1150,7 @@ SegmentReader *SegmentReader::reopenSegment(SegmentInfo
*si) {
if (clone->singleNormStream == NULL) {
for (size_t i = 0; i < _fieldInfos->size(); i++) {
FieldInfo *fi = _fieldInfos->fieldInfo(i);
- if (fi->isIndexed && !fi->omitNorms) {
+ if (fi->isIndexed && !fi->omitNorms && !fi->hasSparseNorms()) {
Directory *d = si->getUseCompoundFile() ? cfsReader :
directory();
string fileName = si->getNormFileName(fi->number);
if (si->hasSeparateNorms(fi->number)) {
diff --git a/src/core/CLucene/index/SparseNorms.cpp
b/src/core/CLucene/index/SparseNorms.cpp
new file mode 100644
index 00000000000..dda1fc6b07b
--- /dev/null
+++ b/src/core/CLucene/index/SparseNorms.cpp
@@ -0,0 +1,96 @@
+#include <cstring>
+#include <exception>
+#include <string>
+
+#include "CLucene/_ApiHeader.h"
+#include "CLucene/search/Similarity.h"
+#include "_SparseNorms.h"
+
+CL_NS_USE(store)
+CL_NS_DEF(index)
+
+namespace {
+constexpr uint8_t HEADER[] = {'N', 'R', 'S', 1};
+constexpr int32_t HEADER_LENGTH = sizeof(HEADER);
+} // namespace
+
+const char* SparseNorms::EXTENSION = "nrs";
+
+uint8_t SparseNorms::defaultNorm() {
+ // SDocumentsWriter fills a dense .nrm file with this byte for documents
without the field.
+ return CL_NS(search)::Similarity::encodeNorm(1);
+}
+
+void SparseNorms::writeHeader(IndexOutput* out) {
+ out->writeBytes(HEADER, HEADER_LENGTH);
+}
+
+void SparseNorms::writeField(IndexOutput* out, int64_t totalTermCount,
roaring::Roaring& docs,
+ const std::vector<uint8_t>& norms) {
+ if (docs.cardinality() != norms.size()) {
+ _CLTHROWA(CL_ERR_IllegalState, "sparse norms: documents and norms
differ in number");
+ }
+ docs.runOptimize();
+ std::vector<char> bitmap(docs.getSizeInBytes(true));
+ docs.write(bitmap.data(), true);
+
+ out->writeLong(totalTermCount);
+ out->writeVInt(static_cast<int32_t>(bitmap.size()));
+ out->writeBytes(reinterpret_cast<const uint8_t*>(bitmap.data()),
+ static_cast<int32_t>(bitmap.size()));
+ out->writeVInt(static_cast<int32_t>(norms.size()));
+ if (!norms.empty()) {
+ out->writeBytes(norms.data(), static_cast<int32_t>(norms.size()));
+ }
+}
+
+int64_t SparseNorms::readHeader(IndexInput* in) {
+ uint8_t header[HEADER_LENGTH];
+ in->readBytes(header, HEADER_LENGTH);
+ if (memcmp(header, HEADER, HEADER_LENGTH) != 0) {
+ _CLTHROWA(CL_ERR_CorruptIndex, "sparse norms: unknown header or
version");
+ }
+ return in->getFilePointer();
+}
+
+void SparseNorms::readEntry(IndexInput* in, int64_t entryPosition, int64_t*
totalTermCount,
+ int64_t* normsPosition, int64_t*
nextEntryPosition) {
+ in->seek(entryPosition);
+ *totalTermCount = in->readLong();
+ *normsPosition = in->getFilePointer();
+ const int32_t bitmapSize = in->readVInt();
+ // lands on the norm count, which follows the bitmap
+ in->seek(in->getFilePointer() + bitmapSize);
+ const int32_t count = in->readVInt();
+ *nextEntryPosition = in->getFilePointer() + count;
+}
+
+void SparseNorms::readNorms(IndexInput* in, int32_t maxDoc, uint8_t* bytes) {
+ const int32_t bitmapSize = in->readVInt();
+ std::vector<char> buffer(bitmapSize);
+ in->readBytes(reinterpret_cast<uint8_t*>(buffer.data()), bitmapSize);
+ roaring::Roaring docs;
+ try {
+ docs = roaring::Roaring::readSafe(buffer.data(), buffer.size());
+ } catch (const std::exception& e) {
+ _CLTHROWA(CL_ERR_CorruptIndex,
+ (std::string("sparse norms: bad document bitmap: ") +
e.what()).c_str());
+ }
+ const int32_t count = in->readVInt();
+ if (static_cast<uint64_t>(count) != docs.cardinality() ||
+ (count > 0 && docs.maximum() >= static_cast<uint32_t>(maxDoc))) {
+ _CLTHROWA(CL_ERR_CorruptIndex, "sparse norms: bitmap does not match
the norms");
+ }
+ std::vector<uint8_t> norms(count);
+ if (count > 0) {
+ in->readBytes(norms.data(), count);
+ }
+
+ memset(bytes, defaultNorm(), maxDoc);
+ size_t i = 0;
+ for (const uint32_t doc : docs) {
+ bytes[doc] = norms[i++];
+ }
+}
+
+CL_NS_END
diff --git a/src/core/CLucene/index/_FieldInfos.h
b/src/core/CLucene/index/_FieldInfos.h
index cea935ab8c5..fba586cd19d 100644
--- a/src/core/CLucene/index/_FieldInfos.h
+++ b/src/core/CLucene/index/_FieldInfos.h
@@ -8,6 +8,7 @@
#define _lucene_index_FieldInfos_
#include "CLucene/store/Directory.h"
+#include "CLucene/index/FieldConfig.h"
#include "CLucene/index/IndexVersion.h"
@@ -80,6 +81,13 @@ public:
void setFlags(uint32_t flags) { flags_ = flags; }
uint32_t getFlags() { return flags_; }
+
+ // Whether the field's norms live in the sparse .nrs file. Requires kV3
or later, the
+ // versions that persist the flags; an earlier field could not keep the
flag on reopen.
+ bool hasSparseNorms() const {
+ return isIndexed && !omitNorms && indexVersion_ >=
IndexVersion::kV3 &&
+ isFlagSet(flags_, FlagBits::SPARSE_NORMS);
+ }
};
/** Access to the Field Info file that describes document fields and whether or
diff --git a/src/core/CLucene/index/_SegmentHeader.h
b/src/core/CLucene/index/_SegmentHeader.h
index 4223d6c962b..c34236fb041 100644
--- a/src/core/CLucene/index/_SegmentHeader.h
+++ b/src/core/CLucene/index/_SegmentHeader.h
@@ -381,6 +381,8 @@ class SegmentReader: public DirectoryIndexReader {
volatile int32_t refCount;
bool useSingleNormStream;
bool rollbackDirty;
+ // The norms are a field entry of the .nrs file, read through `in` from
normSeek.
+ bool sparse = false;
/** Closes the underlying IndexInput for this norm.
diff --git a/src/core/CLucene/index/_SparseNorms.h
b/src/core/CLucene/index/_SparseNorms.h
new file mode 100644
index 00000000000..5cf76d77d9b
--- /dev/null
+++ b/src/core/CLucene/index/_SparseNorms.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include <cstdint>
+#include <roaring/roaring.hh>
+#include <vector>
+
+#include "CLucene/_ApiHeader.h"
+#include "CLucene/store/IndexInput.h"
+#include "CLucene/store/IndexOutput.h"
+
+CL_NS_DEF(index)
+
+// The sparse norms file (.nrs) of a segment. A dense .nrm file stores one
norm byte for every
+// document of the segment; this file stores the norm only for the documents
that hold the
+// field, so a field that most documents lack costs bytes in proportion to its
values.
+//
+// Layout: the 4-byte header, then one entry for every field with sparse
norms, in field
+// number order:
+// int64 the field's total term count
+// vint the size of a portable roaring bitmap, then the bitmap: the
documents with a norm
+// vint the number of norms, which is the cardinality of the bitmap, then
the norm bytes
+// in document order
+//
+// A document outside the bitmap reads the default norm, the byte a dense .nrm
file stores for
+// a document without the field. For example, norms {doc 1: 3, doc 4: 7} in a
6-document
+// segment decode to [1, 3, 1, 1, 7, 1], the same bytes the dense file holds.
+class SparseNorms {
+public:
+ static const char* EXTENSION;
+
+ // The norm of a document that does not hold the field.
+ static uint8_t defaultNorm();
+
+ static void writeHeader(CL_NS(store)::IndexOutput* out);
+ // Writes one field. runOptimize() is applied to `docs` before it is
serialized.
+ static void writeField(CL_NS(store)::IndexOutput* out, int64_t
totalTermCount,
+ roaring::Roaring& docs, const std::vector<uint8_t>&
norms);
+
+ // Checks the header at the current position. Returns the position of the
first entry.
+ static int64_t readHeader(CL_NS(store)::IndexInput* in);
+ // Reads the entry at `entryPosition`: the field's total term count, the
position readNorms()
+ // starts from, and the position of the next entry. It never seeks to the
end of the file,
+ // which a file input may refuse, as the next position of the last entry
is.
+ static void readEntry(CL_NS(store)::IndexInput* in, int64_t entryPosition,
+ int64_t* totalTermCount, int64_t* normsPosition,
+ int64_t* nextEntryPosition);
+ // Decodes the field's norms at the current position into `maxDoc` bytes.
+ static void readNorms(CL_NS(store)::IndexInput* in, int32_t maxDoc,
uint8_t* bytes);
+};
+
+CL_NS_END
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index e571e5470f3..67c04859fbe 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -104,6 +104,7 @@ SET(clucene_core_Files
./CLucene/index/DocumentsWriter.cpp
./CLucene/index/SDocumentWriter.cpp
./CLucene/index/SDocumentWriter.h
+ ./CLucene/index/SparseNorms.cpp
./CLucene/index/BlockMaxBM25Similarity.cpp
./CLucene/index/DocumentsWriterThreadState.cpp
./CLucene/index/SegmentTermVector.cpp
diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt
index 7cb4e244bac..d2b33994e1d 100644
--- a/src/test/CMakeLists.txt
+++ b/src/test/CMakeLists.txt
@@ -90,6 +90,7 @@ SET(test_files ./tests.cpp
./index/TestIndexCompaction.cpp
./index/TestIndexCompress.cpp
./index/TestIndexCompressV3.cpp
+ ./index/TestSparseNorms.cpp
./index/TestIndexModifier.cpp
./index/TestIndexWriter.cpp
./index/TestIndexModifier.cpp
diff --git a/src/test/index/TestSparseNorms.cpp
b/src/test/index/TestSparseNorms.cpp
new file mode 100644
index 00000000000..3e1b9019e74
--- /dev/null
+++ b/src/test/index/TestSparseNorms.cpp
@@ -0,0 +1,281 @@
+#include <algorithm>
+#include <cstdint>
+#include <map>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "CLucene.h"
+#include "CLucene/index/FieldConfig.h"
+#include "CLucene/index/IndexVersion.h"
+#include "CLucene/index/IndexWriter.h"
+#include "CLucene/store/IndexInput.h"
+#include "store/MockRAMDirectory.h"
+#include "test.h"
+
+CL_NS_USE(index)
+CL_NS_USE(store)
+
+namespace {
+
+// FieldInfos::OMIT_NORMS in the .fnm field bits.
+constexpr uint8_t kOmitNormsBit = 0x10;
+
+// Documents of the test, by row: std::nullopt is a NULL row, which Doris adds
as a document
+// without the field. Rows 0, 7, 14, ... are NULL, rows 11, 22, ... hold "",
and every other row
+// holds "common" and up to 39 more words, so the norms include lengths above
23, which the norm
+// byte rounds, and the postings of "common" span many skip blocks.
+std::vector<std::optional<std::string>> sparseNormsDocuments(int32_t rows) {
+ const char* words[] = {"alpha", "beta", "gamma", "delta"};
+ std::vector<std::optional<std::string>> documents;
+ for (int32_t row = 0; row < rows; ++row) {
+ if (row % 7 == 0) {
+ documents.emplace_back(std::nullopt);
+ continue;
+ }
+ std::string value;
+ if (row % 11 != 0) {
+ value = "common";
+ for (int32_t i = 0; i < row % 40; ++i) {
+ value += ' ';
+ value += words[(row + i) % 4];
+ }
+ }
+ documents.emplace_back(value);
+ }
+ return documents;
+}
+
+void writeSparseNormsIndex(Directory& dir, const
std::vector<std::optional<std::string>>& documents,
+ bool sparseNorms, int32_t maxBufferedDocs) {
+ lucene::analysis::SimpleAnalyzer<char> analyzer;
+ analyzer.set_stopwords(nullptr);
+ lucene::util::SStringReader<char> reader;
+ lucene::document::Document doc;
+ auto* field = _CLNEW lucene::document::Field(
+ _T("body"),
+ lucene::document::Field::STORE_NO |
lucene::document::Field::INDEX_TOKENIZED);
+ field->setOmitTermFreqAndPositions(false);
+ field->setIndexVersion(IndexVersion::kV4);
+ if (sparseNorms) {
+ field->updateFlag(FlagBits::SPARSE_NORMS);
+ }
+ doc.add(*field);
+ IndexWriter writer(&dir, &analyzer, true);
+ writer.setMaxBufferedDocs(maxBufferedDocs);
+ writer.setRAMBufferSizeMB(512);
+ writer.setMergeFactor(1000000000);
+ writer.setUseCompoundFile(false);
+ for (const auto& value : documents) {
+ if (!value.has_value()) {
+ writer.addNullDocument(&doc);
+ continue;
+ }
+ reader.init(value->data(), value->size(), false);
+ field->setValue(analyzer.tokenStream(field->name(), &reader), true);
+ writer.addDocument(&doc);
+ }
+ writer.close();
+}
+
+std::vector<std::string> listFiles(Directory& dir) {
+ std::vector<std::string> files;
+ dir.list(&files);
+ return files;
+}
+
+bool hasFileEnding(const std::vector<std::string>& files, const std::string&
extension) {
+ return std::any_of(files.begin(), files.end(), [&](const std::string&
file) {
+ return file.size() >= extension.size() &&
+ file.compare(file.size() - extension.size(), extension.size(),
extension) == 0;
+ });
+}
+
+std::string readFile(Directory& dir, const std::string& name) {
+ IndexInput* input = dir.openInput(name.c_str());
+ std::string bytes(input->length(), '\0');
+ input->readBytes(reinterpret_cast<uint8_t*>(&bytes[0]),
static_cast<int32_t>(bytes.size()));
+ input->close();
+ _CLDELETE(input);
+ return bytes;
+}
+
+// The postings files, which carry the block-max data computed from the norms.
+std::map<std::string, std::string> postingsFiles(Directory& dir) {
+ std::map<std::string, std::string> files;
+ for (const auto& file : listFiles(dir)) {
+ for (const char* extension : {".frq", ".prx", ".tis", ".tii"}) {
+ if (hasFileEnding({file}, extension)) {
+ files[file] = readFile(dir, file);
+ }
+ }
+ }
+ return files;
+}
+
+struct NormsView {
+ bool hasNorms = false;
+ std::optional<uint64_t> tokenCount;
+ // through norms(field, bytes) before anything is cached, then through
norms(field)
+ std::vector<uint8_t> copied;
+ std::vector<uint8_t> cached;
+};
+
+NormsView readNorms(Directory& dir) {
+ NormsView view;
+ IndexReader* reader = IndexReader::open(&dir);
+ view.hasNorms = reader->hasNorms(_T("body"));
+ view.tokenCount = reader->sumTotalTermFreq(_T("body"));
+ view.copied.assign(reader->maxDoc(), 0);
+ reader->norms(_T("body"), view.copied.data());
+ const uint8_t* cached = reader->norms(_T("body"));
+ view.cached.assign(cached, cached + reader->maxDoc());
+ reader->close();
+ _CLDELETE(reader);
+ return view;
+}
+
+// The field bits of the single field in each .fnm file: field count, field
name, field bits.
+std::vector<uint8_t> fnmFieldBits(Directory& dir) {
+ std::vector<uint8_t> bits;
+ for (const auto& file : listFiles(dir)) {
+ if (!hasFileEnding({file}, ".fnm")) {
+ continue;
+ }
+ IndexInput* input = dir.openInput(file.c_str());
+ input->readVInt();
+ TCHAR* name = input->readString();
+ _CLDELETE_CARRAY(name);
+ bits.push_back(input->readByte());
+ input->close();
+ _CLDELETE(input);
+ }
+ return bits;
+}
+
+void assertSameNorms(CuTest* tc, const NormsView& dense, const NormsView&
sparse,
+ size_t documents) {
+ CuAssertTrue(tc, dense.hasNorms);
+ CuAssertTrue(tc, sparse.hasNorms);
+ CuAssertTrue(tc, dense.tokenCount.has_value() && *dense.tokenCount > 0);
+ CuAssertTrue(tc, dense.tokenCount == sparse.tokenCount);
+ CuAssertIntEquals(tc, _T("norms of every document"), documents,
dense.copied.size());
+ CuAssertTrue(tc, dense.copied == dense.cached);
+ CuAssertTrue(tc, dense.copied == sparse.copied);
+ CuAssertTrue(tc, dense.cached == sparse.cached);
+}
+
+void TestSparseNormsDecodeToDenseNorms(CuTest* tc) {
+ const auto documents = sparseNormsDocuments(3000);
+ // one segment, then three: 1000 buffered documents flush the norms
buffers twice
+ for (int32_t maxBufferedDocs : {-1, 1000}) {
+ RAMDirectory dense;
+ RAMDirectory sparse;
+ writeSparseNormsIndex(dense, documents, false, maxBufferedDocs);
+ writeSparseNormsIndex(sparse, documents, true, maxBufferedDocs);
+
+ CuAssertTrue(tc, hasFileEnding(listFiles(dense), ".nrm"));
+ CuAssertTrue(tc, !hasFileEnding(listFiles(dense), ".nrs"));
+ CuAssertTrue(tc, hasFileEnding(listFiles(sparse), ".nrs"));
+ CuAssertTrue(tc, !hasFileEnding(listFiles(sparse), ".nrm"));
+
+ const NormsView denseNorms = readNorms(dense);
+ assertSameNorms(tc, denseNorms, readNorms(sparse), documents.size());
+ // equal norms must not be equal by being all defaults: the lengths 1
to 40 encode apart
+ std::vector<uint8_t> distinct = denseNorms.copied;
+ std::sort(distinct.begin(), distinct.end());
+ distinct.erase(std::unique(distinct.begin(), distinct.end()),
distinct.end());
+ CuAssertTrue(tc, distinct.size() > 20);
+
+ const auto densePostings = postingsFiles(dense);
+ CuAssertTrue(tc, !densePostings.empty());
+ CuAssertTrue(tc, densePostings == postingsFiles(sparse));
+
+ dense.close();
+ sparse.close();
+ }
+}
+
+// A reader that does not know FlagBits::SPARSE_NORMS takes omitNorms from the
field bits alone, so
+// the sparse field must carry OMIT_NORMS: that reader then sees no norms
instead of decoding .nrs
+// as dense norms.
+void TestSparseNormsHiddenFromOlderReaders(CuTest* tc) {
+ const auto documents = sparseNormsDocuments(100);
+ RAMDirectory dense;
+ RAMDirectory sparse;
+ writeSparseNormsIndex(dense, documents, false, -1);
+ writeSparseNormsIndex(sparse, documents, true, -1);
+ for (uint8_t bits : fnmFieldBits(dense)) {
+ CuAssertIntEquals(tc, _T("dense norms are not omitted"), 0, bits &
kOmitNormsBit);
+ }
+ const auto sparseBits = fnmFieldBits(sparse);
+ CuAssertTrue(tc, !sparseBits.empty());
+ for (uint8_t bits : sparseBits) {
+ CuAssertIntEquals(tc, _T("sparse norms look omitted"), kOmitNormsBit,
bits & kOmitNormsBit);
+ }
+ dense.close();
+ sparse.close();
+}
+
+std::vector<NormsView> compactTwoSources(Directory& source0, Directory&
source1,
+
std::vector<std::vector<std::string>>* destinationFiles) {
+ MockRAMDirectory destination0;
+ MockRAMDirectory destination1;
+ destination0.setRandomIOExceptionRate(0.0, 0);
+ destination1.setRandomIOExceptionRate(0.0, 0);
+ RAMDirectory scratch;
+ lucene::analysis::SimpleAnalyzer<char> analyzer;
+ IndexWriter writer(&scratch, &analyzer, true);
+ std::vector<Directory*> sources {&source0, &source1};
+ std::vector<Directory*> destinations {&destination0, &destination1};
+ // the 100 documents of each source alternate between the destinations
+ std::vector<std::vector<std::pair<uint32_t, uint32_t>>> mapping(2);
+ for (uint32_t source = 0; source < 2; ++source) {
+ for (uint32_t doc = 0; doc < 100; ++doc) {
+ mapping[source].emplace_back(doc % 2, source * 50 + doc / 2);
+ }
+ }
+ writer.indexCompaction(sources, destinations, mapping, {100, 100});
+ writer.close();
+ std::vector<NormsView> norms;
+ for (auto* destination : destinations) {
+ destinationFiles->push_back(listFiles(*destination));
+ norms.push_back(readNorms(*destination));
+ }
+ return norms;
+}
+
+// Index compaction reads sparse and dense sources alike and writes dense
norms, so a mixed set of
+// sources merges to the same norms as dense sources.
+void TestCompactionMergesSparseNormsSources(CuTest* tc) {
+ const auto documents = sparseNormsDocuments(100);
+ RAMDirectory dense0;
+ RAMDirectory dense1;
+ RAMDirectory sparse1;
+ writeSparseNormsIndex(dense0, documents, false, -1);
+ writeSparseNormsIndex(dense1, documents, false, -1);
+ writeSparseNormsIndex(sparse1, documents, true, -1);
+
+ std::vector<std::vector<std::string>> denseFiles;
+ std::vector<std::vector<std::string>> mixedFiles;
+ const auto fromDense = compactTwoSources(dense0, dense1, &denseFiles);
+ const auto fromMixed = compactTwoSources(dense0, sparse1, &mixedFiles);
+ for (size_t i = 0; i < fromDense.size(); ++i) {
+ CuAssertTrue(tc, hasFileEnding(mixedFiles[i], ".nrm"));
+ CuAssertTrue(tc, !hasFileEnding(mixedFiles[i], ".nrs"));
+ assertSameNorms(tc, fromDense[i], fromMixed[i], 100);
+ }
+ dense0.close();
+ dense1.close();
+ sparse1.close();
+}
+
+} // namespace
+
+CuSuite* testSparseNorms() {
+ CuSuite* suite = CuSuiteNew(_T("CLucene Sparse Norms Test"));
+ SUITE_ADD_TEST(suite, TestSparseNormsDecodeToDenseNorms);
+ SUITE_ADD_TEST(suite, TestSparseNormsHiddenFromOlderReaders);
+ SUITE_ADD_TEST(suite, TestCompactionMergesSparseNormsSources);
+ return suite;
+}
diff --git a/src/test/test.h b/src/test/test.h
index eee783f93d6..f358af946b7 100644
--- a/src/test/test.h
+++ b/src/test/test.h
@@ -94,6 +94,7 @@ CuSuite *testUTF8CharsSuite(void);
CuSuite *testIndexReader2(void);
CuSuite *testPFORSuite(void);
CuSuite *testBlockMaxScoreV3(void);
+CuSuite *testSparseNorms(void);
CuSuite *testReadRange(void);
#ifdef TEST_CONTRIB_LIBS
//CuSuite *testGermanAnalyzer(void);
diff --git a/src/test/tests.cpp b/src/test/tests.cpp
index db523ef42f3..aff710a69eb 100644
--- a/src/test/tests.cpp
+++ b/src/test/tests.cpp
@@ -30,4 +30,5 @@ unittest tests[] = {{"analysis", testanalysis},
{"TestIndexReader2", testIndexReader2},
{"testBlockMaxScoreV3", testBlockMaxScoreV3},
{"testReadRange", testReadRange},
+ {"SparseNorms", testSparseNorms},
{"LastTest", NULL}};
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]