Go client for the Typesense API: https://github.com/typesense/typesense
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.
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.
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)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()) 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{}) 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{}) 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)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,LimitandLimitHitsonly 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.
client.Collection("companies").Document("123").Retrieve(context.Background()) 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{})client.Collection("companies").Document("123").Delete(context.Background())filter := &api.DeleteDocumentsParams{FilterBy: pointer.String("num_employees:>100"), BatchSize: pointer.Int(100)}
client.Collection("companies").Documents().Delete(context.Background(), filter)client.Collection("companies").Retrieve(context.Background())client.Collection("companies").Documents().Export(context.Background(), &api.ExportDocumentsParams{})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)client.Collections().Retrieve(context.Background(), &api.GetCollectionsParams{})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.
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.
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)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")})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 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)client.Analytics().Rule("company-clicks").Delete(context.Background())client.Collection("companies").Delete(context.Background()) 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)client.Key(1).Retrieve(context.Background())client.Keys().Retrieve(context.Background())client.Key(1).Delete(context.Background())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) 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)client.CurationSet("company-curations").Retrieve(context.Background())client.CurationSets().Retrieve(context.Background())client.CurationSet("company-curations").Items().Retrieve(context.Background())client.CurationSet("company-curations").Item("hide-287").Delete(context.Background())client.CurationSet("company-curations").Delete(context.Background()) body := &api.CollectionAliasSchema{CollectionName: "companies_june11"}
client.Aliases().Upsert(context.Background(), "companies", body)client.Alias("companies").Retrieve(context.Background())client.Aliases().Retrieve(context.Background())client.Alias("companies").Delete(context.Background())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) synonym := &api.SynonymItemUpsertSchema{
Root: pointer.String("blazer"),
Synonyms: []string{"blazer", "coat", "jacket"},
}
client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Upsert(context.Background(), synonym)client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Retrieve(context.Background())client.SynonymSet("clothing-synonyms").Items().Retrieve(context.Background())client.SynonymSet("clothing-synonyms").Item("coat-synonyms").Delete(context.Background())client.SynonymSet("clothing-synonyms").Delete(context.Background()) stopwords := &api.StopwordsSetUpsertSchema{
Locale: pointer.String("en"),
Stopwords: []string{"Germany", "France", "Italy", "United States"},
}
client.Stopwords().Upsert(context.Background(), "stopword_set1", stopwords)client.Stopword("stopword_set1").Retrieve(context.Background())client.Stopwords().Retrieve(context.Background())client.Stopword("stopword_set1").Delete(context.Background())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)client.Preset("listing-view-preset").Retrieve(context.Background())client.Presets().Retrieve(context.Background())client.Preset("listing-view-preset").Delete(context.Background())client.Operations().Snapshot(context.Background(), "/tmp/typesense-data-snapshot")client.Operations().Vote(context.Background())client.Metrics().Retrieve(context.Background())client.Stats().Retrieve(context.Background())Bug reports and pull requests are welcome on GitHub at https://github.com/typesense/typesense-go.
Install dependencies,
go mod downloadUpdate 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 -vtypesense-go is distributed under the Apache 2 license.