Go · Scans

Scans

import "github.com/unum-cloud/ustore" 1.0.0-rc.1 · 084197c4

Ask your coding agent about this page, or add the docs server to it

curl -s 'https://www.unum.cloud/docs/ustore/go/scans.md' | claude -p "How would this fit my code?"

Scans, samples and measures run one task per collection their Collections names, from a start key, inclusive, towards an end key, exclusive, in a ScanDirection. BlobsScan lists up to the count it wants, BlobsSample draws keys at random, and BlobsMeasure bounds the keys and bytes a range holds without walking it; DocsScan, PagesScan, StringsScan and GraphScanVertices serve the other modalities. A start key of Key{} walks up from the first key, and KeyUnknown walks down from the last. A cursor walks one collection page by page, each pull resuming past the last key the one before it handed out, and a page shorter than wanted exhausts it for good. ChangesCursorInit opens a feed of the changes committed after a CommitStamp, oldest first, pinning that stamp as a snapshot does. A cursor keeps no executor: cursor.NextPairs(..) pulls on the calling goroutine, and cursor.On(executor).NextPairs(..) blocks on the executor named for that pull. A DocsCursor gathers the Fields of its config into typed columns, and its Next answers DocsBatches, one batch of keys and columns per executor task that found rows, none once the walk is exhausted.

first, err := database.BlobsScan(people, 100, arena, nil)
measured, err := database.BlobsMeasure(people, arena, &ustore.MeasureConfig{StartKeys: []ustore.Key{ada}, EndKeys: []ustore.Key{kent}})
last, err := database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{
	StartKeys: []ustore.Key{ustore.KeyUnknown}, Direction: ustore.ScanDescending,
})

cursor, err := database.On(executor).BlobsCursorInit(people, ustore.Key{}, nil)
defer cursor.Close()
for {
	page, err := cursor.On(executor).NextPairs(1024, arena)
	if err != nil || page.Len() < 1024 {
		break
	}
}

ages, err := database.DocsCursorInit(people, ustore.Key{}, &ustore.DocsCursorConfig{
	Fields: ustore.TapeOf("age"), ColumnsTypes: []ustore.DocsFieldType{ustore.DocsFieldTypeU64},
})
defer ages.Close()
batches, err := ages.On(executor).Next(1024, arena) // batches.Keys(i) and batches.Columns(i) per batch

§ Progress and Cancellation

The configs of Compact, Save, PagesImport and the scans carry an optional ProgressCallback, called with the units finished and the units in all, never on two threads at once and never after the call is final. Answering false cancels the call, which fails with StatusCancelled and publishes nothing, a cancelled save removing what it wrote. A handler must not panic, since unwinding through the library’s C frames aborts the process.

deadline := time.Now().Add(30 * time.Second)
beforeTheDeadline := func(finished, total uint64) bool { return time.Now().Before(deadline) }
err := snapshot.Save("/var/lib/people-copy", beforeTheDeadline)
if errors.Is(err, ustore.StatusCancelled) {
	fmt.Println("the copy was removed")
}

The Predicate field of a scan or cursor config admits or passes over the keys it lists, asked on the host, and its type tells the library what one call costs:

  • ustore.Predicate answers one key at a time, asked before patterns or filters read any value.
  • ustore.BatchPredicate answers a page of keys at once, asked about the keys patterns and filters kept, for handlers that pay per call.
  • ustore.CheapBatchPredicate answers a page of keys at once, asked before patterns or filters read any value.
odd := ustore.Predicate(func(key ustore.Key) bool { return key[15]%2 == 1 })
found, err := database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{Predicate: odd})

moderated := ustore.BatchPredicate(func(keys []ustore.Key, admissions []ustore.Admission) {
	for position, allowed := range moderation.Check(keys) { // one round trip for the whole page
		if allowed {
			admissions[position] = ustore.Admit
		}
	}
})
found, err = database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{Predicate: moderated})

Admissions start as ustore.Reject, and both slices live only until the handler returns.

API

Types

AdmissionAdmission is whether a predicate keeps a listed key or passes over it.
db.go:465 ↗
type Admission int32

Values

RejectReject passes over the key.
AdmitAdmit keeps the key among the listed ones.
AdmitterAdmitter is the predicate a scan or a cursor asks about the keys it lists: a Predicate, a BatchPredicate or a CheapBatchPredicate, whose type tells the library what one call costs.
db.go:443 ↗
type Admitter interface {
    // contains filtered or unexported methods
}
BatchPredicateBatchPredicate writes an Admission for every key into admissions, which start as Reject, for handlers that pay per call: it is asked once per page about every key patterns and filters kept.
db.go:458 ↗
type BatchPredicate func(keys []Key, admissions []Admission)

Both slices live only until it returns. The executor's threads may ask it at once, so it must be safe to call from several goroutines concurrently, and it must not panic.

BlobsCursorConfigBlobsCursorConfig carries the optional arguments of DatabaseOn.BlobsCursorInit.
db.go:383 ↗
type BlobsCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Patterns Patterns
    Predicate Admitter
}

Fields

EndKey*KeyEndKey is the key the walk stops before, or nil for no bound.
DirectionScanDirectionDirection is which way the walk goes from its start.
PatternsPatternsPatterns keep the keys whose values match, compiled once.
PredicateAdmitterPredicate admits or passes over the keys of every page.
CheapBatchPredicateCheapBatchPredicate is a BatchPredicate asked once per page before patterns or filters read any value, so it narrows those reads.
db.go:462 ↗
type CheapBatchPredicate func(keys []Key, admissions []Admission)
DocsCursorConfigDocsCursorConfig carries the optional arguments of DatabaseOn.DocsCursorInit.
db.go:548 ↗
type DocsCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
    Fields Tape
    ColumnsTypes []DocsFieldType
}

Fields

EndKey*KeyEndKey is the key the walk stops before, or nil for no bound.
DirectionScanDirectionDirection is which way the walk goes from its start.
FilterstringFilter is a JSONPath every document the walk hands out matches, compiled once.
PredicateAdmitterPredicate admits or passes over the keys of every page.
FieldsTapeFields are the fields every pull gathers into the columns of its batches, the empty field being the whole document, or none for keys alone.
ColumnsTypes[]DocsFieldTypeColumnsTypes holds the type every field converts into, one per field.
DocsScanConfigDocsScanConfig carries the optional arguments of DatabaseOn.DocsScan.
db.go:473 ↗
type DocsScanConfig struct {
    StartKeys []Key
    EndKeys []Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
    Mode ScanMode
    Progress ProgressCallback
}

Fields

StartKeys[]KeyStartKeys are the inclusive starts of the scans, one per task, or the first key in Direction when empty.
EndKeys[]KeyEndKeys are the keys every scan stops before, one per task, or no bound when empty.
DirectionScanDirectionDirection is which way every scan goes from its start.
FilterstringFilter is a JSONPath, or a bare root filter such as ?@.age>30, every listed document matches.
PredicateAdmitterPredicate admits or passes over the listed keys.
ModeScanModeMode is in what order the keys come.
ProgressProgressCallbackProgress reports the scans finished, and may cancel the call.
EachEach names one collection per task of a batch.
db.go:154 ↗
type Each []CollectionID
MeasureConfigMeasureConfig carries the optional arguments of a measure.
db.go:110 ↗
type MeasureConfig struct {
    StartKeys []Key
    EndKeys []Key
    Direction ScanDirection
}

Fields

StartKeys[]KeyStartKeys are the inclusive starts of the ranges, one per task, or the first key in Direction when empty.
EndKeys[]KeyEndKeys are the keys every range stops before, one per task, or no bound when empty.
DirectionScanDirectionDirection is which way every range goes from its start.
MeasuredMeasured is the bounds on the entries and the space one range holds.
db.go:134 ↗
type Measured struct {
    MinCardinality, MaxCardinality uint64
    MinValueBytes, MaxValueBytes   uint64
    MinSpaceUsage, MaxSpaceUsage   uint64
}
PagesCursorConfigPagesCursorConfig carries the optional arguments of DatabaseOn.PagesCursorInit.
db.go:577 ↗
type PagesCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
}

Fields

EndKey*KeyEndKey is the key the walk stops before, or nil for no bound.
DirectionScanDirectionDirection is which way the walk goes from its start.
FilterstringFilter is the expression every page the walk hands out matches, compiled once.
PredicateAdmitterPredicate admits or passes over the keys of every page.
PatternsPatterns keeps the values or strings a scan or a walk lists to the ones matching, shared by every task of the call; the zero value matches everything.
db.go:620 ↗
type Patterns struct {
    Patterns Tape
    Kind PatternKind
    Sensitivity CaseSensitivity
    Weights []float32
}

Fields

PatternsTapePatterns are the expressions or substrings to match.
KindPatternKindKind is what the patterns are matched as.
SensitivityCaseSensitivitySensitivity is whether matching folds case.
Weights[]float32Weights holds one weight per substring pattern, which turns on BM25 scores, or nothing.
PredicatePredicate admits one listed key into a scan or a walk, or passes over it, asked once per page before patterns or filters read any value.
db.go:452 ↗
type Predicate func(key Key) bool

The executor's threads may ask it at once, so it must be safe to call from several goroutines concurrently, and it must not panic.

EnumCaseSensitivityCaseSensitivity is whether patterns compare bytes as they are or after Unicode case folding.2
types.go:257 ↗
type CaseSensitivity int32

Values

CasedCased compares bytes as they are.
UncasedUncased folds the case of both the patterns and the values.
CaseSensitivityFromNameCaseSensitivityFromName reads a case sensitivity back from the spelling CaseSensitivity.String renders.
types.go:273 ↗
func CaseSensitivityFromName(name string) (CaseSensitivity, error)
StringString renders the case sensitivity as the library spells it.
types.go:267 ↗
func (sensitivity CaseSensitivity) String() string
EnumChangeKindChangeKind is what one committed change did to its key.2
db.go:392 ↗
type ChangeKind int32

Values

ChangeWriteChangeWrite wrote the whole value.
ChangeRemovalChangeRemoval removed the key.
ChangeChangeChangeChange changed part of the value, as a document patch or a page edit does.
ChangeKindFromNameChangeKindFromName reads a change kind back from the spelling ChangeKind.String renders.
db.go:409 ↗
func ChangeKindFromName(name string) (ChangeKind, error)
StringString renders the change kind as the library spells it.
db.go:404 ↗
func (kind ChangeKind) String() string
StructChangesChanges is one pull of a feed, written into its arena and readable until the arena serves another call.5
db.go:1858 ↗
type Changes struct {
    // contains filtered or unexported fields
}
KeyKey reports the key change index touched.
db.go:1871 ↗
func (changes Changes) Key(index uint) Key
KindKind reports what change index did to its key.
db.go:1885 ↗
func (changes Changes) Kind(index uint) ChangeKind
LenLen reports how many changes the pull yielded, zero at the newest commit.
db.go:1868 ↗
func (changes Changes) Len() uint
StampStamp reports the commit change index landed at.
db.go:1878 ↗
func (changes Changes) Stamp(index uint) CommitStamp
ValueValue views the bytes change index carries in the arena, empty for a removal and for a pull through ChangesCursor.NextKeys.
db.go:1893 ↗
func (changes Changes) Value(index uint) []byte
StructMeasurementMeasurement is the bounds a measure estimated, one per range, readable until the arena serves another call.2
blobs.go:122 ↗
type Measurement struct {
    // contains filtered or unexported fields
}
GetGet reports the bounds of range index.
blobs.go:144 ↗
func (measurement Measurement) Get(index uint) Measured
LenLen reports how many ranges the call measured.
blobs.go:141 ↗
func (measurement Measurement) Len() uint
StructPagePage is one pull of a walk, written into its arena and readable until the arena serves another call.3
db.go:1780 ↗
type Page struct {
    // contains filtered or unexported fields
}
KeysKeys views the keys of the page in the arena.
db.go:1791 ↗
func (page Page) Keys() []Key
LenLen reports how many keys the pull handed out; fewer than wanted exhausts the walk for good.
db.go:1788 ↗
func (page Page) Len() uint
ValuesValues views the values of the page in the arena, one per key, empty for a keys-only pull.
db.go:1798 ↗
func (page Page) Values() Strings
EnumPatternKindPatternKind is what the strings of Patterns are matched as.2
types.go:235 ↗
type PatternKind int32

Values

PatternRegexPatternRegex matches regular expressions, of which a value matches at least one somewhere.
PatternSubstringsPatternSubstrings matches literal substrings, found together through Aho-Corasick.
PatternKindFromNamePatternKindFromName reads a pattern kind back from the spelling PatternKind.String renders.
types.go:250 ↗
func PatternKindFromName(name string) (PatternKind, error)
StringString renders the pattern kind as the library spells it.
types.go:245 ↗
func (kind PatternKind) String() string
EnumScanDirectionScanDirection is which way a scan, a walk or a measure goes from its start key.2
db.go:286 ↗
type ScanDirection int32

Values

ScanAscendingScanAscending walks up from the start key, the default.
ScanDescendingScanDescending walks down from the start key.
ScanDirectionFromNameScanDirectionFromName reads a direction back from the spelling ScanDirection.String renders.
db.go:301 ↗
func ScanDirectionFromName(name string) (ScanDirection, error)
StringString renders the direction as the library spells it.
db.go:296 ↗
func (direction ScanDirection) String() string
EnumScanModeScanMode is in what order a scan hands its keys over.2
db.go:264 ↗
type ScanMode int32

Values

ScanOrderedScanOrdered hands keys over in their order.
ScanUnorderedScanUnordered hands keys over in any order, as fast as the engine finds them.
ScanModeFromNameScanModeFromName reads a scan mode back from the spelling ScanMode.String renders.
db.go:279 ↗
func ScanModeFromName(name string) (ScanMode, error)
StringString renders the scan mode as the library spells it.
db.go:274 ↗
func (mode ScanMode) String() string
StructScannedScanned is what a batch of scans or samples wrote into its arena, keys scan after scan, readable until the arena serves another call.3
blobs.go:79 ↗
type Scanned struct {
    // contains filtered or unexported fields
}
KeysKeys views the keys scan task found in the arena.
blobs.go:91 ↗
func (scanned Scanned) Keys(task uint) []Key
LenLen reports how many scans or samples the call ran.
blobs.go:88 ↗
func (scanned Scanned) Len() uint
ScoresScores views the BM25 score of every key scan task found, and nothing unless the patterns carried weights.
blobs.go:99 ↗
func (scanned Scanned) Scores(task uint) []float32