Skip to content
itzTheMeowPublic

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fusego

A pure Go port of Fuse.js, a lightweight fuzzy-search library, targeting Fuse.js 7.5.0 with verified behavioral parity: the upstream vitest suite runs byte-unmodified against this engine through a JS↔Go bridge (318/318 tests, zero skips).

Create a Fuse over a slice of strings or objects, then call Search. Searching supports approximate (Bitap) matching, weighted keys, nested key paths, extended (unix-like) search syntax, logical $and/$or queries, and token (TF-IDF) search.

Install

go get fusego

(or vendor the module; it has no dependencies beyond golang.org/x/text for Unicode NFD.)

Quick start

package main

import fusego "fusego"

type book struct {
	Title  string `json:"title"`
	Author struct {
		FirstName string `json:"firstName"`
		LastName  string `json:"lastName"`
	} `json:"author"`
}

func main() {
	books := []book{ /* ... */ }

	fuse, err := fusego.New(books, &fusego.Options{
		Keys: []any{
			"title",
			&fusego.Key{Name: "author.lastName", Weight: 0.5},
		},
		IncludeScore: fusego.Ptr(true),
	}, nil)
	if err != nil {
		panic(err)
	}

	results, err := fuse.Search("old man's war", nil)
	if err != nil {
		panic(err)
	}
	for _, r := range results {
		fmt.Println(r.Item.Title, r.RefIndex, *r.Score)
	}
}

Options left unset (nil pointer fields) resolve against the package-level fusego.Config when the Fuse is constructed — the equivalent of JS Fuse.config. Instances snapshot the resolved options, exactly like JS { ...Config, ...options }.

API mapping: Fuse.js → fusego

Fuse.js fusego
new Fuse(docs, options) fusego.New(docs, options, nil) — generic over the document type
new Fuse(docs, options, index) fusego.New(docs, options, index)
fuse.search(pattern) fuse.Search(pattern, nil)
fuse.search(pattern, { limit }) fuse.Search(pattern, &fusego.SearchOptions{Limit: fusego.Ptr(10)})
fuse.search({ $and, $or }) fuse.Search(logicalQuery, nil) (*OrderedMap or map[string]any)
Fuse.config fusego.Config
Fuse.version fusego.Version
fuse.add(doc) fuse.Add(doc)
fuse.remove(predicate) fuse.Remove(func(doc T, idx int) bool) []T
fuse.removeAt(idx) fuse.RemoveAt(idx)
fuse.setCollection(docs) fuse.SetCollection(docs, nil)
fuse.getIndex() fuse.GetIndex()
Fuse.createIndex(keys, docs, options) fusego.CreateIndex(keys, docs, options)
Fuse.parseIndex(data, options) fusego.ParseIndex[T](data, options)
index.toJSON() index.IndexJSON()
Fuse.match(pattern, text, options) fusego.MatchText(pattern, text, options)
Fuse.use(plugins) fusego.RegisterSearchers(plugins)
Fuse.parseQuery(query, options) fusego.ParseLogical(query, resolvedOptions, auto)
options object fusego.Options (pointer fields; fusego.Ptr(v))
{ keys: ['title', {name: 'author', weight: 2}] } Keys: []any{"title", &fusego.Key{Name: "author", Weight: 2}}
{ limit } per search SearchOptions{Limit: *int} (nil = unlimited, 0 = empty)
FuseIndex.keys / records (*FuseIndex[T]).Keys / .Records
inverted index internals (*Fuse[T]).InvertedIndex()

Errors are returned as Go error values (*fusego.FuseError carries the upstream message verbatim), not thrown.

Options

Every Fuse.js option exists on fusego.Options with the same name and semantics: IsCaseSensitive, IgnoreDiacritics, IncludeScore, ShouldSort, SortFn, Keys, IncludeMatches, FindAllMatches, MinMatchCharLength, Location, Threshold, Distance, UseExtendedSearch, UseTokenSearch, Tokenize, TokenMatch, GetFn, IgnoreLocation, IgnoreFieldNorm, FieldNormWeight.

Pointer fields are nil when unset — set them with fusego.Ptr(v) — so meaningful zero values (Threshold: 0) are expressible, mirroring JS optionality. Function-typed fields (SortFn, GetFn, Tokenize) and TokenMatch (string) are nil/"" when unset.

Behavior and compatibility notes

  • Character indices are UTF-16 code units, like JavaScript: an emoji counts as 2 positions in match ranges.
  • Match indices are [start, end] pairs (inclusive), JSON-shaped like the JS arrays.
  • Errors carry upstream messages verbatim ("Extended search is not available", …) so tests and tooling can match on them.
  • Tokenizer regexes use Go regexp (RE2); the tokenizer regexes and extended-search patterns the JS suite uses are compatible. RE2 has no backreferences/lookahead — exotic JS regex features are rejected.
  • Struct documents are traversed by field name (exact, JSON tag, then case-insensitive); map documents by key. Custom GetFn overrides both.

Demo

example/ is a terminal version of the fusejs.io demo (a port of fuse_dart's demo): same 19-book corpus, same keys, and the same toggles (threshold slider, includeScore, includeMatches, ignoreLocation, useExtendedSearch, useTokenSearch), with score + highlighted matches per result — byte-identical output to the Dart demo.

go run ./example                # interactive REPL
go run ./example "old man"      # one-shot
go run ./example "ste ham" --threshold=0.4 --useTokenSearch

Conformance: how parity is verified

The conformance/ directory (the pinned git submodule of the shared conformance harness) vendors the upstream Fuse.js test suite byte-unmodified and runs it in two modes. After cloning, initialize it once: git submodule update --init --recursive, then (cd conformance && npm install).

just conformance   # baseline: the suite against real Fuse.js (304 tests)
just bridge        # the suite against fusego through the bridge (318 tests)
just check         # vet + go tests + baseline + bridge

In bridge mode every new Fuse(...), .search(...), index operation, and callback (getFn, sortFn, tokenizer, remove predicates, Fuse.use plugins) is forwarded to a Go process over a synchronous JSON-line protocol, including JS objects, BigInts, and regular expressions crossing the boundary. The extra 14 tests in bridge mode cover the bridge infrastructure itself (process lifecycle, leak regressions, watchdog fail-fast, shim fidelity).

Testing

just test      # Go-only: engine edges, float parity, bridge protocol
just smoke     # walk every major code path, print intermediate shapes
just bench     # native performance suite vs Fuse.js (see benchmark/)

Performance

Native Go vs real Fuse.js 7.5.0, identical datasets, no bridge in the measured path (methodology and the shared driver live in the conformance repo's benchmark/; just bench-compare runs the go+js pair):

dataset geomean vs Fuse.js
1,000 docs ~1.7× faster
10,000 docs ~1.8× faster
100,000 docs ~2.2× faster

The driver also runs a per-workload memory pass (peak incremental RSS in a fresh process per workload; go/js numbers are post-GC retained footprints). The index footprint (index_build memory): ~1 MB at 1k docs, ~5 MB at 10k, ~51 MB at 100k — versus Fuse.js's ~7 MB / 16 MB / 126 MB on the same data.

Every score-affecting Math.pow call runs through jsPow, a correctly-rounded pow (double-double fast path with an exact fallback), so the Go port matches V8 bit for bit where it matters while staying ~2× ahead of it end to end.

Formatting

nix fmt formats the whole repo via treefmt (gofmt for .go, nixfmt for .nix, prettier for everything else). Run it before committing — see AGENTS.md; nix flake check enforces it via checks.formatting. The conformance/ submodule is excluded — it carries its own treefmt setup.

License

Apache License 2.0. This is a derivative work of Fuse.js (Copyright Kiro Risk), which is also licensed under Apache 2.0.

Releases

Packages

Contributors

Languages