ruleix

package module
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 13 Imported by: ? modules, 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

ruleix

ruleix is a strongly typed, in-memory rule index for Go. Given a concrete value, it efficiently finds all stored rules whose constraints match that value.

Use it when you have many rules with optional fields—for example pricing, feature flags, promotions, routing, or audience targeting—and need to evaluate the same schema repeatedly.

The problem

Rule-based systems often need to answer the inverse of a typical lookup: given one concrete value, find all stored rules whose optional constraints match it.

In SQL terms, a lookup with optional geographic constraints might resemble:

SELECT *
FROM rules
WHERE (store_id = $1 OR store_id IS NULL)
  AND (region_id = $2 OR region_id IS NULL)
  AND (district_id = $3 OR district_id IS NULL);

Here, NULL in a stored rule acts as a wildcard: the rule matches any concrete value for that field. Queries with several such conditions can make efficient use of conventional database indexes difficult.

A straightforward in-memory implementation scans every rule for every request and checks each field individually. Its cost grows with both the number of rules and the number of fields, especially when rules contain wildcards, ranges, exclusions, or nested properties.

ruleix builds an immutable index from the rules once. Searches then combine precomputed candidate sets for each constraint instead of evaluating every rule from scratch.

Features

  • Generic, strongly typed API with no reflection.
  • Equality, exclusion, ordered, interval, and dynamic comparison filters.
  • Wildcards: a getter returning ok == false matches every concrete value.
  • Multi-column rules composed with All and direct nested getters.
  • Unique results in first-insertion order.
  • Immutable indexes safe for concurrent searches after Build.
  • Roaring bitmap-backed candidate sets with pooled search scratch space.
  • Opt-in planner diagnostics without instrumentation on ordinary searches.

Requirements

  • Go 1.23 or newer.

Installation

go get github.com/typomaker/ruleix

Quick start

This example indexes rules across four different columns: country, customer tier, minimum order total, and an excluded sales channel.

package main

import (
	"cmp"
	"fmt"

	"github.com/typomaker/ruleix"
)

type Constraint struct {
	Country         *string
	Tier            *string
	MinimumTotal    *int
	ExcludedChannel *string
}

func pointer[T any](value T) *T { return &value }
func optional[T any](value *T) (T, bool) {
	if value == nil {
		var zero T
		return zero, false
	}
	return *value, true
}

func main() {
	schema := ruleix.All(
		ruleix.Include(func(c Constraint) (string, bool) { return optional(c.Country) }),
		ruleix.Include(func(c Constraint) (string, bool) { return optional(c.Tier) }),
		ruleix.GreaterOrEqual(func(c Constraint) (int, bool) { return optional(c.MinimumTotal) }, cmp.Compare[int]),
		ruleix.Exclude(func(c Constraint) (string, bool) { return optional(c.ExcludedChannel) }),
	)

	constraints := []Constraint{
		{
			Country:         pointer("DE"),
			Tier:            pointer("gold"),
			MinimumTotal:    pointer(100),
			ExcludedChannel: pointer("marketplace"),
		},
		{Country: pointer("DE")},
		{},
	}
	ids := []string{"gold-de", "all-de", "global"}

	entries := ruleix.Zip(constraints, ids)
	index, err := ruleix.New[Constraint, string](schema).Build(entries)
	if err != nil {
		panic(err)
	}

	query := Constraint{
		Country:         pointer("DE"),
		Tier:            pointer("gold"),
		MinimumTotal:    pointer(150),
		ExcludedChannel: pointer("web"),
	}
	var matches []string
	index.Search(query, &matches)

	fmt.Println(matches)
	// Output: [gold-de all-de global]
}

A runnable version is available in examples/multiple_columns.

There is also an example combining an interval with a strict > comparison in examples/between_and_gt. It uses CompareBy to choose the comparison operator from each stored constraint; for a fixed operator, use Greater or Less directly.

Filters

Filter Stored constraint matches when
Include query value equals the stored value
Exclude query value does not equal the stored forbidden value
GreaterOrEqual query value is greater than or equal to the stored value
LessOrEqual query value is less than or equal to the stored value
Greater query value is greater than the stored value
Less query value is less than the stored value
Between the query interval is fully covered by the stored interval
CompareBy the operator stored with the constraint evaluates to true
All every child rule matches

Memory-sensitive equality, ordered, Between, and CompareBy rules can opt into a bounded, conservative representation. The exact representation is retained when it fits; otherwise results may include false positives but never omit an exact match. Built-in terminal representations also let heterogeneous All schemas use one aggregate limit. Ordered rules use comparator-defined rounded boundaries, while equality rules compile a semantic hash codec during Build; a type that cannot receive a safe codec is rejected instead of silently becoming a complete candidate bitmap:

ruleix.Lossy(
	ruleix.Include(customerID),
	ruleix.MemoryLimit(20<<20),
)

One limit can cover an entire conjunction. The build keeps every child exact when their combined accounted size fits. Under pressure it applies one supported discrete downgrade at a time, preferring the step that releases the most bytes, then the larger current leaf, then schema order, and stops as soon as the total fits. Smaller leaves therefore remain exact when they do not need to change:

ruleix.Lossy(
	ruleix.All(ruleix.Include(customerID), ruleix.GreaterOrEqual(minimumTotal, cmp.Compare[int])),
	ruleix.MemoryLimit(20<<20),
)

Lossy policies may nest. A nested limit is a local cap, while every ancestor also caps its complete subtree; an ancestor may force a coarser representation but cannot grant more than the local limit. Planning is repeated from the current input on every Build. If all minimum viable representations still exceed any applicable limit, Build returns an error and does not publish the failed index or its diagnostics.

Equality level 0 stores the original comparable value and uses Go map equality without hashing it in Ruleix code. Under memory pressure, the first downgrade uses the compiled semantic codec to replace equalityIndex[V] with equalityIndex[uint64]; later levels clear more low bits so equal rounded integers share one posting list. Codecs cover built-in and named scalars, byte arrays such as UUIDs, recursive arrays, comparable structs, complex values, pointer and channel identity, and time.Time. Interfaces are rejected because their dynamic values cannot be encoded safely without query-time dispatch.

Lossy build planning is streaming. At fixed checkpoints, accounted exact state above a private 125% pressure target advances an equality integer level or rebuilds an ordered index by merging adjacent keys. Later ordered values join the nearest outward current key or remain a new open-edge key. This prevents the builder from retaining the complete input as exact leaf state before compression. Low-cardinality exact leaves selected by the aggregate planner may remain exact, while pressured high-cardinality leaves release their exact maps and ordered values. The published index contains the ordinary lossy search types, not a streaming wrapper. MemoryLimit is a hard limit on Ruleix's final deterministic retained accounting, not on transient Go heap or RSS.

All getters return (value, ok). In a stored constraint, ok == false is a wildcard. In a search value it only matches stored wildcards. For Exclude, ok == false means that no value is forbidden. Zero values remain concrete when returned with ok == true.

Between applies the following rule; either stored bound may be a wildcard:

stored.from <= query.from AND query.until <= stored.until

CompareBy supports the typed OperatorEQ, OperatorLT, OperatorLTE, OperatorGT, and OperatorGTE constants. Its value accessor is used for both stored constraints and queries, while its operator accessor is used only when building stored constraints. The operator present in a query is ignored. A non-wildcard stored constraint must have a valid operator. A missing query value matches only stored wildcards. Nested fields are read directly:

ruleix.Include(func(c Constraint) (int, bool) {
	if c.Platform == nil || c.Platform.Version == nil {
		return 0, false
	}
	return c.Platform.Version.Major, true
})

Building an index

New returns a reusable builder. Build accepts an iter.Seq2 of constraints and result IDs:

index, err := ruleix.New[Constraint, string](schema).Build(
	func(yield func(Constraint, string) bool) {
		for _, row := range source {
			if !yield(row.Constraint, row.ID) {
				return
			}
		}
	},
)

Zip is a convenience for parallel slices and panics when their lengths differ.

For workloads that periodically rebuild the same schema, keep the builder and call Build again. Every call creates independent mutable build state and returns a new immutable index; indexes returned earlier remain safe for concurrent searches. Build itself is not safe for concurrent calls on the same builder: callers must provide synchronization when they need parallel build coordination. A failed build does not prevent the next call:

builder := ruleix.New[Constraint, string](schema)
first, err := builder.Build(firstEntries)
second, err := builder.Build(secondEntries)

Searching

Search appends matches to a destination slice, allowing callers to accumulate results across searches. Reset the slice explicitly when previous results are not needed:

var matches []string
if index.Search(value, &matches) {
	fmt.Println("matched", matches)
}

matches = matches[:0]
index.Search(anotherValue, &matches)

Search returns true when the current call finds at least one match. Elements already present in the destination slice do not affect the return value.

The proposed design for a separate ranked-result layer and its Search and Match signatures is recorded in docs/rankix.md.

When adjacent searches repeat constraint values, Local can reuse intermediate bitmap results from Include, Greater, GreaterOrEqual, Less, LessOrEqual, CompareBy, Between, and Exclude filters. For example, queries for the same store and different regions can reuse the store bitmap:

local := index.Local()
defer local.Close()

queries := []Constraint{
	{StoreUUID: pointer("store-10"), RegionID: pointer(20)},
	{StoreUUID: pointer("store-10"), RegionID: pointer(30)},
}
for _, query := range queries {
	matches = matches[:0]
	local.Search(query, &matches)
	fmt.Println(matches)
}

Local initially keeps up to two recent intermediate bitmaps per filter node. Value-based caches can grow to four after repeated misses prove that a larger working set is being reused; one-off values never cause bitmap growth. This keeps memory bounded while covering repeated, alternating, and small cyclic workloads. Call local.Close() when the worker is done. It releases cached query values and returns the internal bitmap context to this index for reuse. A closed Local cannot be used again.

A local search context is not safe for concurrent use. Create one inside each goroutine while sharing the immutable index:

for range workers {
	go func() {
		local := index.Local()
		defer local.Close()
		var matches []string
		for query := range jobs {
			matches = matches[:0]
			local.Search(query, &matches)
			handle(matches)
		}
	}()
}

Use index.Search when searches do not have value locality or when maintaining a per-goroutine context is inconvenient. The index and its regular Search method remain safe for concurrent use. Local.Visit provides the same caching for streaming result iteration.

A complete runnable example is available in examples/local_search.

Visit avoids collecting results and supports early termination:

index.Visit(value, func(id string) bool {
	return handle(id) // false stops iteration
})

If the same external ID is inserted more than once, it is returned at most once. Its first matching insertion determines result order.

Rule diagnostics

Inspect can mark one rule and report the representation selected during Build. For a Lossy policy it exposes accounted subtree usage, the effective MemoryLimit after ancestor caps, selected exact/lossy mode, item and distinct-value counts, and physical key granularity when applicable. Optional metrics return an availability flag. Call Snapshot once to capture one successful build generation and its observed runtime counters. Runtime counters are low-priority samples: shared Index searches and 63 of every 64 Local contexts execute the plain tree without instrumentation. The selected Local accumulates candidate checks, empty results, cache activity, adaptive cache expansions, and an allocation-free result-cardinality histogram without atomics, then publishes them on Close. Snapshots are monotonic but do not represent total workload activity and exclude selected Local contexts that are still open.

Development

go test ./...
go vet ./...

Documentation

Overview

Package ruleix implements a strongly typed in-memory rule index.

Example (MultiColumnRules)
package main

import (
	"cmp"
	"fmt"

	"github.com/typomaker/ruleix"
)

func main() {
	type targetingConstraint struct {
		country         *string
		tier            *string
		minimumTotal    *int
		excludedChannel *string
	}

	schema := ruleix.All(
		ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.country })),
		ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.tier })),
		ruleix.GreaterOrEqual(ruleix.GetterFromPointer(func(c targetingConstraint) *int { return c.minimumTotal }), cmp.Compare[int]),
		ruleix.Exclude(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.excludedChannel })),
	)

	countryDE := "DE"
	tierGold := "gold"
	minimum100 := 100
	marketplace := "marketplace"
	constraints := []targetingConstraint{
		{
			country:         &countryDE,
			tier:            &tierGold,
			minimumTotal:    &minimum100,
			excludedChannel: &marketplace,
		},
		{country: &countryDE},
		{},
	}
	ids := []string{"gold-de", "all-de", "global"}

	entries := ruleix.Zip(constraints, ids)
	index, err := ruleix.New[targetingConstraint, string](schema).Build(entries)
	if err != nil {
		panic(err)
	}

	minimum150 := 150
	web := "web"
	query := targetingConstraint{
		country:         &countryDE,
		tier:            &tierGold,
		minimumTotal:    &minimum150,
		excludedChannel: &web,
	}
	var matches []string
	index.Search(query, &matches)
	fmt.Println(matches)

}
Output:
[gold-de all-de global]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Zip

func Zip[C any, ID any](constraints []C, ids []ID) iter.Seq2[C, ID]

Zip pairs equally sized constraint and ID slices into a sequence accepted by Builder.Build. It panics when the slice lengths differ. The slices are read when the returned sequence is consumed, not when Zip is called.

Types

type Builder

type Builder[C any, ID comparable] struct {
	// contains filtered or unexported fields
}

Builder constructs immutable indexes from the same Rule schema. A Builder is not safe for concurrent calls to Build; callers that need them must provide their own synchronization. Indexes returned by completed builds are independent and safe for concurrent use.

func New

func New[C any, ID comparable](schema Rule[C]) *Builder[C, ID]

New constructs a Builder from a strongly typed rule schema. New panics when schema is nil.

func (*Builder[C, ID]) Build

func (b *Builder[C, ID]) Build(entries iter.Seq2[C, ID]) (*Index[C, ID], error)

Build consumes entries and returns an immutable, concurrently searchable Index. Constraints that share an external ID are combined under that ID, which is returned at most once by a search. Build must not be called concurrently on the same Builder; the library deliberately leaves synchronization of builds to the caller. A failed build does not prevent later calls.

type Compare

type Compare[V any] func(a, b V) int

Compare defines an ordering for values used by ordered filters. It returns a negative number when a < b, zero when a == b, and a positive number when a > b. Compare must define a stable, transitive total order for every value supplied during Build and Search. The standard library's cmp.Compare is suitable for ordered types.

type Getter

type Getter[T, V any] func(T) (V, bool)

Getter returns a value and reports whether it is present. A missing value is interpreted as a wildcard by filters. The boolean keeps zero values distinct from missing values without requiring pointers or heap allocations.

func GetterFromPointer

func GetterFromPointer[T, V any](get func(T) *V) Getter[T, V]

GetterFromPointer adapts an old pointer getter during migration. New schemas should return (value, ok) directly to avoid pointers to temporary values.

type Histogram

type Histogram struct {
	Zero, One, TwoToFour, FiveToSixteen, SeventeenTo256, Above256 uint64
}

Histogram groups observed values into stable, allocation-free bins. Each bin includes its lower bound and excludes the next bin's lower bound.

type Index

type Index[C any, ID comparable] struct {
	// contains filtered or unexported fields
}

Index maps query values to the unique IDs of all matching stored constraints. It is immutable after Build and safe for concurrent calls to Search and Visit.

func (*Index[C, ID]) Local

func (ix *Index[C, ID]) Local() *Local[C, ID]

Local returns a search context that initially caches up to two recently repeated intermediate bitmap results per filter node and can adapt to four for a repeatedly reused working set. A value is admitted after its second recent use, so one-off queries do not retain their result bitmaps. It can reduce repeated work when adjacent searches share constraint values, at the cost of retaining admitted bitmaps for the lifetime of the Local.

A Local is not safe for concurrent use. Create one per goroutine:

local := index.Local()
var matches []ID
for value := range values {
	local.Search(value, &matches)
}

Call Close when the context is no longer needed so its internal resources can be reused. The Index remains immutable and may be shared by all of those goroutines.

Example
package main

import (
	"fmt"

	"github.com/typomaker/ruleix"
)

func main() {
	type constraint struct {
		store  *int
		region *int
	}
	pointer := func(value int) *int { return &value }

	entries := ruleix.Zip(
		[]constraint{
			{},
			{store: pointer(10)},
			{store: pointer(10), region: pointer(20)},
			{store: pointer(10), region: pointer(30)},
		},
		[]string{"global", "store", "region-20", "region-30"},
	)
	index, err := ruleix.New[constraint, string](ruleix.All(
		ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.store })),
		ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.region })),
	)).Build(entries)
	if err != nil {
		panic(err)
	}

	// Local caches intermediate bitmaps between calls. Keep it in one goroutine.
	local := index.Local()
	defer local.Close()
	var matches []string
	for _, region := range []int{20, 30} {
		matches = matches[:0]
		local.Search(constraint{store: pointer(10), region: pointer(region)}, &matches)
		fmt.Println(matches)
	}

}
Output:
[global store region-20]
[global store region-30]

func (*Index[C, ID]) Search

func (ix *Index[C, ID]) Search(value C, dst *[]ID) bool

Search appends the unique IDs of every stored rule matching value to dst, reports whether this call found any matches, and updates the slice through its pointer if append allocates a larger backing array. Existing elements in dst do not affect the reported result. Results preserve first-insertion order. Search panics when dst is nil.

func (*Index[C, ID]) Visit

func (ix *Index[C, ID]) Visit(value C, yield func(ID) bool)

Visit calls yield once for each unique matching ID in first-match order. Iteration stops immediately when yield returns false. A nil yield function is a no-op.

type Inspector

type Inspector interface {
	Snapshot() InspectorSnapshot
	// contains filtered or unexported methods
}

Inspector captures immutable views of one rule's compiled representation and accumulated runtime metrics. Inspect selects and assigns the implementation when it decorates a rule.

type InspectorSnapshot

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

InspectorSnapshot is a coherent view of the build generation selected by one Snapshot call and the runtime counters observed during that call.

func (InspectorSnapshot) Bound

func (s InspectorSnapshot) Bound() bool

Bound reports whether the snapshot belongs to a successful build.

func (InspectorSnapshot) CacheAdmission

func (s InspectorSnapshot) CacheAdmission() uint64

CacheAdmission reports observed cache admissions.

func (InspectorSnapshot) CacheEviction

func (s InspectorSnapshot) CacheEviction() uint64

CacheEviction reports observed cache evictions.

func (InspectorSnapshot) CacheExpansion

func (s InspectorSnapshot) CacheExpansion() uint64

CacheExpansion reports observed adaptive cache capacity expansions.

func (InspectorSnapshot) CacheHit

func (s InspectorSnapshot) CacheHit() uint64

CacheHit reports observed cache hits.

func (InspectorSnapshot) CacheMiss

func (s InspectorSnapshot) CacheMiss() uint64

CacheMiss reports observed cache misses.

func (InspectorSnapshot) CandidateCheck

func (s InspectorSnapshot) CandidateCheck() uint64

CandidateCheck reports observed direct internal-ID membership checks.

func (InspectorSnapshot) DistinctValueCount

func (s InspectorSnapshot) DistinctValueCount() (uint64, bool)

DistinctValueCount reports indexed concrete values, excluding wildcards.

func (InspectorSnapshot) EmptyResult

func (s InspectorSnapshot) EmptyResult() uint64

EmptyResult reports observed empty results.

func (InspectorSnapshot) EntryCount

func (s InspectorSnapshot) EntryCount() uint64

EntryCount reports the number of input entries consumed by the build.

func (InspectorSnapshot) FalsePositiveRate

func (s InspectorSnapshot) FalsePositiveRate() (float64, bool)

FalsePositiveRate reports an estimate when one is meaningful.

func (InspectorSnapshot) Granularity

func (s InspectorSnapshot) Granularity() (uint64, bool)

Granularity reports the selected number of quantized key classes.

func (InspectorSnapshot) ItemCount

func (s InspectorSnapshot) ItemCount() (uint64, bool)

ItemCount reports indexed wildcard and concrete posting items.

func (InspectorSnapshot) MemoryLimit

func (s InspectorSnapshot) MemoryLimit() (uint64, bool)

MemoryLimit reports the effective representation byte limit after applying every ancestor policy limit.

func (InspectorSnapshot) MemoryUsage

func (s InspectorSnapshot) MemoryUsage() (uint64, bool)

MemoryUsage reports deterministic accounted representation bytes.

func (InspectorSnapshot) Mode

func (s InspectorSnapshot) Mode() RuleMode

Mode reports the compiled representation mode.

func (InspectorSnapshot) RangePruning

func (s InspectorSnapshot) RangePruning() uint64

RangePruning reports observed early All exits proved by disjoint bitmap ID ranges.

func (InspectorSnapshot) ResultCardinality

func (s InspectorSnapshot) ResultCardinality() Histogram

ResultCardinality reports the captured result-cardinality histogram.

func (InspectorSnapshot) RuleCount

func (s InspectorSnapshot) RuleCount() uint64

RuleCount reports the number of unique external rule IDs in the build.

func (InspectorSnapshot) Strategy

func (s InspectorSnapshot) Strategy() string

Strategy reports the compiled strategy.

type Local

type Local[C any, ID comparable] struct {
	// contains filtered or unexported fields
}

Local is a search context that keeps per-node cached results between calls. It must not be used concurrently by multiple goroutines.

func (*Local[C, ID]) Close

func (local *Local[C, ID]) Close()

Close releases cached search results and returns the internal context to the originating Index for reuse. Empty per-node cache structures and learned All child orders remain with that recyclable context, while all admission and replacement state is reset so its next Local lifetime starts cold. A closed Local must not be used again. Repeated calls to Close are safe.

func (*Local[C, ID]) Search

func (local *Local[C, ID]) Search(value C, dst *[]ID) bool

Search appends matching IDs to dst while reusing this Local's cached state and reports whether this call found any matches. Existing elements in dst do not affect the reported result. Search panics when dst is nil.

func (*Local[C, ID]) Visit

func (local *Local[C, ID]) Visit(value C, yield func(ID) bool)

Visit calls yield for matching IDs while reusing this Local's cached state. A nil yield function is a no-op.

type LossyOption

type LossyOption interface {
	// contains filtered or unexported methods
}

LossyOption configures a memory-bounded representation selected during Build. Implementations are sealed so new options can be added without weakening validation of a schema.

func MemoryLimit

func MemoryLimit(bytes uint64) LossyOption

MemoryLimit sets the maximum accounted bytes retained by one Lossy rule.

type Operator

type Operator uint8

Operator identifies a comparison stored in a CompareBy constraint. The comparison is written from the query's perspective: OperatorGTE means query >= stored.

const (
	// OperatorEQ selects query == stored.
	OperatorEQ Operator = iota
	// OperatorLT selects query < stored.
	OperatorLT
	// OperatorLTE selects query <= stored.
	OperatorLTE
	// OperatorGT selects query > stored.
	OperatorGT
	// OperatorGTE selects query >= stored.
	OperatorGTE
)

type Rule

type Rule[T any] interface {
	// contains filtered or unexported methods
}

Rule describes how constraints and query values of T are matched. Construct rules with Include, Exclude, the ordered filters, Between, CompareBy, and All. Its implementation is sealed so an index can rely on all rule invariants.

func All

func All[T any](rules ...Rule[T]) Rule[T]

All combines rules with logical AND: a stored constraint matches only when every child rule matches. All may be nested.

For example, to match both country and customer tier:

ruleix.All(
	ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true }),
	ruleix.Include(func(c Constraint) (string, bool) { return c.Tier, true }),
)

func Between

func Between[T any, V any](from, until Getter[T, V], compare Compare[V]) Rule[T]

Between matches an interval fully covered by a stored interval: stored.from <= query.from AND query.until <= stored.until. Either missing stored bound is a wildcard for that side of the interval; a missing query bound matches only a stored wildcard on the same side.

For example, to find stored validity windows that cover a query window:

ruleix.Between(
	func(c Constraint) (time.Time, bool) { return c.ValidFrom, true },
	func(c Constraint) (time.Time, bool) { return c.ValidUntil, true },
	time.Time.Compare,
)

func CompareBy

func CompareBy[T any, V any](
	value Getter[T, V],
	operator Getter[T, Operator],
	compare Compare[V],
) Rule[T]

CompareBy evaluates the operator stored in each inserted rule against the concrete value supplied to Search. The query-side operator is ignored. A missing stored value is a wildcard and its operator is not validated. Build returns an error when a non-wildcard rule has no operator or an unsupported operator.

For example, a stored value with OperatorGTE and value 5 matches a query whose value is 7:

ruleix.CompareBy(
	func(c Constraint) (int, bool) { return c.Orders, true },
	func(c Constraint) (ruleix.Operator, bool) { return c.Operator, true },
	cmp.Compare[int],
)

func Exclude

func Exclude[T any, V comparable](get Getter[T, V]) Rule[T]

Exclude indexes an optional forbidden value. ok == false means no forbidden value. A concrete match excludes the associated result ID even when another stored constraint with that ID matches.

For example, to reject rules whose forbidden channel equals the query channel:

ruleix.Exclude(func(c Constraint) (string, bool) { return c.ExcludedChannel, true })

func Greater

func Greater[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

Greater matches query > stored. A missing stored value is a wildcard.

For example, a stored order-count threshold of 5 matches a query count of 6:

ruleix.Greater(
	func(c Constraint) (int, bool) { return c.OrderCountThreshold, true },
	cmp.Compare[int],
)

func GreaterOrEqual

func GreaterOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

GreaterOrEqual matches query >= stored. A missing stored value is a wildcard.

For example, a stored minimum total of 100 matches a query total of 150:

ruleix.GreaterOrEqual(
	func(c Constraint) (int, bool) { return c.MinimumTotal, true },
	cmp.Compare[int],
)

func Include

func Include[T any, V comparable](get Getter[T, V]) Rule[T]

Include matches a query field when it equals the stored field. A missing stored value is a wildcard and matches every concrete query value; a missing query value matches only stored wildcards.

For example, to match a rule's optional country:

ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true })

func Inspect

func Inspect[T any](dst *Inspector, rule Rule[T]) Rule[T]

Inspect decorates rule with an observational handle. It does not change the compiled search tree or matching semantics. Inspect panics for a nil inspector or rule. Attaching the same inspector more than once in one schema makes Build fail.

func Less

func Less[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

Less matches query < stored. A missing stored value is a wildcard.

For example, a stored upper limit of 10 matches a query value of 9:

ruleix.Less(
	func(c Constraint) (int, bool) { return c.UpperLimit, true },
	cmp.Compare[int],
)

func LessOrEqual

func LessOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

LessOrEqual matches query <= stored. A missing stored value is a wildcard.

For example, a stored maximum total of 200 matches a query total of 150:

ruleix.LessOrEqual(
	func(c Constraint) (int, bool) { return c.MaximumTotal, true },
	cmp.Compare[int],
)

func Lossy

func Lossy[T any](rule Rule[T], options ...LossyOption) Rule[T]

Lossy permits rule to use a conservative approximation when its exact representation does not fit the configured memory limit. Approximate searches can return false positives, but never omit an exact match.

type RuleMode

type RuleMode string

RuleMode describes whether a compiled rule retains exact matching semantics or uses an approximation that may return false positives.

const (
	// RuleModeExact reports a representation with no false positives.
	RuleModeExact RuleMode = "exact"
	// RuleModeLossy reports a conservative representation that may include
	// false positives but never excludes an exact match.
	RuleModeLossy RuleMode = "lossy"
)

Directories

Path Synopsis
examples
between_and_gt command
Package main demonstrates combining Between with a strict greater-than rule.
Package main demonstrates combining Between with a strict greater-than rule.
local_search command
Command local_search demonstrates repeated searches with a local cache.
Command local_search demonstrates repeated searches with a local cache.
multiple_columns command
Package main demonstrates matching rules across several independent columns.
Package main demonstrates matching rules across several independent columns.

Jump to

Keyboard shortcuts

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