index

package
v1.72.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 33 Imported by: 2 modules, 3 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.

Documentation

Index

Constants

View Source
const (
	ItemKindSnapshot = ".snp"
	ItemKindSegment  = ".seg"
	// ItemKindGraph is a cached HNSW graph of one segment; see graphItemID.
	ItemKindGraph = ".hnsw"
)

Kinds of items managed by a Directory

View Source
const (
	EventKindCloseStart                 = 1 // when the index has started to close
	EventKindClose                      = 2 // when the index has been fully closed
	EventKindMergerProgress             = 3 // when the index has completed a round of merge operations
	EventKindPersisterProgress          = 4 // when the index has completed a round of persistence operations
	EventKindBatchIntroductionStart     = 5 // when the index has started to introduce a new batch
	EventKindBatchIntroduction          = 6 // when index has finished introducing a batch
	EventKindMergeTaskIntroductionStart = 7 // when the index has started to introduce a merge
	EventKindMergeTaskIntroduction      = 8 // when the index has finished introdocing a merge

)

Kinds of index events

View Source
const DefaultStreamMemoryBudget = 16 << 20

DefaultStreamMemoryBudget is the Stream buffer size used for a non-positive budget. Building a segment takes about as much again, so a small budget bounds indexing memory with no loss of speed (16 MiB: 100K documents index in the same CPU time as 64 MiB, in a third of the memory).

View Source
const TimestampField = "_bluge_timestamp"

TimestampField is reserved for document time metadata, stored as a big-endian int64.

Variables

This section is empty.

Functions

func LoadMMapAlways

func LoadMMapAlways(f lock.LockedFile) (*segment.Data, io.Closer, error)

func LoadMMapNever

func LoadMMapNever(f lock.LockedFile) (*segment.Data, io.Closer, error)

Types

type Batch

type Batch struct {
	// contains filtered or unexported fields
}

func NewBatch

func NewBatch() *Batch

func (*Batch) Delete

func (b *Batch) Delete(id segment.Term)

func (*Batch) Insert

func (b *Batch) Insert(doc segment.Document)

func (*Batch) PersistedCallback

func (b *Batch) PersistedCallback() func(error)

func (*Batch) Reset

func (b *Batch) Reset()

func (*Batch) SetPersistedCallback

func (b *Batch) SetPersistedCallback(f func(error))

func (*Batch) Update

func (b *Batch) Update(id segment.Term, doc segment.Document)

type Config

type Config struct {
	SegmentType    string
	SegmentVersion uint32

	UnsafeBatch        bool
	EventCallback      func(Event)
	AsyncError         func(error)
	MergePlanOptions   mergeplan.Options
	NumAnalysisWorkers int
	AnalysisChan       chan func()
	GoFunc             func(func())
	DeletionPolicyFunc func() DeletionPolicy
	DirectoryFunc      func() Directory
	NormCalc           func(string, int) float32

	MergeBufferSize int

	// StoredChunkCacheSize bounds decompressed stored-field chunks each ice
	// segment keeps in its LRU; zero disables caching. Applies to segments
	// opened after the index is configured.
	StoredChunkCacheSize int

	// VectorStorage selects where persisted HNSW graphs keep their vectors;
	// the zero value is VectorStorageDisk.
	VectorStorage VectorStorage

	// VectorIndexes declares the approximate searches to prepare: a Writer
	// builds their HNSW graphs in the background as segments are introduced,
	// persisted and merged, rather than on the first search.
	VectorIndexes []VectorIndex

	// Inclusive segment time bounds; zero leaves that bound unrestricted.
	// Unknown timestamps are retained. Only read-only OpenReader accepts a range.
	FilterTimeMin int64
	FilterTimeMax int64

	// Optimizations
	OptimizeConjunction          bool
	OptimizeConjunctionUnadorned bool
	OptimizeDisjunctionUnadorned bool

	// MinSegmentsForInMemoryMerge represents the number of
	// in-memory zap segments that persistSnapshotMaybeMerge() needs to
	// see in an Snapshot before it decides to merge and persist
	// those segments
	MinSegmentsForInMemoryMerge int

	// PersisterNapTimeMSec controls the wait/delay injected into
	// persistence workloop to improve the chances for
	// a healthier and heavier in-memory merging
	PersisterNapTimeMSec int

	// PersisterNapTimeMSec > 0, and the number of files is less than
	// PersisterNapUnderNumFiles, then the persister will sleep
	// PersisterNapTimeMSec amount of time to improve the chances for
	// a healthier and heavier in-memory merging
	PersisterNapUnderNumFiles int

	// MemoryPressurePauseThreshold let persister to have a better leeway
	// for prudently performing the memory merge of segments on a memory
	// pressure situation. Here the config value is an upper threshold
	// for the number of paused application threads. The default value would
	// be a very high number to always favor the merging of memory segments.
	MemoryPressurePauseThreshold int

	ValidateSnapshotCRC bool

	// IndexMode selects how Writer.Batch builds segments, see Mode.
	IndexMode Mode
	// BatchSegmentDocs caps the documents per segment in IndexModeBatch;
	// zero or less builds one segment per batch.
	BatchSegmentDocs int
	// StreamMemoryBudget is the packed bytes per segment in IndexModeStream
	// and of Writer.NewStream(0); zero or less uses
	// DefaultStreamMemoryBudget.
	StreamMemoryBudget int
	// contains filtered or unexported fields
}

func DefaultConfig

func DefaultConfig(path string) Config

func DefaultConfigWithDirectory

func DefaultConfigWithDirectory(df func() Directory) Config

func InMemoryOnlyConfig

func InMemoryOnlyConfig() Config

func (Config) DisableOptimizeConjunction

func (config Config) DisableOptimizeConjunction() Config

func (Config) DisableOptimizeConjunctionUnadorned

func (config Config) DisableOptimizeConjunctionUnadorned() Config

func (Config) DisableOptimizeDisjunctionUnadorned

func (config Config) DisableOptimizeDisjunctionUnadorned() Config

func (Config) WithBatchIndexing added in v1.70.0

func (config Config) WithBatchIndexing(segmentDocs int) Config

WithBatchIndexing selects IndexModeBatch with up to segmentDocs documents per segment; zero or less builds one segment per batch. With a cap, each document's analysis is released once its segment is built.

func (Config) WithNormCalc

func (config Config) WithNormCalc(calc func(field string, numTerms int) float32) Config

WithNormCalc sets the field length norm; segments of large batches are built by several goroutines at once, so calc must be safe to call concurrently.

func (Config) WithPersisterNapTimeMSec

func (config Config) WithPersisterNapTimeMSec(napTime int) Config

func (Config) WithSegmentPlugin

func (config Config) WithSegmentPlugin(plugin *SegmentPlugin) Config

func (Config) WithSegmentType

func (config Config) WithSegmentType(typ string) Config

func (Config) WithSegmentVersion

func (config Config) WithSegmentVersion(ver uint32) Config

func (Config) WithStoredChunkCacheSize added in v1.30.0

func (config Config) WithStoredChunkCacheSize(n int) Config

WithStoredChunkCacheSize re-registers the ice plugins so their segments cache at most n decompressed stored-field chunks; zero disables caching.

func (Config) WithStreamIndexing added in v1.70.0

func (config Config) WithStreamIndexing(memoryBudget int) Config

WithStreamIndexing selects IndexModeStream with a segment every memoryBudget packed bytes; zero or less uses DefaultStreamMemoryBudget. Each document's analysis is released once it is packed.

func (Config) WithTimeRange

func (config Config) WithTimeRange(timeMin, timeMax int64) Config

WithTimeRange prunes segments outside the inclusive range, not individual documents. Zero bounds are unrestricted. Documents must use the same timestamp units.

func (Config) WithUnsafeBatches

func (config Config) WithUnsafeBatches() Config

func (Config) WithVectorIndex added in v1.72.0

func (config Config) WithVectorIndex(field string, metric vec.Metric, params hnsw.Params) Config

WithVectorIndex declares an approximate search whose graphs a Writer builds at index time; see VectorIndex.

func (Config) WithVectorStorage added in v1.50.0

func (config Config) WithVectorStorage(storage VectorStorage) Config

WithVectorStorage selects where persisted HNSW graphs keep their vectors.

func (Config) WithVirtualField

func (config Config) WithVirtualField(field segment.Field) Config

type DeletionPolicy

type DeletionPolicy interface {
	Commit(snapshot *Snapshot)
	Cleanup(Directory) error
}

type Directory

type Directory interface {

	// Setup is called first, allowing a directory to
	// perform additional set up, or return an error
	// indicating this directory cannot be used
	Setup(readOnly bool) error

	// List the ids of all the items of the specified kind
	// Items are returned in descending order by id
	List(kind string) ([]uint64, error)

	// Load the specified item
	// Item data is accessible via the returned *segment.Data structure
	// A io.Closer is returned, which must be called to release
	// resources held by this open item.
	// NOTE: care must be taken to handle a possible nil io.Closer
	Load(kind string, id uint64) (*segment.Data, io.Closer, error)

	// Persist a new item with data from the provided WriterTo
	// Implementations should monitor the closeCh and return with error
	// in the event it is closed before completion.
	Persist(kind string, id uint64, w WriterTo, closeCh chan struct{}) error

	// Remove the specified item
	Remove(kind string, id uint64) error

	// Stats returns total number of items and their cumulative size
	Stats() (numItems uint64, numBytes uint64)

	// Sync ensures directory metadata itself has been committed.
	// On platforms without directory fsync (Windows) this is best-effort:
	// item contents are already flushed by Persist, but a power loss may
	// still lose the newest directory entries.
	Sync() error

	// Lock ensures this process has exclusive access to write in this directory
	Lock() error

	// Unlock releases the lock held on this directory
	Unlock() error
}

Directory abstracts over a collection of items An item has a kind (string) and an id (uint64)

type Event

type Event struct {
	Kind     int
	Chill    *Writer
	Duration time.Duration
}

Event represents the information provided in an OnEvent() callback.

type FileSystemDirectory

type FileSystemDirectory struct {
	// contains filtered or unexported fields
}

func NewFileSystemDirectory

func NewFileSystemDirectory(path string) *FileSystemDirectory

func (*FileSystemDirectory) List

func (d *FileSystemDirectory) List(kind string) ([]uint64, error)

func (*FileSystemDirectory) Load

func (d *FileSystemDirectory) Load(kind string, id uint64) (*segment.Data, io.Closer, error)

func (*FileSystemDirectory) Lock

func (d *FileSystemDirectory) Lock() error

func (*FileSystemDirectory) Persist

func (d *FileSystemDirectory) Persist(kind string, id uint64, w WriterTo, closeCh chan struct{}) error

func (*FileSystemDirectory) Remove

func (d *FileSystemDirectory) Remove(kind string, id uint64) error

func (*FileSystemDirectory) SetLoadMMapFunc

func (d *FileSystemDirectory) SetLoadMMapFunc(f LoadMMapFunc)

func (*FileSystemDirectory) Setup

func (d *FileSystemDirectory) Setup(readOnly bool) error

func (*FileSystemDirectory) Stats

func (d *FileSystemDirectory) Stats() (numFilesOnDisk, numBytesUsedDisk uint64)

func (*FileSystemDirectory) Sync

func (d *FileSystemDirectory) Sync() error

func (*FileSystemDirectory) Unlock

func (d *FileSystemDirectory) Unlock() error

type InMemoryDirectory

type InMemoryDirectory struct {
	// contains filtered or unexported fields
}

func NewInMemoryDirectory

func NewInMemoryDirectory() *InMemoryDirectory

func (*InMemoryDirectory) List

func (d *InMemoryDirectory) List(kind string) ([]uint64, error)

func (*InMemoryDirectory) Load

func (d *InMemoryDirectory) Load(kind string, id uint64) (*segment.Data, io.Closer, error)

func (*InMemoryDirectory) Lock

func (d *InMemoryDirectory) Lock() error

func (*InMemoryDirectory) Persist

func (d *InMemoryDirectory) Persist(kind string, id uint64, w WriterTo, closeCh chan struct{}) error

func (*InMemoryDirectory) Remove

func (d *InMemoryDirectory) Remove(kind string, id uint64) error

func (*InMemoryDirectory) Setup

func (d *InMemoryDirectory) Setup(_ bool) error

func (*InMemoryDirectory) Stats

func (d *InMemoryDirectory) Stats() (numItems, numBytes uint64)

func (*InMemoryDirectory) Sync

func (d *InMemoryDirectory) Sync() error

func (*InMemoryDirectory) Unlock

func (d *InMemoryDirectory) Unlock() error

func (*InMemoryDirectory) Volatile added in v1.70.0

func (d *InMemoryDirectory) Volatile() bool

Volatile reports that persisting to d keeps nothing past the process, so a batch need not wait for it: its segments are already searchable.

type KeepNLatestDeletionPolicy

type KeepNLatestDeletionPolicy struct {
	// contains filtered or unexported fields
}

func NewKeepNLatestDeletionPolicy

func NewKeepNLatestDeletionPolicy(n int) *KeepNLatestDeletionPolicy

func (*KeepNLatestDeletionPolicy) Cleanup

func (p *KeepNLatestDeletionPolicy) Cleanup(dir Directory) error

func (*KeepNLatestDeletionPolicy) Commit

func (p *KeepNLatestDeletionPolicy) Commit(snapshot *Snapshot)

type LoadMMapFunc

type LoadMMapFunc func(f lock.LockedFile) (*segment.Data, io.Closer, error)

type Mode added in v1.70.0

type Mode uint8

Mode selects how Writer.Batch turns documents into segments. Either way a batch is published atomically.

const (
	// IndexModeBatch analyzes the documents and builds them
	// into segments of up to BatchSegmentDocs documents. A Batch already
	// holds every document, so this is its cheapest mode; for bounded
	// memory, add documents through Writer.NewStream instead.
	IndexModeBatch Mode = iota
	// IndexModeStream, the default of DefaultConfig and its variants,
	// analyzes documents a block at a time and packs them into a compact
	// buffer, built into a segment every StreamMemoryBudget bytes, as
	// Stream does.
	IndexModeStream
)

type SegmentBuilder added in v1.70.0

type SegmentBuilder interface {
	Add(segment.Document) error
	Len() int
	Size() int // approximate heap use
	Build() (segment.Segment, uint64, error)
}

SegmentBuilder builds the segment New would build over the documents added, in order; Add does not keep the document.

type SegmentPlugin

type SegmentPlugin struct {
	Type    string
	Version uint32
	New     func(results []segment.Document, normCalc func(string, int) float32) (segment.Segment, uint64, error)
	Load    func(*segment.Data) (segment.Segment, error)
	Merge   func([]segment.Segment, []*roaring.Bitmap, int) segment.Merger
	// NewBuilder, when set, builds a segment from documents added one at
	// a time, so a Stream need not keep them; nil packs them for New.
	NewBuilder func(normCalc func(string, int) float32) SegmentBuilder
}

type SegmentSnapshot

type SegmentSnapshot interface {
	ID() uint64
	Deleted() *roaring.Bitmap
	DocNum() uint64
	SegmentSize() uint64
	Timestamp() (int64, int64)
}

type Snapshot

type Snapshot struct {
	// contains filtered or unexported fields
}

func OpenReader

func OpenReader(config Config) (*Snapshot, error)

func (*Snapshot) Backup

func (i *Snapshot) Backup(remote Directory, cancel chan struct{}) error

Backup writes the snapshot, its segments and their persisted HNSW graphs to remote. It is incremental: an item remote already holds with the same length and trailing checksum is skipped, so backing up into the same remote again sends only new segments and graphs, then the snapshot, which is written last. Persisted items are hard linked into a file system remote when possible, the rest is copied. Old items in remote are not removed.

func (*Snapshot) Close

func (i *Snapshot) Close() error

func (*Snapshot) CollectionStats

func (i *Snapshot) CollectionStats(field string) (segment.CollectionStats, error)

func (*Snapshot) Count

func (i *Snapshot) Count() (uint64, error)

func (*Snapshot) DictionaryIterator

func (i *Snapshot) DictionaryIterator(field string, automaton segment.Automaton, start, end []byte) (
	segment.DictionaryIterator, error)

func (*Snapshot) DictionaryLookup

func (i *Snapshot) DictionaryLookup(field string) (segment.DictionaryLookup, error)

func (*Snapshot) DocsMatchingRange added in v1.60.0

func (i *Snapshot) DocsMatchingRange(field string, automaton segment.Automaton, start, end []byte) (
	segment.PostingsIterator, error)

DocsMatchingRange is DocsMatchingTerms for every term in [start, end) that automaton accepts, ORed in one dictionary pass per segment. It returns nil when a segment cannot, so the caller must fall back.

func (*Snapshot) DocsMatchingTerms added in v1.60.0

func (i *Snapshot) DocsMatchingTerms(field string, terms [][]byte) (segment.PostingsIterator, error)

DocsMatchingTerms returns an unadorned iterator, without freq, norm or locations, over the live documents containing any of terms in field. The postings come straight from each segment dictionary and are ORed once per segment. It returns nil when a segment cannot expose its postings bitmaps, so the caller must fall back.

func (*Snapshot) DocumentValueReader

func (i *Snapshot) DocumentValueReader(fields []string) (
	segment.DocumentValueReader, error)

func (*Snapshot) Fields

func (i *Snapshot) Fields() ([]string, error)

func (*Snapshot) NumericRange added in v1.70.0

func (i *Snapshot) NumericRange(field string, lo, hi int64, loTerm, hiTermEnd []byte) (
	segment.PostingsIterator, error)

NumericRange returns an unadorned iterator over the live documents with a value of field in [lo, hi]. Each segment answers from its numeric column when it has one, else by ORing the exact-value terms [loTerm, hiTermEnd) from its dictionary. It returns nil when a segment can do neither, so the caller must fall back.

func (*Snapshot) PostingsIterator

func (i *Snapshot) PostingsIterator(term []byte, field string, includeFreq,
	includeNorm, includeTermVectors bool) (segment.PostingsIterator, error)

func (*Snapshot) ReadFrom

func (i *Snapshot) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads the snapshot payload. The directory loader validates the trailing CRC.

func (*Snapshot) SearchVectors

func (i *Snapshot) SearchVectors(ctx context.Context, field string, query []float32, k int,
	metric vec.Metric, accept func(uint64) bool) ([]vec.Match, error)

SearchVectors searches each segment with its deletion mask and selects the global top-k, ordered by descending score then ascending document number. Segments are searched concurrently. accept is optional and receives global snapshot-local numbers, never concurrently.

func (*Snapshot) SearchVectorsANN added in v1.30.0

func (i *Snapshot) SearchVectorsANN(ctx context.Context, field string, query []float32, k int,
	metric vec.Metric, params hnsw.Params, accept func(uint64) bool) ([]vec.Match, error)

SearchVectorsANN is the approximate counterpart of SearchVectors. Each segment is searched through an HNSW graph loaded from the directory or built from its stored vectors on first use, and cached for the segment's lifetime, keyed by field, metric and construction parameters. Deleted and rejected documents are filtered during graph traversal. Results may miss some true neighbors; scores are exact. accept is called serially unless params.ConcurrentAccept is set.

func (*Snapshot) Segments

func (i *Snapshot) Segments() []SegmentSnapshot

func (*Snapshot) Size

func (i *Snapshot) Size() int

func (*Snapshot) TermsIterator added in v1.60.0

func (i *Snapshot) TermsIterator(field string, automaton segment.Automaton, start, end []byte) (
	segment.DictionaryIterator, error)

TermsIterator is DictionaryIterator for callers that only need terms: entry counts are 0 wherever a segment can skip reading postings.

func (*Snapshot) VisitNumericBlocks added in v1.70.0

func (i *Snapshot) VisitNumericBlocks(field string, visitor func(base uint64, docs []uint64, vals []int64) error) error

VisitNumericBlocks is VisitNumericColumn a block at a time: docs holds the global doc numbers of vals, or is nil when they are base, base+1, ... Both slices are reused between calls.

func (*Snapshot) VisitNumericColumn added in v1.70.0

func (i *Snapshot) VisitNumericColumn(field string, visitor func(docNum uint64, value int64) error) error

VisitNumericColumn calls visitor with the global doc number and value of every live document holding field, scanning each segment's numeric column directly. It fails when a segment holding field has no numeric column.

func (*Snapshot) VisitStoredFields

func (i *Snapshot) VisitStoredFields(number uint64, visitor segment.StoredFieldVisitor) error

func (*Snapshot) WriteTo

func (i *Snapshot) WriteTo(w io.Writer, _ chan struct{}) (written int64, writeErr error)

type Stats

type Stats struct {
	TotUpdates uint64
	TotDeletes uint64

	TotBatches        uint64
	TotBatchesEmpty   uint64
	TotBatchIntroTime uint64
	MaxBatchIntroTime uint64

	CurRootEpoch       uint64
	LastPersistedEpoch uint64
	LastMergedEpoch    uint64

	TotOnErrors uint64

	TotAnalysisTime uint64
	TotIndexTime    uint64

	TotIndexedPlainTextBytes uint64

	TotTermSearchersStarted  uint64
	TotTermSearchersFinished uint64

	TotIntroduceLoop       uint64
	TotIntroduceSegmentBeg uint64
	TotIntroduceSegmentEnd uint64
	TotIntroducePersistBeg uint64
	TotIntroducePersistEnd uint64
	TotIntroduceMergeBeg   uint64
	TotIntroduceMergeEnd   uint64
	TotIntroduceRevertBeg  uint64
	TotIntroduceRevertEnd  uint64

	TotIntroducedItems         uint64
	TotIntroducedSegmentsBatch uint64
	TotIntroducedSegmentsMerge uint64

	TotPersistLoopBeg          uint64
	TotPersistLoopErr          uint64
	TotPersistLoopProgress     uint64
	TotPersistLoopWait         uint64
	TotPersistLoopWaitNotified uint64
	TotPersistLoopEnd          uint64

	TotPersistedItems    uint64
	TotItemsToPersist    uint64
	TotPersistedSegments uint64

	TotPersisterSlowMergerPause  uint64
	TotPersisterSlowMergerResume uint64

	TotPersisterNapPauseCompleted uint64
	TotPersisterMergerNapBreak    uint64

	TotFileMergeLoopBeg uint64
	TotFileMergeLoopErr uint64
	TotFileMergeLoopEnd uint64

	TotFileMergePlan     uint64
	TotFileMergePlanErr  uint64
	TotFileMergePlanNone uint64
	TotFileMergePlanOk   uint64

	TotFileMergePlanTasks              uint64
	TotFileMergePlanTasksDone          uint64
	TotFileMergePlanTasksErr           uint64
	TotFileMergePlanTasksSegments      uint64
	TotFileMergePlanTasksSegmentsEmpty uint64

	TotFileMergeSegmentsEmpty uint64
	TotFileMergeSegments      uint64
	TotFileSegmentsAtRoot     uint64
	TotFileMergeWrittenBytes  uint64

	TotFileMergeZapBeg              uint64
	TotFileMergeZapEnd              uint64
	TotFileMergeZapTime             uint64
	MaxFileMergeZapTime             uint64
	TotFileMergeZapIntroductionTime uint64
	MaxFileMergeZapIntroductionTime uint64

	TotFileMergeIntroductions          uint64
	TotFileMergeIntroductionsDone      uint64
	TotFileMergeIntroductionsSkipped   uint64
	TotFileMergeIntroductionsObsoleted uint64

	CurFilesIneligibleForRemoval     uint64
	TotSnapshotsRemovedFromMetaStore uint64

	TotMemMergeBeg          uint64
	TotMemMergeErr          uint64
	TotMemMergeDone         uint64
	TotMemMergeZapBeg       uint64
	TotMemMergeZapEnd       uint64
	TotMemMergeZapTime      uint64
	MaxMemMergeZapTime      uint64
	TotMemMergeSegments     uint64
	TotMemorySegmentsAtRoot uint64

	TotEventFired    uint64
	TotEventReturned uint64

	CurOnDiskBytes           uint64
	CurOnDiskBytesUsedByRoot uint64 // FIXME not currently supported
	CurOnDiskFiles           uint64
	// contains filtered or unexported fields
}

Stats tracks statistics about the index, fields that are prefixed like CurXxxx are gauges (can go up and down), and fields that are prefixed like TotXxxx are monotonically increasing counters.

type Stream added in v1.70.0

type Stream struct {
	// contains filtered or unexported fields
}

Stream indexes documents incrementally with bounded memory, like riot-go's IndexWriter: each document is analyzed and packed into a flat buffer, so its analysis objects are freed right away, and the buffer is built into a segment once it reaches the memory budget. With a persistent directory each such segment is written to its own file and memory-mapped right away, as Tantivy's writer does, so it holds no heap and Commit publishes it without rewriting it. Commit publishes every segment, and the deletions, as one snapshot, with the semantics of a single Batch. A Stream is not safe for concurrent use.

func (*Stream) Commit added in v1.70.0

func (st *Stream) Commit() error

Commit publishes everything added since the last Commit. On error the uncommitted work is discarded.

func (*Stream) Delete added in v1.70.0

func (st *Stream) Delete(id segment.Term)

Delete deletes the committed documents with id at Commit.

func (*Stream) Discard added in v1.70.0

func (st *Stream) Discard()

Discard drops everything added since the last Commit, and the files of its flushed segments.

func (*Stream) Insert added in v1.70.0

func (st *Stream) Insert(doc segment.Document) error

Insert adds doc; it is searchable after Commit. Nil documents are ignored. On error, everything added since the last Commit is discarded.

func (*Stream) Update added in v1.70.0

func (st *Stream) Update(id segment.Term, doc segment.Document) error

Update deletes the committed documents with id at Commit and inserts doc.

type VectorIndex added in v1.72.0

type VectorIndex struct {
	Field  string
	Metric vec.Metric
	Params hnsw.Params
}

VectorIndex declares an approximate search on Field. A search uses the prebuilt graph only with the same Metric, M, EfConstruction and Quantization; EfSearch and ConcurrentAccept do not matter.

type VectorStorage added in v1.50.0

type VectorStorage uint8

VectorStorage selects where the HNSW graphs of persisted segments keep their vectors. Either way, graphs of in-memory segments live on the heap and search returns exact scores.

const (
	// VectorStorageDisk, the default, persists each graph with its float32
	// vectors and int8 codes and memory-maps it, as Lucene does: opening
	// reads no vectors, and the OS page cache, not the Go heap, holds them.
	// Graph files take about 5 bytes more per dimension and vector.
	VectorStorageDisk VectorStorage = iota
	// VectorStorageMemory persists links only and reads the vectors from
	// the segment's stored fields onto the heap when a graph is opened.
	VectorStorageMemory
)

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

func OpenWriter

func OpenWriter(config Config) (*Writer, error)

func (*Writer) Batch

func (s *Writer) Batch(batch *Batch) (err error)

Batch applies a batch of changes to the index atomically, building the documents into segments as Config.IndexMode selects.

func (*Writer) Close

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

func (*Writer) DirectoryStats

func (s *Writer) DirectoryStats() (numItems, numBytes uint64)

DirectoryStats returns the directory's total item count and cumulative size in bytes.

func (*Writer) MemoryUsed

func (s *Writer) MemoryUsed() (memUsed uint64)

func (*Writer) NewStream added in v1.70.0

func (s *Writer) NewStream(memoryBudget int) *Stream

NewStream returns a Stream over s that flushes at memoryBudget bytes of packed documents; a non-positive budget uses Config.StreamMemoryBudget, or DefaultStreamMemoryBudget when that is not positive either.

func (*Writer) Reader

func (s *Writer) Reader() (*Snapshot, error)

Reader returns a low-level accessor on the index data. Close it to release associated resources.

func (*Writer) Stats

func (s *Writer) Stats() Stats

Stats returns a race-safe snapshot. Fields are sampled independently, not as a single point-in-time view of the index.

type WriterOffline

type WriterOffline struct {
	// contains filtered or unexported fields
}

func OpenOfflineWriter

func OpenOfflineWriter(config Config) (writer *WriterOffline, err error)

func (*WriterOffline) Batch

func (s *WriterOffline) Batch(batch *Batch) (err error)

func (*WriterOffline) Close

func (s *WriterOffline) Close() error

type WriterTo

type WriterTo interface {
	WriteTo(w io.Writer, closeCh chan struct{}) (n int64, err error)
}

WriterTo is like io.WriterTo only it can be canceled by closing the closeCh

Directories

Path Synopsis
Package mergeplan provides a segment merge planning approach that's inspired by Lucene's TieredMergePolicy.java and descriptions like http://blog.mikemccandless.com/2011/02/visualizing-lucenes-segment-merges.html
Package mergeplan provides a segment merge planning approach that's inspired by Lucene's TieredMergePolicy.java and descriptions like http://blog.mikemccandless.com/2011/02/visualizing-lucenes-segment-merges.html

Jump to

Keyboard shortcuts

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