storage

package
v1.9.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Layout

┌─────────────────────────────────────────────────────┐
│                      HEADER                         │
│  magic (8B) | version (2B) | padding (6B)           │
│  total_docs (4B) | padding (4B)                     │
│  field_count (8B)                                   │
│  total_posting_lists (8B)                           │
│  total_posting_lists_data_size (8B)                 │
│  total_token_frequencies (8B)                       │
├─────────────────────────────────────────────────────┤
│                  DOC ID TABLE                       │
│  [size (8B) | data (128B)] × total_docs             │
│  (fixed 136B stride; insertion order, not sorted;   │
│   position = internal ID; mapped zero-copy)         │
├─────────────────────────────────────────────────────┤
│           TOKEN FREQUENCIES REGION                  │
│  [doc_index (4B) | frequency (4B)]                  │
│  × total_token_frequencies                          │
│  (fixed 8B stride; indexed by frequencies_index)   │
├─────────────────────────────────────────────────────┤
│                 FIELD BLOCKS                        │
│  ┌───────────────────────────────────────────────┐  │
│  │  hash (8B) | avgdl (4B f32) | Padding (4B)    │  │
│  │  total_docs_length (8B)                       │  │
│  │  token_count (8B) | total_token_freqs (8B)    │  │
│  │  doc_length_count (8B)                        │  │
│  ├───────────────────────────────────────────────┤  │
│  │           DOC LENGTH ENTRIES                  │  │
│  │  [doc_index (4B) | length (4B)]               │  │
│  │  × doc_length_count (fixed 8B stride)         │  │
│  │  (sorted by doc_index ascending)              │  │
│  ├───────────────────────────────────────────────┤  │
│  │             TOKEN ENTRIES                     │  │
│  │  [frequency_count (8B) |                      │  │
│  │   posting_list_index (8B) |                   │  │
│  │   frequencies_index (8B) |                    │  │
│  │   value_size (8B) | value_data (128B)]        │  │
│  │  × token_count                                │  │
│  │  (fixed 160B stride; sorted alphabetically)   │  │
│  └───────────────────────────────────────────────┘  │
│  ...repeated for each field...                      │
├─────────────────────────────────────────────────────┤
│              POSTING LISTS REGION                   │
│  [offset (8B) | length (8B)] × total_posting_lists  │
│  followed by total_posting_lists_data_size bytes    │
│  of roaring bitmaps (offsets relative to the        │
│  start of the bitmap bytes)                         │
│  (indexed by posting_list_index)                    │
├─────────────────────────────────────────────────────┤
│                  FOOTER (version 2)                 │
│  checksum (8B, xxh3 of every byte before it)        │
│  footer magic (8B)                                  │
└─────────────────────────────────────────────────────┘

Invariants

  • Doc IDs and token values are stored as RawValue: an 8-byte length plus a fixed MaxRawValueSize-byte (currently 128) inline buffer. The doc ID stride is therefore 136 B; the token entry stride (3 × 8 B index fields + RawValue) is 160 B; the doc-length entry stride is 8 B (two uint32 fields, no padding). The fixed stride is what allows the doc ID table and each field's token table to be mapped directly over the file as native Go slices (unsafe.Slice) with zero allocation and zero deserialization.
  • Doc IDs are stored in the order the documents were passed to BuildFrom; Merge appends B's IDs after A's. They are not sorted. A document's position in the table is its internal sequential ID used in posting lists and TF entries.
  • Token frequencies are written immediately after the doc ID table, before the field blocks. Each TokenFrequencyEntry is a fixed 8 B record: doc_index (uint32, 4B) | frequency (uint32, 4B) — both fields are naturally aligned, so the struct carries no padding. The FrequenciesIndex in a token entry is an absolute offset into this region; the relevant slice is TokenFrequencies[FrequenciesIndex : FrequenciesIndex+FrequencyCount].
  • Doc length entries within each field block are sorted by doc_index ascending. This enables a merge scan during BM25 scoring instead of binary search.
  • Token entries within each field block are sorted alphabetically by token bytes, so they are binary-searched in place at query time — no btree is built at load. (A btree is used only as a transient accumulator during BuildFrom.)
  • Posting lists and TF entries within a field are written in the same alphabetical token order, enabling sequential page access during sorted query processing.

Field widths and ceilings

Several count/size fields are stored as 32-bit integers to keep the on-disk records compact. These widths are deliberate and impose the following hard ceilings on a single storage file:

Field Type Ceiling Notes
Header.TotalDocuments / internal doc index uint32 4,294,967,295 docs Internal doc IDs, TF DocumentIndex, and DocumentLengthEntry.Index are all uint32.
TokenFrequencyEntry.Frequency uint32 4.29B occurrences Count of one token in one field of one document — never approached in practice.
DocumentLengthEntry.Length uint32 4.29B tokens Per-document field length in tokens, used as docLen in BM25.
PostingListHeader.Size uint32 4 GiB per posting list A roaring bitmap over a uint32 doc-ID domain serializes to well under 1 GiB even fully dense, so this is not a practical limit.

Because the doc-ID domain is itself uint32, no single posting list can serialize past the uint32 size field, and no token frequency can exceed uint32 — the width reductions are safe for any corpus that fits the 4.29B-document ceiling. Fields that index the whole file (FieldCount, TotalPostingLists, TotalTokenFrequencies, FrequenciesIndex, PostingListIndex, per-token FrequencyCount, and all byte offsets during load) remain 64-bit.

When shrinking these widths, keep buffer-length math 64-bit. During load the remaining-buffer bounds check must compare uint64(len(buffer)) against the (now 32-bit) record size — never uint32(len(buffer)). On a multi-GB index the buffer length exceeds uint32 range, and truncating it there makes the posting-list bounds check compare against the low 32 bits of the length, which fails spuriously on exactly the large files this engine targets.

Storage.Size contract

Storage.Size is set by both BuildFrom and Load:

  • After BuildFrom: exact byte count that SaveTo will write, footer included. SaveTo itself does not read it.
  • After Load: number of bytes consumed from the mapped file. For version 2 files this is the whole file, footer included; version 1 files may carry trailing bytes that are not counted.

Canonical write path

var s Storage
err := s.BuildFrom(docs...)   // computes s.Size; ErrValueTooLong for >128 B values

err = s.SaveTo("index.bin")   // temp file + buffered writes + checksum footer
                              // + fsync + rename + directory fsync

SaveTo owns the whole write. It writes to a temporary file next to the destination (.index.bin.*.tmp): the header, doc ID table, token frequencies and field blocks through a 4 MiB buffered writer, then the posting-list headers and bitmap bytes, then the footer with the xxh3 checksum of everything before it. It then syncs the file, renames it over the destination and syncs the directory.

Until the rename, the destination is untouched: a failure or crash leaves any existing index intact, and processes that have the old file loaded keep reading it (the rename gives the new file a new inode instead of truncating the mapped one). SaveToNew does the same but refuses to replace an existing file (errors.Is(err, os.ErrExist)). There is no separate "write into a caller-provided buffer" entry point.

BuildFrom returns ErrValueTooLong for a document ID or token over MaxRawValueSize bytes and ErrTooManyDocuments past the uint32 document limit, leaving the storage empty. A token listed twice in one document's field has its frequencies summed, and a field listed twice in one document has its lengths summed.

Canonical read path

var s Storage
err := s.Load("index.bin")   // open + mmap(PROT_READ, MAP_SHARED) + madvise
defer s.Close()              // munmap + close fd

// s is now queryable; token/doc/TF tables are mapped in place as fixed-stride
// slices (no btree rebuilt — tokens are binary-searched directly), and all
// reads are O(log n) search + O(1) slice access

Load maps the file read-only and points every table (DocumentsIds, TokenFrequencies, each field's DocumentLengths and Tokens, and the posting lists) directly into the mapped pages via unsafe.Slice. Nothing is copied out of the mapping, so the Storage is valid only until Close. Close clears the storage so that stale use fails cleanly; slices taken from it before Close must not be used afterwards. Load on a storage that is already loaded closes it first.

Before mapping any table, Load checks the magic number, the version, and (for version 2) the footer, then checks that every table fits in the remaining bytes. Size checks divide instead of multiplying, so a damaged count cannot overflow past them, and the field count is bounded by the file size before anything is allocated. Errors caused by the file's contents wrap ErrCorrupt (or ErrUnsupportedVersion), and a failed Load leaves the storage empty.

Load does not read every byte, so it stays fast on large files. Verify does:

if err := s.Verify(); err != nil { // errors.Is(err, ErrCorrupt); ErrChecksum for a bad checksum
    log.Fatal(err)
}

It compares the file's xxh3 with the footer (version 2), then checks every internal reference: doc IDs and tokens fit their 128-byte slots, tokens are strictly sorted, each token's frequencies and posting list are in range, name the same documents, and reference only existing documents. Version 1 files get the reference checks only.

Posting list decoding

A PostingList is a thin { Data []byte } view into the mmap'd file. Decode posting list i into a roaring bitmap with PostingLists.Bitmap, which clears the destination and uses FromUnsafeBytes — the bitmap aliases the mmap buffer with no copy:

var bm roaring.Bitmap
err := s.PostingLists.Bitmap(int64(token.PostingListIndex), &bm) // zero-copy, no allocation

Bitmap returns an error wrapping ErrCorrupt and leaves bm empty if the index or its header points outside the file, the bytes do not decode, or the bitmap references a document past the document count. Queries ignore the error and so drop a damaged posting list instead of crashing. Use the token's frequencies through Storage.FrequenciesOf(token), which returns nil for an out-of-range token instead of panicking. PostingLists.Get(i).UnsafeBitmap(&bm) still works, but skips the document range check.

Because the decoded bitmap points into read-only mmap pages, it must not be mutated in place. Clone first if you need to modify it:

owned := bm.Clone()
owned.Add(newDocID)

Merge

Merger.Merge combines two storages into a single output file using a streaming, temp-file-backed pipeline. No output size pre-computation is required. The only precondition is that doc ID ranges are disjoint: every doc ID in b must sort after every doc ID in a. This is guaranteed when the corpus is partitioned by range before building each batch.

m := storage.Merger{TempDir: "/tmp"} // scratch files written here during merge

err := m.Merge("merged.bin", &a, &b)

var merged Storage
err = merged.Load("merged.bin")
defer merged.Close()

The output is written like SaveTo: to a temporary file next to merged.bin, with a checksum footer, synced and renamed into place, so a failed or interrupted merge never leaves a partial merged.bin and never touches its inputs. Every write error is checked. Set NoReplace: true to make Merge refuse to replace an existing file. A damaged input (an out-of-range reference or a posting list that does not decode) makes Merge return an error wrapping ErrCorrupt instead of panicking or copying the damage into a new file with a fresh checksum.

Merge semantics

Fields are classified into three groups per merge:

  • A-only fields: written verbatim, indices resequenced via global cursors.
  • B-only fields: written with all internal doc indices shifted by len(a.DocumentsIds). Posting list bitmaps are re-encoded with the offset applied. Token frequency DocumentIndex values are shifted accordingly.
  • Collision fields (same field hash in both): tokens are further classified as A-only, B-only, or shared. Shared tokens have their posting lists unioned (B's doc IDs shifted before OR), their frequency slices concatenated (B's entries shifted), and FrequencyCount summed. AvgDocumentLength is recomputed from the merged DocumentLengths slice.

Field count in the output is len(a.Fields) + len(b.Fields) - collisions.

Large-corpus ingestion pattern

For corpora too large to fit in one BuildFrom call, partition docs into unsorted batches, build each batch into a segment file in parallel, then merge pairwise:

// Build segments in parallel (each worker owns a disjoint doc ID range)
segments := buildSegmentsParallel(batches) // []string of file paths

// Pairwise merge until one file remains
for len(segments) > 1 {
    next := mergePass(segments, m)
    segments = next
}
// segments[0] is the final index

With ~2 GB of heap per 1M-doc segment build and a merge that holds only the working set (not the whole corpus), ingestion scales to arbitrarily large corpora within a bounded memory envelope. This is not a projection: textiplex indexed the full 120 GB English Wikipedia export (25.65M documents) into a 70 GB index on a single i9-10900K in ~33.6 min of segment creation followed by ~30.9 min of merge, ~1 h 4.5 min total. Bluge and Bleve cannot complete this corpus; they OOM during segment combination.

BM25 scoring formula

score(doc, term) = idf(term) × (tf × (k1+1)) / (tf + k1 × (1 - b + b × docLen/avgdl))

idf(term) = log(1 + (totalDocs - docFreq + 0.5) / (docFreq + 0.5))

Where:

  • totalDocs — from the header
  • docFreq — Token.FrequencyCount
  • tf — TokenFrequencies[FrequenciesIndex + offset].Frequency for the candidate doc
  • docLen — DocumentLengths[i].Length for the candidate doc (binary search or merge scan)
  • avgdl — Field.AvgDocumentLength

Benchmarks

The table below was measured on an Intel Core i9-10900K @ 3.70GHz (10C/20T) at an earlier version of the code. The 1M-doc corpus has 3 fields per document, 1 unique token per field (Bluge-equivalent). Numbers for the current code are in Current numbers.

Operation Time Throughput Heap Allocs
BuildFrom (textiplex) 2.84s — 2.12 GB 33.5M
Merge 2×500K→1M (textiplex) 1.35s 375 MB/s 0.71 GB 19.5M
Load (textiplex) 0.63s 804 MB/s 0.78 GB 27.0M
OfflineWriter (Bluge fork) 5.47s — 6.34 GB 104.9M
OfflineWriter (Bluge upstream) 12.28s — 8.20 GB 131.0M
OfflineWriter (Bleve) 24.28s — 10.07 GB 146.5M

Build vs Bluge fork: 1.9× faster, 3.0× less heap, 3.1× fewer allocs. Build vs Bluge upstream: 4.3× faster, 3.9× less heap, 3.9× fewer allocs. Build vs Bleve: 8.5× faster, 4.7× less heap, 4.4× fewer allocs.

The Load row predates the current loader. The fixed-stride layout now makes Load a pure mmap-and-slice operation: doc IDs, token tables, doc-length tables and token-frequency tables are mapped in place with no per-record parsing.

Current numbers (i7-1280P)

Current code on an Intel Core i7-1280P (12th gen, 20 threads), Linux, amd64, Go 1.27.4, same 1M-doc corpus. Not comparable with the i9-10900K table above: the CPU and the code both differ. One run per benchmark (-count=1), so treat timing differences under about 10% as noise; heap and allocation counts are exact.

Operation Time Throughput Heap Allocs
BuildFrom 1.80 s — 1.70 GB 21.4M
Merge 2×500K→1M 0.74 s 1,037 MB/s 0.95 GB 15.0M
Load 3.4 ms — 2.1 KB 7

Load maps the file without reading its pages, so its time does not grow with the amount of data read and no throughput figure is given. Heap is the total allocated per operation (B/op), not peak resident memory.

Full English Wikipedia

The decisive result: textiplex indexed the complete 120 GB English Wikipedia export — 25,653,263 documents (id + title + content, parsed with encoding/json/v2) into a 70 GB index on the same i9-10900K.

Phase Time Peak RAM
Segment creation (indexing) 33.6 min 14 GB
Merge (parallel) 30.9 min see note below
Total 1 h 4.5 min —

Merge peak RAM is unmeasured in this run. The 30.9 min figure comes from the parallel bottom-up merge (up to 8 workers). Because multiple pairwise merges run concurrently, peak resident memory is expected to exceed the 12 GB of the older serial merge and must be re-measured (e.g. /usr/bin/time -v maxrss) before quoting a number here. The B/op reported by go test -benchmem is cumulative allocation traffic, not resident set size, and is not a substitute.

~214 GB/hour during segment creation, ~112 GB/hour end-to-end. Bluge (upstream and fork) and Bleve all OOM during the merge and never finish — textiplex is the only Go FTS engine able to fully index Wikipedia.

Documentation

Index

Constants

View Source
const (
	// Original format: no footer, no checksum.
	VersionV1 uint16 = iota
	// Adds a Footer with an xxh3 checksum of every byte before it.
	VersionV2
)
View Source
const CurrentVersion = VersionV2

Version written by SaveTo and Merge. Load accepts every version up to this one.

View Source
const DefaultBufferedWriterSize = 4 << 20
View Source
const DocumentIdSize = unsafe.Sizeof(DocumentId{})
View Source
const DocumentLengthEntrySize = unsafe.Sizeof(DocumentLengthEntry{})
View Source
const FieldHeaderSize = unsafe.Sizeof(FieldHeader{})
View Source
const FooterMagic uint64 = 0x7E7127E9F007E2

Marks the end of a complete VersionV2 file. A file without it was truncated or never finished writing.

View Source
const FooterSize = unsafe.Sizeof(Footer{})
View Source
const HeaderSize = unsafe.Sizeof(Header{})
View Source
const MagicNumber uint64 = 0x7E7127E9
View Source
const MaxDocuments = 1<<32 - 1

Largest number of documents a storage can hold: internal document indexes are uint32.

View Source
const MaxPostingListHeaders = 5_000_000
View Source
const MaxRawValueSize = 128
View Source
const OffsetBitmapCachedSize = 16
View Source
const PendingPostingListSize = unsafe.Sizeof(PendingPostingList{})
View Source
const PostingListHeaderSize = unsafe.Sizeof(PostingListHeader{})
View Source
const TokenFrequencyEntrySize = unsafe.Sizeof(TokenFrequencyEntry{})
View Source
const TokenSize = unsafe.Sizeof(Token{})

Variables

View Source
var (
	// The file is not a textiplex index or is damaged. Every Load and Verify
	// error caused by the file's contents wraps it.
	ErrCorrupt = errors.New("storage: corrupt index")
	// The file was written by a newer version of textiplex.
	ErrUnsupportedVersion = errors.New("storage: unsupported index version")
	// The file's contents do not match the checksum in its footer.
	ErrChecksum = fmt.Errorf("%w: checksum mismatch", ErrCorrupt)
	// A document id or token is longer than MaxRawValueSize bytes.
	ErrValueTooLong = errors.New("storage: value longer than MaxRawValueSize bytes")
	// More documents than a uint32 internal document index can address.
	ErrTooManyDocuments = errors.New("storage: more than 4294967295 documents")
)

Functions

func CloseAndRemove

func CloseAndRemove(file *os.File)

func CompareTokens

func CompareTokens(a, b Token) (cmp int)

func CountTokensBetweenCollisionFields added in v1.4.0

func CountTokensBetweenCollisionFields(fieldA, fieldB *Field) (count uint64)

func MaxPostingListHeadersBatch added in v1.9.0

func MaxPostingListHeadersBatch(l int) (n int)

func SyncDir added in v1.9.5

func SyncDir(dir string) error

SyncDir makes creates, renames and removals in dir durable.

Types

type Document

type Document struct {
	// External document identifier e.g. "CO1.PCCNTR.123456"
	// Must be unique across the index
	// Will be inserted sorted into DocumentsIds
	Id DocumentId
	// Fields present in this document
	// Fields absent from this slice are treated as empty for this document
	Fields []*FieldDefinition
}

type DocumentId

type DocumentId struct {
	Value RawValue
}

type DocumentLengthEntry

type DocumentLengthEntry struct {
	// Index of the document referenced
	Index uint32
	// Actual length of the document in number of tokens
	Length uint32
}

This is per field Meaning the length only references what the field is actually storing for that particular document Writer must ensure they are sorted based on index

type DocumentsLengths added in v1.9.0

type DocumentsLengths []DocumentLengthEntry

func (DocumentsLengths) BinarySearch added in v1.9.0

func (s DocumentsLengths) BinarySearch(docIdx uint32) (i int, found bool)

type Field

type Field struct {
	// Used for BM25 calculation
	AvgDocumentLength float32
	// Computed on load time
	TotalDocumentsLength uint64
	// Tokens present on the file
	// This field is stored in memory but most of its references
	// are direct mmap zero-copied arrays
	Tokens Tokens
	// Sum of all token frequencies count
	TotalTokenFrequenciesCount uint64
	// DocumentLength entries
	// Keys are indexes of the documents
	DocumentLengths DocumentsLengths
}

type FieldDefinition

type FieldDefinition struct {
	// xxh3 hash of the field name
	Hash uint64
	// Tokens found in this field for this document
	// Caller must deduplicate — one entry per unique token
	// Frequency carries the count of occurrences
	Tokens []*TokenDefinition
	// Total number of tokens in this field for this document
	// Used to update avgdl and store as DocumentLengthEntry
	Length uint32
}

type FieldHeader

type FieldHeader struct {
	// xxh3 hashed representation of the field string
	Hash uint64
	// Avgdl used in the BM25 formula
	// Precomputed so the reader can go directly to queries
	AvgDocumentLength float32

	// Storage total document lengths
	TotalDocumentsLength uint64
	// Number of total tokens the field has
	// This number is also the number of posting lists
	TokenCount uint64
	// Sum of all token frequencies count
	TotalTokenFrequencies uint64
	// Number of document lengths included
	DocumentLengthCount uint64
	// contains filtered or unexported fields
}

type FieldsOrder added in v1.4.0

type FieldsOrder struct {
	A, B, Collision []uint64
}

func (*FieldsOrder) Count added in v1.4.0

func (o *FieldsOrder) Count() (count uint64)
type Footer struct {
	// xxh3 of every byte of the file before the footer
	Checksum uint64
	Magic    uint64
}

Footer is the last FooterSize bytes of a VersionV2 file.

type Header struct {
	Magic   uint64
	Version uint16

	TotalDocuments uint32

	FieldCount                uint64
	TotalPostingLists         uint64
	TotalPostingListsDataSize uint64
	TotalTokenFrequencies     uint64
	// contains filtered or unexported fields
}

type MergeContext added in v1.4.0

type MergeContext struct {
	StorageA                             *Storage
	StorageB                             *Storage
	DstFile                              *os.File
	DstW                                 *bufio.Writer
	PostingListCursor, FrequenciesCursor uint64
	// Cached token frequencies
	PostingListCount                              uint64
	PendingPostingLists                           []PendingPostingList
	Buffer                                        [8]byte
	CachedBitmapChunk                             [OffsetBitmapCachedSize]uint32
	DocumentOffset                                uint32
	ReusableBitmap, BitmapForPostingListRetrieval roaring.Bitmap
	// Iteration order
	FieldsOrder FieldsOrder
}

type Merger

type Merger struct {
	// Directory for scratch files used during a merge. The output itself is
	// always written next to its final name.
	TempDir string
	// Never replace an existing file at the output name: Merge fails with an
	// error matching os.ErrExist instead.
	NoReplace bool
}

Handles merges between storages

func (*Merger) CreateTemp

func (m *Merger) CreateTemp(pattern string) (file *os.File, err error)

func (*Merger) Merge

func (m *Merger) Merge(name string, a, b *Storage) (err error)

Merge merges storages A and B into the file name; B's documents follow A's. Document ids should not collide in both storage otherwise undefined behavior will ocurr

The output is written under a temporary name next to name and only renamed into place once it is complete and synced, so name never holds a partial file and a failure leaves any existing file at name untouched. Damaged inputs make Merge return an error wrapping ErrCorrupt rather than panic or silently drop postings.

type PendingPostingList added in v1.4.0

type PendingPostingList struct {
	IndexA int64
	IndexB int64
}

type PostingList

type PostingList struct {
	Data []byte
}

func (*PostingList) UnsafeBitmap added in v1.6.3

func (l *PostingList) UnsafeBitmap(dst *roaring.Bitmap) (err error)

UnsafeBitmap clears dst and decodes the posting list into it without copying: dst aliases Data, so it must not outlive the Storage and must not be mutated in place (Clone it first). A posting list that fails to decode leaves dst empty and returns an error wrapping ErrCorrupt.

type PostingListHeader

type PostingListHeader struct {
	Offset uint64
	Length uint64
}

type PostingLists added in v1.9.0

type PostingLists struct {
	Reference []byte
	Headers   []PostingListHeader
	Entries   []PostingList
	// Number of documents in the storage. Posting lists read from a file are
	// rejected by Bitmap if they reference a document at or past it.
	DocumentCount uint64
}

func (*PostingLists) Bitmap added in v1.9.5

func (p *PostingLists) Bitmap(idx int64, dst *roaring.Bitmap) (err error)

Bitmap clears dst and decodes posting list idx into it without copying (see PostingList.UnsafeBitmap for the aliasing rules). A missing or undecodable posting list, or one read from a file that references a document past DocumentCount, leaves dst empty and returns an error wrapping ErrCorrupt.

func (*PostingLists) DataSize added in v1.9.0

func (p *PostingLists) DataSize() (n int)

func (*PostingLists) Get added in v1.9.0

func (p *PostingLists) Get(idx int64) (pl *PostingList)

Get returns the posting list at idx. An index or a header that points outside the storage yields an empty posting list instead of panicking, so a damaged file degrades query results rather than crashing the process. Prefer Bitmap, which also rejects posting lists that reference documents the storage does not have, and does not allocate.

func (*PostingLists) GetChecked added in v1.9.5

func (p *PostingLists) GetChecked(idx int64) (pl *PostingList, err error)

GetChecked returns the posting list at idx, or an error wrapping ErrCorrupt if idx or its header points outside the storage.

func (*PostingLists) Len added in v1.9.0

func (p *PostingLists) Len() (n int)

func (*PostingLists) WriteToFile added in v1.9.0

func (p *PostingLists) WriteToFile(f *os.File, dst *bufio.Writer) (n int64, err error)

type RawValue

type RawValue struct {
	Size uint64
	Data [MaxRawValueSize]byte
}

func RawValueFrom

func RawValueFrom[T ~string | ~[]byte](b T) (v RawValue)

RawValueFrom copies b into a RawValue. Only the first MaxRawValueSize bytes fit; Size keeps the original length so a longer value can be detected with Truncated (BuildFrom rejects such values instead of storing them cut short).

func (*RawValue) Bytes

func (v *RawValue) Bytes() (b []byte)

func (*RawValue) Hash

func (v *RawValue) Hash() (hash uint64)

func (*RawValue) Truncated added in v1.9.5

func (v *RawValue) Truncated() bool

Truncated reports whether the value was longer than MaxRawValueSize and so lost bytes when it was stored.

func (*RawValue) UnsafeString

func (v *RawValue) UnsafeString() (s string)

type Storage

type Storage struct {
	// Read-only intended field
	Version uint16
	// Read-only intended field
	Size uint64
	// Reference of the internal buffer of the file
	// exposed only if the caller needs to hack his way around
	Buffer []byte
	// File reference
	File *os.File
	// Fast reference to mapped fields for O(1) lookups
	Fields map[uint64]*Field
	// Documents mapped only unce to the sub-slices of buffer for quick convertion between
	// index form and human-readble form
	DocumentsIds []DocumentId
	// Posting lists used once the caller knows which fields-tokens to query
	PostingLists PostingLists
	// Token frequencies
	TokenFrequencies TokenFrequencies
	// Used to determine if the storage was already initialized or not
	Initialized bool
}

func (*Storage) BuildFrom

func (s *Storage) BuildFrom(docs ...*Document) (err error)

BuildFrom builds the storage in memory from a set of documents. Documents keep the order they are passed in; a document's position is its internal index.

It returns ErrValueTooLong if a document id or a token is longer than MaxRawValueSize bytes (instead of storing it cut short, which would make it unsearchable and could merge distinct values), and ErrTooManyDocuments past the uint32 document limit. On error the storage is left empty.

The same token listed twice in one field of one document has its frequencies summed, and the same field listed twice in one document has its lengths summed, so the index stays consistent even if the caller does not deduplicate.

func (*Storage) Close

func (s *Storage) Close() (err error)

Close unmaps a loaded storage and closes its file. Every slice the storage handed out (doc ids, tokens, frequencies, posting lists, bitmaps decoded with UnsafeBitmap) points into that mapping and must not be used afterwards; Close clears the storage so it cannot be used by mistake. On a storage that was built in memory and never loaded, Close does nothing.

func (*Storage) ColdInitialize

func (s *Storage) ColdInitialize()

func (*Storage) FrequenciesOf added in v1.9.5

func (s *Storage) FrequenciesOf(token *Token) (freqs TokenFrequencies)

FrequenciesOf returns the token's per-document frequencies, or nil if the token's range lies outside the storage (a damaged file).

func (*Storage) Load

func (s *Storage) Load(name string) (err error)

Load maps the file read-only and points every table directly into the mapping. A storage that is already loaded is closed first.

Load checks the file's structure: magic number, version, that every table fits in the file, and (format v2) that the footer is present. It does not read every byte, so it stays fast on large indexes; call Verify for the full checksum and cross-reference check. Errors caused by the file's contents wrap ErrCorrupt (or ErrUnsupportedVersion). On error the storage is left empty.

func (*Storage) Reset

func (s *Storage) Reset() (err error)

func (*Storage) SaveTo

func (s *Storage) SaveTo(name string) (err error)

SaveTo writes the storage to name. The file is written under a temporary name in the same directory, synced, and only then renamed over name, so a failure or crash at any point leaves an existing file at name untouched, and processes that have the old file loaded keep reading the old contents.

func (*Storage) SaveToNew added in v1.9.5

func (s *Storage) SaveToNew(name string) (err error)

SaveToNew is SaveTo but never replaces an existing file: if name exists it returns an error matching os.ErrExist and writes nothing.

func (*Storage) Verify added in v1.9.5

func (s *Storage) Verify() (err error)

Verify checks the whole storage and returns an error wrapping ErrCorrupt (ErrChecksum for a checksum mismatch) describing the first problem found.

For a loaded version 2 file it first compares the xxh3 checksum of the file with the one in its footer. It then checks every internal reference: doc ids and tokens fit their buffers, tokens are strictly sorted, every token's frequencies and posting list are in range and agree with each other, and every document index is below the document count.

Verify reads every byte of the index, so it costs a full pass over the file. Load does not call it. Run it after copying an index from another machine, at startup if you do not trust the disk, or before an operation that destroys the only other copy of the data (Writer.VerifySegments).

type Token

type Token struct {
	// Document frequency of the token in all documents
	FrequencyCount uint64
	// Posting list of the documents for this token
	PostingListIndex uint64
	// Token frequencies per document
	FrequenciesIndex uint64
	// Actual content of the token
	Value RawValue
}

type TokenDefinition

type TokenDefinition struct {
	// Normalized token value e.g. "interventoria" not "Interventoría"
	// The caller is responsible for normalization before insertion
	Value []byte
	// How many times this token appears in this field of this document
	Frequency uint32
}

type TokenFrequencies added in v1.9.0

type TokenFrequencies []TokenFrequencyEntry

func (TokenFrequencies) BinarySearch added in v1.9.0

func (s TokenFrequencies) BinarySearch(docIdx uint32) (i int, found bool)

type TokenFrequencyEntry

type TokenFrequencyEntry struct {
	// The index of the document
	// Mapping this to a human readable key consist in
	// indexing the document id on the document id table
	DocumentIndex uint32
	// Token frequency on this document
	// this value is used by BM25
	Frequency uint32
}

type Tokens

type Tokens []Token

func (*Tokens) BinarySearchBytes added in v1.9.0

func (s *Tokens) BinarySearchBytes(b []byte) (i int, found bool)

func (*Tokens) BinarySearchString added in v1.9.0

func (s *Tokens) BinarySearchString(ss string) (i int, found bool)

func (*Tokens) GetBytes

func (s *Tokens) GetBytes(b []byte) (token *Token, found bool)

func (*Tokens) GetBytesOrNear

func (s *Tokens) GetBytesOrNear(b []byte) (token *Token, found bool)

func (*Tokens) GetString

func (s *Tokens) GetString(ss string) (token *Token, found bool)

func (*Tokens) IterBytes

func (s *Tokens) IterBytes(lo, hi []byte) (seq iter.Seq[*Token])

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL