Documentation
¶
Index ¶
- Constants
- Variables
- func CloseAndRemove(file *os.File)
- func CompareTokens(a, b Token) (cmp int)
- func CountTokensBetweenCollisionFields(fieldA, fieldB *Field) (count uint64)
- func IsTemporaryFile(name, final string) bool
- func MaxPostingListHeadersBatch(l int) (n int)
- func SyncDir(dir string) error
- type Document
- type DocumentId
- type DocumentLengthEntry
- type DocumentsLengths
- type Field
- type FieldDefinition
- type FieldHeader
- type FieldsOrder
- type Footer
- type Header
- type MergeContext
- type Merger
- type PendingPostingList
- type PostingList
- type PostingListHeader
- type PostingLists
- func (p *PostingLists) Bitmap(idx int64, dst *roaring.Bitmap) (err error)
- func (p *PostingLists) DataSize() (n int)
- func (p *PostingLists) Get(idx int64) (pl *PostingList)
- func (p *PostingLists) GetChecked(idx int64) (pl *PostingList, err error)
- func (p *PostingLists) Len() (n int)
- func (p *PostingLists) WriteToFile(f *os.File, dst *bufio.Writer) (n int64, err error)
- type RawValue
- type Storage
- func (s *Storage) BuildFrom(docs ...*Document) (err error)
- func (s *Storage) Close() (err error)
- func (s *Storage) ColdInitialize()
- func (s *Storage) FrequenciesOf(token *Token) (freqs TokenFrequencies)
- func (s *Storage) Load(name string) (err error)
- func (s *Storage) Reset() (err error)
- func (s *Storage) SaveTo(name string) (err error)
- func (s *Storage) SaveToNew(name string) (err error)
- func (s *Storage) Verify() (err error)
- type Token
- type TokenDefinition
- type TokenFrequencies
- type TokenFrequencyEntry
- type Tokens
- func (s *Tokens) BinarySearchBytes(b []byte) (i int, found bool)
- func (s *Tokens) BinarySearchString(ss string) (i int, found bool)
- func (s *Tokens) GetBytes(b []byte) (token *Token, found bool)
- func (s *Tokens) GetBytesOrNear(b []byte) (token *Token, found bool)
- func (s *Tokens) GetString(ss string) (token *Token, found bool)
- func (s *Tokens) IterBytes(lo, hi []byte) (seq iter.Seq[*Token])
Constants ¶
const ( // Original format: no footer, no checksum. VersionV1 uint16 = iota // Adds a Footer with an xxh3 checksum of every byte before it. VersionV2 )
const CurrentVersion = VersionV2
Version written by SaveTo and Merge. Load accepts every version up to this one.
const DefaultBufferedWriterSize = 4 << 20
const DocumentIdSize = unsafe.Sizeof(DocumentId{})
const DocumentLengthEntrySize = unsafe.Sizeof(DocumentLengthEntry{})
const FieldHeaderSize = unsafe.Sizeof(FieldHeader{})
Marks the end of a complete VersionV2 file. A file without it was truncated or never finished writing.
const HeaderSize = unsafe.Sizeof(Header{})
const MagicNumber uint64 = 0x7E7127E9
const MaxDocuments = 1<<32 - 1
Largest number of documents a storage can hold: internal document indexes are uint32.
const MaxPostingListHeaders = 5_000_000
const MaxRawValueSize = 128
const OffsetBitmapCachedSize = 16
const PendingPostingListSize = unsafe.Sizeof(PendingPostingList{})
const PostingListHeaderSize = unsafe.Sizeof(PostingListHeader{})
const TokenFrequencyEntrySize = unsafe.Sizeof(TokenFrequencyEntry{})
const TokenSize = unsafe.Sizeof(Token{})
Variables ¶
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 CompareTokens ¶
func CountTokensBetweenCollisionFields ¶ added in v1.4.0
func IsTemporaryFile ¶ added in v1.9.6
IsTemporaryFile reports whether name (a base name) is a temporary file left by SaveTo or Merge for the final file final (also a base name): one that was never renamed into place because the write failed or the process died.
func MaxPostingListHeadersBatch ¶ added in v1.9.0
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 ¶ added in v1.9.5
type Footer struct {
// xxh3 of every byte of the file before the footer
}
Footer is the last FooterSize bytes of a VersionV2 file.
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) Merge ¶
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 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 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
type RawValue ¶
type RawValue struct {
Size uint64
Data [MaxRawValueSize]byte
}
func RawValueFrom ¶
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) Truncated ¶ added in v1.9.5
Truncated reports whether the value was longer than MaxRawValueSize and so lost bytes when it was stored.
func (*RawValue) UnsafeString ¶
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 ¶
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. If building fails the storage is left unchanged.
If the storage was loaded from a file it is closed only once the new storage is built, so docs may safely point into the old mapping (for example tokens taken from it to rebuild an index).
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 ¶
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 ¶
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) SaveTo ¶
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
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
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 TokenDefinition ¶
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 Tokens ¶
type Tokens []Token