Skip to content

Repository files navigation

typesense-go

Test GoReportCard Status Go Reference GitHub release Gitter

Go client for the Typesense API: https://github.com/typesense/typesense

Installation

go get github.com/typesense/typesense-go/v4/typesense

typesense-go v4 supports Typesense Server 30.2. To upgrade from v3, follow the migration guide.

Usage

Import the the package into your code :

import "github.com/typesense/typesense-go/v4/typesense"

Create new client:

client := typesense.NewClient(
	    typesense.WithServer("http://localhost:8108"),
	    typesense.WithAPIKey("<API_KEY>"))

New client with advanced configuration options (see godoc):

client := typesense.NewClient(
		typesense.WithServer("http://localhost:8108"),
		typesense.WithAPIKey("<API_KEY>"),
		typesense.WithConnectionTimeout(5*time.Second),
		typesense.WithCircuitBreakerMaxRequests(50),
		typesense.WithCircuitBreakerInterval(2*time.Minute),
		typesense.WithCircuitBreakerTimeout(1*time.Minute),
	)

New client with multi-node configuration options:

client := typesense.NewClient(
		typesense.WithNearestNode("https://xxx.a1.typesense.net:443"),
		typesense.WithNodes([]string{
			"https://xxx-1.a1.typesense.net:443",
			"https://xxx-2.a1.typesense.net:443",
			"https://xxx-3.a1.typesense.net:443",
		}),
		typesense.WithAPIKey("<API_KEY>"),
		typesense.WithNumRetries(5),
		typesense.WithRetryInterval(1*time.Second),
		typesense.WithHealthcheckInterval(2*time.Minute),
	)

You can also find some examples in integration tests.

Create a collection

	schema := &api.CollectionSchema{
		Name: "companies",
		Fields: []api.Field{
			{
				Name: "company_name",
				Type: "string",
			},
			{
				Name: "num_employees",
				Type: "int32",
			},
			{
				Name:  "country",
				Type:  "string",
				Facet: pointer.True(),
			},
		},
		DefaultSortingField: pointer.String("num_employees"),
	}

	client.Collections().Create(context.Background(), schema)

Typed document operations

In v2.0.0+, the client allows you to define a document struct to be used type for some of the document operations.

To do that, you've to use typesense.GenericCollection:

type companyDocument struct {
    ID           string `json:"id"`
    CompanyName  string `json:"company_name"`
    NumEmployees int    `json:"num_employees"`
    Country      string `json:"country"`
}

// doc is a typed document
doc, err := typesense.GenericCollection[*companyDocument](client, "companies").Document("123").Retrieve(context.Background())

Index a document

	document := struct {
		ID           string `json:"id"`
		CompanyName  string `json:"company_name"`
		NumEmployees int    `json:"num_employees"`
		Country      string `json:"country"`
	}{
		ID:           "123",
		CompanyName:  "Stark Industries",
		NumEmployees: 5215,
		Country:      "USA",
	}

	client.Collection("companies").Documents().Create(context.Background(), document, &api.DocumentIndexParameters{})

Upserting a document

	newDocument := struct {
		ID           string `json:"id"`
		CompanyName  string `json:"company_name"`
		NumEmployees int    `json:"num_employees"`
		Country      string `json:"country"`
	}{
		ID:           "123",
		CompanyName:  "Stark Industries",
		NumEmployees: 5215,
		Country:      "USA",
	}

	client.Collection("companies").Documents().Upsert(context.Background(), newDocument, &api.DocumentIndexParameters{})

Search a collection

	searchParameters := &api.SearchCollectionParams{
		Q:        pointer.String("stark"),
		QueryBy:  pointer.String("company_name"),
		FilterBy: pointer.String("num_employees:>100"),
		SortBy:   pointer.String("num_employees:desc"),
	}

	client.Collection("companies").Documents().Search(context.Background(), searchParameters)

for the supporting multiple QueryBy params, you can add , after each field

	searchParameters := &api.SearchCollectionParams{
		Q:        pointer.String("stark"),
		QueryBy:  pointer.String("company_name, country"),
		FilterBy: pointer.String("num_employees:>100"),
		SortBy:   pointer.String("num_employees:desc"),
	}

	client.Collection("companies").Documents().Search(context.Background(), searchParameters)

Run several searches in one request

Perform returns one result per search, in request order. PerformUnion merges the hits of every search into one *api.SearchResult.

	searches := api.MultiSearchSearchesParameter{
		Searches: []api.MultiSearchCollectionParameters{
			{
				Collection: pointer.String("companies"),
				Q:          pointer.String("stark"),
				QueryBy:    pointer.String("company_name"),
			},
			{
				Collection: pointer.String("companies"),
				Q:          pointer.String("wayne"),
				QueryBy:    pointer.String("company_name"),
			},
		},
	}

	client.MultiSearch.Perform(context.Background(), &api.MultiSearchParams{}, searches)

	client.MultiSearch.PerformUnion(context.Background(), &api.MultiSearchParams{PerPage: pointer.Int(10)}, searches)

A union follows these rules:

  • The server reads Page, PerPage, Offset, Limit and LimitHits only from the common parameters in the second argument. It ignores them on each search.
  • Every search sorts on the same number of fields, with the same types in the same order. Otherwise the server answers 400.

When Union is true, Perform returns an error without sending the request. See federated and multi-search for more on unions.

Retrieve a document

client.Collection("companies").Document("123").Retrieve(context.Background())

Update a document

	document := struct {
		CompanyName  string `json:"company_name"`
		NumEmployees int    `json:"num_employees"`
	}{
		CompanyName:  "Stark Industries",
		NumEmployees: 5500,
	}

	client.Collection("companies").Document("123").Update(context.Background(), document, &api.DocumentIndexParameters{})

Delete an individual document

client.Collection("companies").Document("123").Delete(context.Background())

Delete a bunch of documents

filter := &api.DeleteDocumentsParams{FilterBy: pointer.String("num_employees:>100"), BatchSize: pointer.Int(100)}
client.Collection("companies").Documents().Delete(context.Background(), filter)

Retrieve a collection

client.Collection("companies").Retrieve(context.Background())

Export documents from a collection

client.Collection("companies").Documents().Export(context.Background(), &api.ExportDocumentsParams{})

Import documents into a collection

The documents to be imported can be either an array of document objects or be formatted as a newline delimited JSON string (see JSONL).

Import an array of documents:

	documents := []interface{}{
		struct {
			ID           string `json:"id"`
			CompanyName  string `json:"companyName"`
			NumEmployees int    `json:"numEmployees"`
			Country      string `json:"country"`
		}{
			ID:           "123",
			CompanyName:  "Stark Industries",
			NumEmployees: 5215,
			Country:      "USA",
		},
	}
	params := &api.ImportDocumentsParams{
		Action:    pointer.Any(api.IndexActionCreate),
		BatchSize: pointer.Int(40),
	}

	client.Collection("companies").Documents().Import(context.Background(), documents, params)

Import a JSONL file:

	params := &api.ImportDocumentsParams{
		Action:    pointer.Any(api.IndexActionCreate),
		BatchSize: pointer.Int(40),
	}
	importBody, err := os.Open("documents.jsonl")
	// defer close, error handling ...

	client.Collection("companies").Documents().ImportJsonl(context.Background(), importBody, params)

List all collections

client.Collections().Retrieve(context.Background(), &api.GetCollectionsParams{})

Create an analytics rule

An analytics rule tells the server which events to record for a collection. This rule records click events on companies:

	rule := &api.AnalyticsRuleCreate{
		Name:       "company-clicks",
		Type:       api.AnalyticsRuleTypeLog,
		EventType:  "click",
		Collection: "companies",
	}
	client.Analytics().Rules().Create(context.Background(), rule)

When the server rejects the rule, Create returns *typesense.HTTPError. A second rule with the same name gets status 400 and Rule already exists.

api.AnalyticsRuleTypeCounter, api.AnalyticsRuleTypePopularQueries and api.AnalyticsRuleTypeNohitsQueries need Params as well. A counter rule needs CounterField and a Weight above 0. The two query rules need a DestinationCollection that exists and a Limit above 0. See analytics and query suggestions for what each type records.

Create several analytics rules

	responses, err := client.Analytics().Rules().CreateMany(context.Background(), []*api.AnalyticsRuleCreate{
		{Name: "company-visits", Type: api.AnalyticsRuleTypeLog, EventType: "visit", Collection: "companies"},
		{Name: "company-conversions", Type: api.AnalyticsRuleTypeLog, EventType: "conversion", Collection: "companies"},
	})
	// error handling ...
	for i, response := range responses {
		if response.Error != "" {
			fmt.Printf("rule %d was rejected: %s\n", i, response.Error)
		}
	}

The server answers 200 even when it rejects some of the rules. Responses come back in request order, and a rejected rule has Error set. The server creates the other rules anyway.

Create or update an analytics rule

Upsert creates the rule, or merges the request into the stored rule with that name. An update can't change Type, Collection or EventType.

	rule := &api.AnalyticsRuleCreate{
		Name:       "company-clicks",
		Type:       api.AnalyticsRuleTypeLog,
		EventType:  "click",
		Collection: "companies",
		RuleTag:    pointer.String("homepage"),
	}
	client.Analytics().Rules().Upsert(context.Background(), "company-clicks", rule)

List analytics rules

Pass nil to list every rule, or a RuleTag to list only the rules with that tag:

client.Analytics().Rules().Retrieve(context.Background(), nil)

client.Analytics().Rules().Retrieve(context.Background(), &api.RetrieveAnalyticsRulesParams{RuleTag: pointer.String("homepage")})

Retrieve an analytics rule

client.Analytics().Rule("company-clicks").Retrieve(context.Background())

When no rule has that name, the server answers 400 with Rule not found, and Retrieve returns *typesense.HTTPError.

Update an analytics rule

Update merges the fields you set into the stored rule. When no rule has that name, the server answers 400 and Update returns *typesense.HTTPError. Use Rules().Upsert to create a rule.

	update := &api.AnalyticsRuleUpdate{RuleTag: pointer.String("search-page")}
	client.Analytics().Rule("company-clicks").Update(context.Background(), update)

Delete an analytics rule

client.Analytics().Rule("company-clicks").Delete(context.Background())

Drop a collection

client.Collection("companies").Delete(context.Background())

Create an API Key

	keySchema := &api.ApiKeySchema{
		Description: "Search-only key.",
		Actions:     []string{"documents:search"},
		Collections: []string{"companies"},
		ExpiresAt:   pointer.Int64(time.Now().AddDate(0, 6, 0).Unix()),
	}

	client.Keys().Create(context.Background(), keySchema)

Retrieve an API Key

client.Key(1).Retrieve(context.Background())

List all keys

client.Keys().Retrieve(context.Background())

Delete API Key

client.Key(1).Delete(context.Background())

Create or update a curation set

A curation set holds rules that pin or hide documents for matching queries. The server applies a curation set to each collection that lists it in curation_sets. The generated api.CollectionSchema has no field for curation_sets yet. Step 5 of the migration guide sets it with a raw request. See curation for the rule options.

	curationSet := &api.CurationSetCreateSchema{
		Items: []api.CurationItemCreateSchema{
			{
				Id: pointer.String("customize-apple"),
				Rule: api.CurationRule{
					Query: pointer.String("apple"),
					Match: pointer.Any(api.CurationRuleMatchExact),
				},
				Includes: &[]api.CurationInclude{
					{
						Id:       "422",
						Position: 1,
					},
					{
						Id:       "54",
						Position: 2,
					},
				},
				Excludes: &[]api.CurationExclude{
					{
						Id: "287",
					},
				},
			},
		},
	}

	client.CurationSets().Upsert(context.Background(), "company-curations", curationSet)

Create or update a curation set item

	item := &api.CurationItemCreateSchema{
		Rule: api.CurationRule{
			Query: pointer.String("phone"),
			Match: pointer.Any(api.CurationRuleMatchContains),
		},
		Excludes: &[]api.CurationExclude{{Id: "287"}},
	}
	client.CurationSet("company-curations").Item("hide-287").Upsert(context.Background(), item)

Retrieve a curation set

client.CurationSet("company-curations").Retrieve(context.Background())

List all curation sets

client.CurationSets().Retrieve(context.Background())

List the items of a curation set

client.CurationSet("company-curations").Items().Retrieve(context.Background())

Delete a curation set item

client.CurationSet("company-curations").Item("hide-287").Delete(context.Background())

Delete a curation set

client.CurationSet("company-curations").Delete(context.Background())

Create or Update an alias

	body := &api.CollectionAliasSchema{CollectionName: "companies_june11"}
	client.Aliases().Upsert(context.Background(), "companies", body)

Retrieve an alias

client.Alias("companies").Retrieve(context.Background())

List all aliases

client.Aliases().Retrieve(context.Background())

Delete an alias

client.Alias("companies").Delete(context.Background())

Create or update a synonym set

A synonym set holds synonym rules. A search uses the synonym sets in its collection's SynonymSets field, plus any it names in the SynonymSets search parameter. See synonyms for the rule options.

	synonymSet := &api.SynonymSetCreateSchema{
		Items: []api.SynonymItemSchema{
			{
				Id:       "coat-synonyms",
				Synonyms: []string{"blazer", "coat", "jacket"},
			},
		},
	}
	client.SynonymSets().Upsert(context.Background(), "clothing-synonyms", synonymSet)

Create or update a one-way synonym in a synonym set

	synonym := &api.SynonymItemUpsertSchema{
		Root:     pointer.String("blazer"),
		Synonyms: []string{"blazer", "coat", "jacket"},
	}
	client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Upsert(context.Background(), synonym)

Retrieve a synonym

client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Retrieve(context.Background())

List all synonyms in a synonym set

client.SynonymSet("clothing-synonyms").Items().Retrieve(context.Background())

Delete a synonym

client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Delete(context.Background())

Delete a synonym set

client.SynonymSet("clothing-synonyms").Delete(context.Background())

Create or update a stopwords set

	stopwords := &api.StopwordsSetUpsertSchema{
		Locale:    pointer.String("en"),
		Stopwords: []string{"Germany", "France", "Italy", "United States"},
	}
	client.Stopwords().Upsert(context.Background(), "stopword_set1", stopwords)

Retrieve a stopwords set

client.Stopword("stopword_set1").Retrieve(context.Background())

List all stopwords sets

client.Stopwords().Retrieve(context.Background())

Delete a stopwords set

client.Stopword("stopword_set1").Delete(context.Background())

Create or update a preset

preset := &api.PresetUpsertSchema{}
preset.Value.FromMultiSearchSearchesParameter(api.MultiSearchSearchesParameter{
		Searches: []api.MultiSearchCollectionParameters{
			{
				Collection: pointer.String("books"),
			},
		},
	})
// or: preset.Value.FromSearchParameters(api.SearchParameters{Q: "Books"})

client.Presets().Upsert(context.Background(), "listing-view-preset", preset)

Retrieve a preset

client.Preset("listing-view-preset").Retrieve(context.Background())

List all presets

client.Presets().Retrieve(context.Background())

Delete a preset

client.Preset("listing-view-preset").Delete(context.Background())

Create snapshot (for backups)

client.Operations().Snapshot(context.Background(), "/tmp/typesense-data-snapshot")

Re-elect Leader

client.Operations().Vote(context.Background())

Cluster Metrics

client.Metrics().Retrieve(context.Background())

API Stats

client.Stats().Retrieve(context.Background())

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/typesense/typesense-go.

Development Workflow Setup

Install dependencies,

go mod download

Update the generated files,

go generate ./...

Run all tests

# In Windows Powershell
# $env:TYPESENSE_API_KEY="xyz"
# $env:TYPESENSE_URL="http://localhost:8108"

export TYPESENSE_URL="http://localhost:8108"
export TYPESENSE_API_KEY="xyz"

go test ./... -tags=integration -v

License

typesense-go is distributed under the Apache 2 license.