> Complete content index: https://narsil.sondelali.com/llms.txt

# Go

> Install the Narsil Go module, build it for each platform, map the names in these docs onto Go's types, keep an index on disk, read its errors, and write a tokeniser in Go.

URL: https://narsil.sondelali.com/docs/go
Section: Languages
Version: 0.4 (@delali/narsil@0.4.3, latest)

With the Go module `github.com/assetcorp/narsil/packages/go/engine`, a Go program searches Narsil indexes inside its process, with no separate server. The module has the single-node operations of the TypeScript package and analyses text and searches vectors through the same C core. It saves every file in the same format as the other packages, so TypeScript, Python, and Rust programs can open an index that a Go program saves, and a Go program can open theirs. If your Go program has to call a Narsil server that a TypeScript process serves, see [Go client](/docs/go-client) for the client module.

## Install the module

The examples in these docs use version 0.2.1 of the module.

```bash title="go get"
go get github.com/assetcorp/narsil/packages/go/engine@v0.2.1
```

The module requires Go 1.26 or later and a C compiler, because the Go toolchain compiles Narsil's C core through cgo along with your program, from the C sources in the module. Cgo is on by default when Go builds for the machine that hosts the build and finds a C compiler there. Each release has a tag of the form `packages/go/engine/vX.Y.Z`, because the module is in a subdirectory of the Narsil repository. `go get github.com/assetcorp/narsil/packages/go/engine@v0.2.1` therefore fetches the release tagged `packages/go/engine/v0.2.1`.

## Build for each platform

A native build requires the C compiler of the platform, which is GCC or Clang on Linux, the Xcode Command Line Tools on macOS, and MinGW-w64 GCC on Windows x64. Cgo can't use the Microsoft Visual C++ compiler, so a Windows build requires a GNU-compatible compiler, such as MinGW-w64, llvm-mingw, or Zig. Go turns cgo off when it cross-compiles, so set `CGO_ENABLED=1` for a cross-compile and give a C compiler for the target in `CC`. The command below cross-compiles for Windows on arm64 from Linux.

```bash title="cross-compile"
CGO_ENABLED=1 GOOS=windows GOARCH=arm64 CC="zig cc -target aarch64-windows-gnu" go build ./...
```

Use the same command, with `x86_64-linux-gnu`, `aarch64-linux-gnu`, or `x86_64-windows-gnu` as the target, to build for the other Linux and Windows targets from Linux. Build for macOS on a Mac, because the linker requires Apple's SDK.

## Map the names in these docs onto Go

Almost every method takes a `context.Context` as its first argument and returns an error as its last value. The methods and fields have Go's exported names, which start with a capital letter. Where these docs pass a JavaScript object, the module takes a typed struct:

| TypeScript | Go |
| --- | --- |
| `createNarsil(config)` | `engine.New(ctx, engine.Config{...})` |
| `shutdown()` | `Shutdown(ctx)` |
| `schema: { name: 'string', price: 'number' }` | `Schema: engine.Schema{"name": engine.FieldString, "price": engine.FieldNumber}` |
| a document object | an `*engine.Document` from `engine.DocumentFromMap` or `engine.NewDocument().Set(...)` |
| `insertBatch(index, documents)` | `InsertBatch(ctx, index, []*engine.Document{...}, engine.InsertOptions{})` |
| `limit: 5` | `Limit: engine.Some(5)` |
| `hit.score`, which can be `undefined` | `hit.Score.Or(0)`, or `hit.Score.Get()` |
| `get` returning `undefined` | `Get` returning `false` as its second value |
| `open`, `close` | `Open`, `Close` |
| `snapshot(index)` returning a stream | `Snapshot(ctx, index, engine.SnapshotOptions{}, writer)` |

`engine.Some` wraps a value in an `engine.Optional`, which marks that setting as set. The engine applies its default to every optional setting that you leave unset, so a zero inside `engine.Some` stays a zero. The Go compiler rejects a `[]engine.Document` built from map literals, because `engine.Document` is a struct and every write takes a pointer to one. `engine.DocumentFromMap` sorts the keys of the map, while `engine.NewDocument().Set(...)` keeps them in the order that you set them. That order matters when a query groups by a field that holds an object, because the engine can put two documents whose objects hold the same keys in a different order into two groups.

## Keep an index on disk

With `Durability` set in `engine.Config`, the engine writes each change to a write-ahead log before the call returns. The next `engine.New` on the same directory loads every index before it returns. In the program below, one engine saves an index, and a second engine on the same directory loads it again.

```go title="main.go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/assetcorp/narsil/packages/go/engine"
)

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	directory, err := os.MkdirTemp("", "bicycles")
	if err != nil {
		return err
	}
	defer os.RemoveAll(directory)

	if err := save(ctx, directory); err != nil {
		return err
	}
	return read(ctx, directory)
}

func save(ctx context.Context, directory string) error {
	narsil, err := engine.New(ctx, engine.Config{Durability: &engine.DurabilityConfig{Directory: directory}})
	if err != nil {
		return err
	}
	err = narsil.CreateIndex(ctx, "bicycles", engine.IndexConfig{
		Schema: engine.Schema{"name": engine.FieldString, "price": engine.FieldNumber},
	})
	if err != nil {
		return err
	}
	cargo := engine.DocumentFromMap(map[string]any{"id": "cargo-hauler", "name": "Larsson Cargo hauler", "price": 3499})
	if _, err := narsil.Insert(ctx, "bicycles", cargo, "", engine.InsertOptions{}); err != nil {
		return err
	}
	return narsil.Shutdown(ctx)
}

func read(ctx context.Context, directory string) error {
	narsil, err := engine.New(ctx, engine.Config{Durability: &engine.DurabilityConfig{Directory: directory}})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)

	for _, index := range narsil.ListIndexes() {
		fmt.Println(index.Name, index.DocumentCount)
	}
	stored, found, err := narsil.Get(ctx, "bicycles", "cargo-hauler")
	if err != nil || !found {
		return err
	}
	fmt.Println(stored.Map())
	return nil
}
```

```text result open
bicycles 1
map[id:cargo-hauler name:Larsson Cargo hauler price:3499]
```

`Shutdown` flushes the log and closes the directory. A nil error from `Shutdown` confirms that the last writes are on disk, which is why `save` returns that error. In a real deployment, pass a fixed directory; this program uses a temporary directory so that it starts with an empty directory each time. Leave `Durability` out to keep every index only in memory. The other settings are on [Persistence and durability](/docs/persistence-and-durability).

## Read the error code

When a method fails, it returns an `*engine.Error`. Its `Code` holds the same code that the TypeScript package raises for the same input, its `Message` holds a description of the failure, and its `Details` holds the extra values that the engine attaches to the failure. `engine.AsError(err)` returns that error and true, or false for an error from outside Narsil. `engine.ErrorCode(err)` returns only the code, or an empty string for an error from outside Narsil. The module declares each code as a constant, such as `engine.CodeDocAlreadyExists`, so the compiler rejects a misspelt one. Examples that branch on a code, each with a Go tab, are on [Errors](/docs/errors).

## Write a tokeniser, an adapter, or a plugin in Go

The default tokeniser keeps a name such as `parseInvoiceDate` as one word, so a search for `invoice` doesn't find it. A tokeniser is any type with a `Tokenize(text string) []engine.Token` method, where each token holds its text and its position, counting from 0. The tokeniser below splits each name at its capital letters. `Config.Tokenizers` registers it under the name `identifiers`, and `engine.NamedTokenizer("identifiers")` sets it as the tokeniser of the index.

```go title="main.go"
package main

import (
	"context"
	"fmt"
	"log"
	"regexp"
	"strings"

	"github.com/assetcorp/narsil/packages/go/engine"
)

var identifierWords = regexp.MustCompile(`[A-Z]?[a-z]+|[A-Z]+|[0-9]+`)

type identifierTokenizer struct{}

func (identifierTokenizer) Tokenize(text string) []engine.Token {
	var tokens []engine.Token
	for position, word := range identifierWords.FindAllString(text, -1) {
		tokens = append(tokens, engine.Token{Token: strings.ToLower(word), Position: position})
	}
	return tokens
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	narsil, err := engine.New(ctx, engine.Config{
		Tokenizers: map[string]engine.Tokenizer{"identifiers": identifierTokenizer{}},
	})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)

	err = narsil.CreateIndex(ctx, "functions", engine.IndexConfig{
		Schema:    engine.Schema{"name": engine.FieldString},
		Tokenizer: engine.NamedTokenizer("identifiers"),
	})
	if err != nil {
		return err
	}
	_, err = narsil.InsertBatch(ctx, "functions", []*engine.Document{
		engine.DocumentFromMap(map[string]any{"id": "parse-invoice-date", "name": "parseInvoiceDate"}),
		engine.DocumentFromMap(map[string]any{"id": "format-currency", "name": "formatCurrencyAmount"}),
		engine.DocumentFromMap(map[string]any{"id": "send-invoice-reminder", "name": "sendInvoiceReminder"}),
	}, engine.InsertOptions{})
	if err != nil {
		return err
	}

	found, err := narsil.Query(ctx, "functions", engine.QueryParams{Term: "invoice"})
	if err != nil {
		return err
	}
	for _, hit := range found.Hits {
		fmt.Println(hit.ID)
	}
	return nil
}
```

```text result open
parse-invoice-date
send-invoice-reminder
```

With the tokeniser in place, `invoice` matches the two functions whose names hold that word. Register a tokeniser by name, through `Config.Tokenizers` or `RegisterTokenizer`. The index stores only that name, so after a restart the engine looks up the tokeniser by the same name.

The other extension points work in the same way. An embedding adapter has the methods `Embed(ctx, input, purpose)` and `Dimensions()`. It can also have an `EmbedBatch` method, so that `InsertBatch` embeds the whole batch in one call. A rerank adapter has a `Rerank(ctx, query, documents)` method, which returns one score for each document. Register each adapter by name with `RegisterEmbeddingAdapter` or `RegisterRerankAdapter`, or pass it in `engine.Config`. A plugin is an `engine.Plugin` struct with a `Name` and any of the hook fields `BeforeInsert`, `AfterInsert`, `BeforeUpdate`, `AfterUpdate`, `BeforeRemove`, `AfterRemove`, `BeforeSearch`, `AfterSearch`, `OnIndexCreate`, `OnIndexDrop`, `OnPartitionSplit`, and `OnWorkerPromote`. Add a plugin to the engine through `Config.Plugins`. When a before hook returns an error, the engine refuses the write with `CodeDocValidationFailed`, unless the error already holds an engine code. The engine also recovers a panic in any hook and reports it in the same way.

## Share one engine between goroutines

Every method of an engine is safe to call from many goroutines at once. The engine can answer a query on an index while a write to the same index is under way. It applies the writes to one index in the order that it receives them. Once an index holds 1,000 documents, the engine serves its searches from a pool of goroutines, which search the one copy of the index that the engine keeps. `Shutdown` refuses new calls with `CodeInstanceShutDown`, waits for the calls already under way, and flushes durable storage. A second call to `Shutdown` returns nil at once.

## How the Go module differs from the TypeScript package

- The TypeScript package copies an index into each worker thread once the index holds 1,000 documents, because JavaScript worker threads share no heap. Goroutines share the heap, so the Go module keeps one copy and emits the same promotion event under the name `WorkerPromote`.
- The cluster, the HTTP client, and the React hooks are only in the TypeScript package. A Go program that needs a server can start the [container image](/docs/container), which holds the TypeScript server and the Rust server, and call it through the [Go client](/docs/go-client).
- `UpdateSync` stores the device sync setting in the index metadata, and `GetSync` returns it. The routes that send sync history to devices are in the HTTP server, so the setting has an effect on devices once a TypeScript or Rust server opens the same directory.
- For popular query suggestions, the Go module normalises each phrase to NFKC through `golang.org/x/text`, which holds the Unicode 17.0.0 tables when you build with Go 1.27 or later and the Unicode 15.0.0 tables on earlier Go releases. If a phrase holds a character from a later Unicode version than the tables in your build, your build can normalise that phrase differently from a newer build.

## Where to go next

- Read [Getting started](/docs/getting-started) to build a bicycle shop's search in Go, with the same scores as in the other languages.
- Read [Errors](/docs/errors) for the codes and for how a program in each language can branch on them.
- Read [Go client](/docs/go-client) to call a Narsil server from Go.
