The Go module github.com/assetcorp/narsil/packages/go sends your calls to a Narsil server over HTTP from Go 1.26 or later, and it depends only on the standard library. It has one typed method for every route in the server's OpenAPI file, with the operation name of the route in Go form, so createIndex becomes CreateIndex. To search an index inside the Go process with no server at all, use the engine module at github.com/assetcorp/narsil/packages/go/engine and start from Getting started.
On this page, you'll build main.go, a program that searches a server, writes documents to it, follows a rebalance that the server continues after the call returns, and keeps working while one of two servers is down. Each code block below holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Install the client
The examples on this page use version 0.1.3. The client and the engine have separate version tags, so go get fetches only the client.
go mod init example.com/helpcentre
go get github.com/assetcorp/narsil/packages/go@v0.1.3From version 0.1.2, GetChanges and UpdateChanges return and set the change capture setting of an index. To follow the change feed from Go, use the separate module github.com/assetcorp/narsil/packages/go/changes, which the examples on Change capture use.
Start a server to call
The client calls a server from the TypeScript package, so start one in a second terminal. The server below listens on port 7700 and accepts only the requests that hold the API key, as in the examples on HTTP server. Install the package and uWebSockets.js, the web server that the package uses, into a Node.js 24 project whose package.json sets "type": "module".
pnpm add -E @delali/narsil uWebSockets.js@github:uNetworking/uWebSockets.js#v20.70.0import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'
const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
host: '127.0.0.1',
port: 7700,
onRequest: (request) =>
request.headers.authorization === `Bearer ${API_KEY}`
? undefined
: { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})
await server.listen()
console.log('Narsil is listening on http://127.0.0.1:7700')
process.once('SIGINT', async () => {
await server.shutdown()
})Node.js 24 can execute a TypeScript file as it stands, so start the server with node server.ts and keep it going while you work through this page.
Narsil is listening on http://127.0.0.1:7700Press Ctrl+C in that terminal when you finish, which makes the SIGINT handler shut the server down along with its engine.
Connect and search
narsil.New takes the server's addresses in URLs, along with an APIKey that the client sends as a bearer token on every request. Every method takes a context.Context first, while the generated types have the same fields as the server's JSON. An optional field is a pointer, which narsil.Ptr fills, while a field that takes one of several shapes is a struct with one field for each shape, such as HTTPQueryParamsDocumentObject on HTTPQueryParamsDocument. Set exactly one of those fields, because the client refuses a value with none set or with two set. The program drops the index as it returns, so that you can execute it again against the same server with go run ..
package main
import (
"context"
"fmt"
"log"
"os"
narsil "github.com/assetcorp/narsil/packages/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
apiKey := os.Getenv("NARSIL_API_KEY")
if apiKey == "" {
apiKey = "support-desk-key"
}
client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
if err != nil {
return err
}
defer client.CloseIdleConnections()
_, err = client.CreateIndex(ctx, narsil.HTTPCreateIndexBody{
Name: "articles",
Config: narsil.HTTPIndexBody{Schema: narsil.SchemaDefinition{
"title": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
"body": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
}},
})
if err != nil {
return err
}
defer client.DropIndex(ctx, "articles")
_, err = client.InsertBatch(ctx, "articles", []narsil.AnyDocument{
{"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
{"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
{"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
}, nil)
if err != nil {
return err
}
if _, err = client.WaitForWrites(ctx, "articles"); err != nil {
return err
}
found, err := client.Query(ctx, "articles", narsil.HTTPQueryParams{
Term: narsil.Ptr("refund"),
Document: &narsil.HTTPQueryParamsDocument{
HTTPQueryParamsDocumentObject: &narsil.HTTPQueryParamsDocumentObject{Include: []string{"title"}},
},
})
if err != nil {
return err
}
for _, hit := range found.Hits {
fmt.Println(hit.ID, hit.Document["title"])
}
return nil
}refund-timing How a refund reaches your bank
refund-currency Refunds in another currencyThe server answers with the same two hits that the TypeScript client receives for this search. You can use one Client from many goroutines at once safely, so keep one for the lifetime of the application.
Write a document under an id that you choose
Put writes a document at the id that you give it and returns Created, which is true when the call creates the document and false when it replaces one. Get returns a nil document and a nil error for an id that the index lacks, while it returns an error for every other failure.
package main
import (
"context"
"fmt"
"log"
"os"
narsil "github.com/assetcorp/narsil/packages/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
apiKey := os.Getenv("NARSIL_API_KEY")
if apiKey == "" {
apiKey = "support-desk-key"
}
client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
if err != nil {
return err
}
defer client.CloseIdleConnections()
_, err = client.CreateIndex(ctx, narsil.HTTPCreateIndexBody{
Name: "articles",
Config: narsil.HTTPIndexBody{Schema: narsil.SchemaDefinition{
"title": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
"body": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
}},
})
if err != nil {
return err
}
defer client.DropIndex(ctx, "articles")
_, err = client.InsertBatch(ctx, "articles", []narsil.AnyDocument{
{"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
{"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
{"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
}, nil)
if err != nil {
return err
}
if _, err = client.WaitForWrites(ctx, "articles"); err != nil {
return err
}
found, err := client.Query(ctx, "articles", narsil.HTTPQueryParams{
Term: narsil.Ptr("refund"),
Document: &narsil.HTTPQueryParamsDocument{
HTTPQueryParamsDocumentObject: &narsil.HTTPQueryParamsDocumentObject{Include: []string{"title"}},
},
})
if err != nil {
return err
}
for _, hit := range found.Hits {
fmt.Println(hit.ID, hit.Document["title"])
}
created, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page.",
}})
if err != nil {
return err
}
replaced, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page, and it expires after one hour.",
}})
if err != nil {
return err
}
missing, err := client.Get(ctx, "articles", "gift-cards")
if err != nil {
return err
}
fmt.Println("created", created.ID, created.Created)
fmt.Println("replaced", replaced.ID, replaced.Created)
fmt.Println("missing", missing == nil)
return nil
}created password-reset true
replaced password-reset false
missing trueThe first Put creates the article, while the second replaces it, so Created holds true and then false.
Follow the work that outlasts a request
A rebalance, a restore, an analysis rebuild, a vector optimisation, and a started import can take longer than a request should wait. For each of them, the server answers at once with a task record and continues the work. WaitForTask then polls that task every 250 ms until the work finishes.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
narsil "github.com/assetcorp/narsil/packages/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
apiKey := os.Getenv("NARSIL_API_KEY")
if apiKey == "" {
apiKey = "support-desk-key"
}
client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
if err != nil {
return err
}
defer client.CloseIdleConnections()
_, err = client.CreateIndex(ctx, narsil.HTTPCreateIndexBody{
Name: "articles",
Config: narsil.HTTPIndexBody{Schema: narsil.SchemaDefinition{
"title": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
"body": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
}},
})
if err != nil {
return err
}
defer client.DropIndex(ctx, "articles")
_, err = client.InsertBatch(ctx, "articles", []narsil.AnyDocument{
{"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
{"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
{"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
}, nil)
if err != nil {
return err
}
if _, err = client.WaitForWrites(ctx, "articles"); err != nil {
return err
}
created, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page.",
}})
if err != nil {
return err
}
replaced, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page, and it expires after one hour.",
}})
if err != nil {
return err
}
missing, err := client.Get(ctx, "articles", "gift-cards")
if err != nil {
return err
}
fmt.Println("created", created.ID, created.Created)
fmt.Println("replaced", replaced.ID, replaced.Created)
fmt.Println("missing", missing == nil)
if _, err = client.UpdatePartitionConfig(ctx, "articles", &narsil.PartitionConfig{MaxPartitions: narsil.Ptr(2.0)}); err != nil {
return err
}
started, err := client.Rebalance(ctx, "articles", narsil.RebalanceBody{TargetPartitionCount: narsil.Ptr(2.0)})
if err != nil {
return err
}
finished, err := client.WaitForTask(ctx, started.ID, narsil.WaitOptions{WaitTimeout: time.Minute})
if err != nil {
return err
}
stats, err := client.GetStats(ctx, "articles")
if err != nil {
return err
}
fmt.Println("started", started.Type, started.Status)
fmt.Println("finished", finished.Status)
fmt.Println("partitions", stats.PartitionCount)
return nil
}created password-reset true
replaced password-reset false
missing true
started rebalance running
finished succeeded
partitions 2The server answers the rebalance with a record whose status is running. WaitForTask then returns once the status reaches succeeded, by which point the index holds two partitions. A task can also end as failed, with the error in the record's Error field, or as cancelled after CancelTask. WaitForTask returns a failed task with a nil Go error, because the record of a part-finished import holds the count of the documents that the server indexes before the failure, so check the Status of the record that it returns. With WaitTimeout, WaitForTask fails with CLIENT_TASK_TIMEOUT once that time passes, while the server continues the task. With OnProgress, you pass a function that the client calls each time the record changes, such as one that updates a progress bar for StartImport.
Keep working while one server is down
URLs can list several addresses, such as one for each node of a cluster or each copy of a server behind your load balancer. The client sends each request to the next address in the list after the address of the previous request, so that the requests spread across the list. When a server refuses the connection, the client retries the request on the next address and skips the refused address for 1 second, doubling that wait after each further refusal, up to 30 seconds. URLSkip and MaxURLSkip set those two intervals. In the block below, port 7701 stands in for a stopped server, since no process listens on it.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
narsil "github.com/assetcorp/narsil/packages/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
apiKey := os.Getenv("NARSIL_API_KEY")
if apiKey == "" {
apiKey = "support-desk-key"
}
client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
if err != nil {
return err
}
defer client.CloseIdleConnections()
_, err = client.CreateIndex(ctx, narsil.HTTPCreateIndexBody{
Name: "articles",
Config: narsil.HTTPIndexBody{Schema: narsil.SchemaDefinition{
"title": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
"body": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
}},
})
if err != nil {
return err
}
defer client.DropIndex(ctx, "articles")
_, err = client.InsertBatch(ctx, "articles", []narsil.AnyDocument{
{"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
{"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
{"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
}, nil)
if err != nil {
return err
}
if _, err = client.WaitForWrites(ctx, "articles"); err != nil {
return err
}
created, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page.",
}})
if err != nil {
return err
}
replaced, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page, and it expires after one hour.",
}})
if err != nil {
return err
}
missing, err := client.Get(ctx, "articles", "gift-cards")
if err != nil {
return err
}
fmt.Println("created", created.ID, created.Created)
fmt.Println("replaced", replaced.ID, replaced.Created)
fmt.Println("missing", missing == nil)
if _, err = client.UpdatePartitionConfig(ctx, "articles", &narsil.PartitionConfig{MaxPartitions: narsil.Ptr(2.0)}); err != nil {
return err
}
started, err := client.Rebalance(ctx, "articles", narsil.RebalanceBody{TargetPartitionCount: narsil.Ptr(2.0)})
if err != nil {
return err
}
finished, err := client.WaitForTask(ctx, started.ID, narsil.WaitOptions{WaitTimeout: time.Minute})
if err != nil {
return err
}
stats, err := client.GetStats(ctx, "articles")
if err != nil {
return err
}
fmt.Println("started", started.Type, started.Status)
fmt.Println("finished", finished.Status)
fmt.Println("partitions", stats.PartitionCount)
nodes, err := narsil.New(narsil.Config{
URLs: []string{"http://127.0.0.1:7701", "http://127.0.0.1:7700"},
APIKey: apiKey,
})
if err != nil {
return err
}
defer nodes.CloseIdleConnections()
written, err := nodes.Put(ctx, "articles", "gift-cards", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Pay with a gift card",
"body": "Enter the gift card code at checkout.",
}})
if err != nil {
return err
}
fmt.Println("written", written.ID, written.Created)
for range 3 {
read, err := nodes.Query(ctx, "articles", narsil.HTTPQueryParams{Term: narsil.Ptr("gift")})
if err != nil {
return err
}
fmt.Println("read", read.Count)
}
return nil
}created password-reset true
replaced password-reset false
missing true
started rebalance running
finished succeeded
partitions 2
written gift-cards true
read 1
read 1
read 1The write and all three searches succeed, because the client retries each request that fails on port 7701 on port 7700. The client counts a GET, a search, a preflight, a suggestion, a document list, and a multi-get as reads. It retries a read on the next address after a refused or broken connection, a timeout, or an answer of 502, 503, or 504. Once every address fails that way, the client sends the read once more, so a list of N addresses can take N + 1 requests. The client retries a write only when the dial fails before the client sends any byte of the request, as with a refused connection or a name that does not resolve, or when the server answers NODE_NOT_READY. A server can apply a write that reaches it, so after a timeout or a broken connection, the client returns the error to you and sends nothing more. The client can send a body that you pass as a *bytes.Reader, a *bytes.Buffer, or a *strings.Reader to a second address. It sends any other io.Reader, such as an *os.File, to one address only, because it can't read that body twice.
Handle failures
The client returns every failure as a *narsil.Error, with the code from the server in Code and the HTTP status in Status, which holds 0 when no answer arrives. The program below asks for an index that the server lacks, and then it sends a search without the API key, which the server's onRequest hook refuses.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
narsil "github.com/assetcorp/narsil/packages/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
apiKey := os.Getenv("NARSIL_API_KEY")
if apiKey == "" {
apiKey = "support-desk-key"
}
client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}, APIKey: apiKey})
if err != nil {
return err
}
defer client.CloseIdleConnections()
_, err = client.CreateIndex(ctx, narsil.HTTPCreateIndexBody{
Name: "articles",
Config: narsil.HTTPIndexBody{Schema: narsil.SchemaDefinition{
"title": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
"body": {FieldType: narsil.Ptr(narsil.FieldTypeString)},
}},
})
if err != nil {
return err
}
defer client.DropIndex(ctx, "articles")
_, err = client.InsertBatch(ctx, "articles", []narsil.AnyDocument{
{"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
{"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
{"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
}, nil)
if err != nil {
return err
}
if _, err = client.WaitForWrites(ctx, "articles"); err != nil {
return err
}
created, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page.",
}})
if err != nil {
return err
}
replaced, err := client.Put(ctx, "articles", "password-reset", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Reset your password",
"body": "Request a reset link from the sign-in page, and it expires after one hour.",
}})
if err != nil {
return err
}
missing, err := client.Get(ctx, "articles", "gift-cards")
if err != nil {
return err
}
fmt.Println("created", created.ID, created.Created)
fmt.Println("replaced", replaced.ID, replaced.Created)
fmt.Println("missing", missing == nil)
if _, err = client.UpdatePartitionConfig(ctx, "articles", &narsil.PartitionConfig{MaxPartitions: narsil.Ptr(2.0)}); err != nil {
return err
}
started, err := client.Rebalance(ctx, "articles", narsil.RebalanceBody{TargetPartitionCount: narsil.Ptr(2.0)})
if err != nil {
return err
}
finished, err := client.WaitForTask(ctx, started.ID, narsil.WaitOptions{WaitTimeout: time.Minute})
if err != nil {
return err
}
stats, err := client.GetStats(ctx, "articles")
if err != nil {
return err
}
fmt.Println("started", started.Type, started.Status)
fmt.Println("finished", finished.Status)
fmt.Println("partitions", stats.PartitionCount)
nodes, err := narsil.New(narsil.Config{
URLs: []string{"http://127.0.0.1:7701", "http://127.0.0.1:7700"},
APIKey: apiKey,
})
if err != nil {
return err
}
defer nodes.CloseIdleConnections()
written, err := nodes.Put(ctx, "articles", "gift-cards", narsil.DocumentBody{Document: narsil.AnyDocument{
"title": "Pay with a gift card",
"body": "Enter the gift card code at checkout.",
}})
if err != nil {
return err
}
fmt.Println("written", written.ID, written.Created)
for range 3 {
read, err := nodes.Query(ctx, "articles", narsil.HTTPQueryParams{Term: narsil.Ptr("gift")})
if err != nil {
return err
}
fmt.Println("read", read.Count)
}
anonymous, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7700"}})
if err != nil {
return err
}
defer anonymous.CloseIdleConnections()
var failure *narsil.Error
_, err = client.Query(ctx, "faqs", narsil.HTTPQueryParams{Term: narsil.Ptr("refund")})
if errors.As(err, &failure) {
fmt.Println("failed", failure.Code, failure.Status)
}
_, err = anonymous.Query(ctx, "articles", narsil.HTTPQueryParams{Term: narsil.Ptr("refund")})
if errors.As(err, &failure) {
fmt.Println("failed", failure.Code, failure.Status)
}
return nil
}created password-reset true
replaced password-reset false
missing true
started rebalance running
finished succeeded
partitions 2
written gift-cards true
read 1
read 1
read 1
failed INDEX_NOT_FOUND 404
failed UNAUTHORISED 401The client passes the hook's code to your program unchanged, so a branch that you write against UNAUTHORISED works whichever node answers. narsil.ErrorCode(err) returns only the code, or the empty string for an error that holds no *narsil.Error. The client itself returns five codes, and each one has a constant:
| Constant | The client returns it when |
|---|---|
CodeClientConnectionFailed | The client can't reach any server, or the connection breaks before the answer arrives. |
CodeClientRequestTimeout | The deadline passes before the answer arrives. |
CodeClientRequestAborted | You cancel the context of the call. |
CodeClientInvalidResponse | The answer holds neither a Narsil error nor the shape that the OpenAPI file gives for the route, as with the HTML error page of a proxy, or it exceeds MaxResponseBytes. |
CodeClientTaskTimeout | WaitForTask reaches WaitTimeout while the task is still in progress. |
The client gives every try of a request 30 seconds, after which the request fails with CLIENT_REQUEST_TIMEOUT. Set Timeout in the config to change that for every request, or pass narsil.WithTimeout to one call, while narsil.NoTimeout makes the client wait for as long as the server takes. The methods that move a corpus or a whole index wait without a deadline unless you set a timeout. Those methods are ImportDocuments, StartImport, ImportNDJSON, Snapshot, Restore, ExportDocuments, ImportDocumentExport, and SyncSnapshot. The context of the call bounds every method, so when you cancel the context, the call fails with CLIENT_REQUEST_ABORTED, while a context deadline that passes makes it fail with CLIENT_REQUEST_TIMEOUT. narsil.WithHeader and narsil.WithMaxResponseBytes change one call in the same way. To add a proxy or custom certificates, build an *http.Client, pass it as HTTPClient, and leave its Timeout at zero, because the client bounds each try through the context.
Where to go next
- Read TypeScript client and Python client for the same routes from those languages.
- Read HTTP server for what each route does and for the hook that checks the key.
- Read Device sync for
UpdateSync, which turns sync on for one user's index from Go. - Read Change capture for the change feed and the
changesmodule that follows it from Go. - Read Errors for the codes that a server sends.