Untitled record
masterTo install the Typesense Go client, use the following command:
go get github.com/typesense/typesense-go/v4/typesenserepository·master·Indexed 43 days ago
https://github.com/typesense/typesense-goThe official Go client library for the Typesense search engine API. It provides a type-safe and idiomatic way to manage collections, index documents, perform searches, and configure advanced features like synonyms, overrides, and curation sets. Includes built-in support for multi-node high availability, circuit breakers, and bulk import/export via JSONL.
To install the Typesense Go client, use the following command:
go get github.com/typesense/typesense-go/v4/typesenseImport the package and use typesense.NewClient to create a client. You can provide various configuration options using functional options.
import "github.com/typesense/typesense-go/v4/typesense"
client := typesense.NewClient(
typesense.WithServer("http://localhost:8108"),
typesense.WithAPIKey("<API_KEY>"),
)Use options like WithConnectionTimeout, WithCircuitBreakerMaxRequests, WithCircuitBreakerInterval, and WithCircuitBreakerTimeout for fine-grained control.
For high availability, configure multiple nodes using WithNearestNode and WithNodes:
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),
)client := typesense.NewClient(
typesense.WithServer("http://localhost:8108"),
typesense.WithAPIKey("<API_KEY>"),
)Use NewClient to create a new Typesense client. You can configure the client using functional options to set the server URL, API key, connection timeouts, retries, and circuit breaker settings.
Common configuration options include:
WithServer(url string): Sets the primary API server URL.WithAPIKey(key string): Sets the API token for authentication.WithNodes(urls []string): Sets multiple hostnames for load balancing reads and writes.WithNearestNode(url string): Sets a specific load-balanced endpoint.WithConnectionTimeout(duration time.Duration): Sets the HTTP client connection timeout (default 5s).WithNumRetries(num int): Sets the number of retries per request.WithCustomHTTPClient(client *http.Client): Provides a custom HTTP client.import "github.com/typesense/typesense-go/v4/typesense"
client := typesense.NewClient(
typesense.WithServer("http://localhost:8108"),
typesense.WithAPIKey("xyz"),
typesense.WithConnectionTimeout(10 * time.Second),
)Efficiently move data in and out of collections.
params := &api.ImportDocumentsParams{
Action: pointer.String("create"),
BatchSize: pointer.Int(40),
}
client.Collection("companies").Documents().Import(context.Background(), documents, params) Action: pointer.String("create"),
BatchSize: pointer.Int(40),
}
importBody, err := os.Open("documents.jsonl")
// ... handle error and defer close
client.Collection("companies").Documents().ImportJsonl(context.Background(), importBody, params)client.Collection("companies").Documents().Export(context.Background())// Import array
client.Collection("companies").Documents().Import(context.Background(), documents, params)
// Import JSONL
client.Collection("companies").Documents().ImportJsonl(context.Background(), importBody, params)
// Export
client.Collection("companies
).Documents().Export(context.Background())Perform standard CRUD operations on documents within a collection.
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) 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) CompanyName string `json:"company_name"`
NumEmployees int `json:"num_employees"`
}{
CompanyName: "Stark Industries",
NumEmployees: 5500,
}
client.Collection("companies").Document("123").Update(context.Background(), document)// Index
client.Collection("companies").Documents().Create(context.Background(), document)
// Upsert
client.Collection("companies").Documents().Upsert(context.Background(), newDocument)
// Update
client.Collection("companies").Document("123").Update(context.Background(), document)Configure how search terms relate to each other using multi-way or one-way synonyms.
All terms in the list are treated as synonyms for each other.
synonym := &api.SearchSynonymSchema{
Synonyms: []string{"blazer", "coat", "jacket"},
}
client.Collection("products").Synonyms().Upsert(context.Background(), "coat-synonyms", synonym)Specifies a Root term that maps to a list of synonyms.
synonym := &api.SearchSynonymSchema{
Root: "blazer",
Synonyms: []string{"blazer", "coat", "jacket"},
}
client.Collection("products").Synonyms().Upsert(context.Background(), "coat-synonyms", synonym)// Retrieve
client.Collection("products").Synonym("coat-synonyms").Retrieve(context.Background())
// List all
client.Collection("products").Synonyms().Retrieve(context.Background())
// Delete
client.Collection("products").Synonym("coat-synonyms").Delete(context.Background())// Multi-way
synonym := &api.SearchSynonymSchema{
Synonyms: []string{"blazer", "coat", "jacket"},
}
client.Collection("products").Synonyms().Upsert(context.Background(), "coat-synonyms", synonym)
// One-way
synonym := &api.SearchSynonymSchema{
Root: "blazer",
Synonyms: []string{"blazer", "coat", "jacket"},
}
client.Collection("products").Synonyms().Upsert(context.Background(), "coat-synonyms", synonym)The client includes a built-in circuit breaker to prevent cascading failures. You can customize its behavior using the following options:
WithCircuitBreakerName(name string): Sets the name (default: "typesenseClient").WithCircuitBreakerMaxRequests(max uint32): Max requests allowed in half-open state (default: 50).WithCircuitBreakerInterval(interval time.Duration): Cyclic period to clear internal counts in closed state (default: 2m).WithCircuitBreakerTimeout(timeout time.Duration): Period the circuit stays open before moving to half-open (default: 1m).WithCircuitBreakerReadyToTrip(fn): Custom logic to determine when to trip the circuit.WithCircuitBreakerOnStateChange(fn): Callback triggered when the circuit state changes.To authenticate requests to Typesense, use the WithAPIKey option when initializing your client. This adds the X-TYPESENSE-API-KEY header to all outgoing requests. The header name is defined by the APIKeyHeader constant.
import "github.com/typesense/typesense-go/api"
// Example usage during client initialization
client, err := api.NewClient(
api.WithAPIKey("your_api_key_here"),
)The Client acts as an entry point for all Typesense API namespaces. Use the following methods to access specific resource managers:
Aliases() / Alias(name): Manage search aliases.SynonymSets() / SynonymSet(name): Manage synonym sets.CurationSets() / CurationSet(name): Manage curation sets.Keys() / Key(id): Manage API keys.Preset(name): Access search presets.NLSearchModels() / NLSearchModel(id): Manage Natural Language search models.Stopwords() / Stopword(id): Manage stopword sets.MultiSearch: Perform multi-search queries.Analytics(), Stemming(), Conversations(), Operations(), Stats(), Metrics(): Access specialized API endpoints.The Client provides access to various Typesense resources. To interact with a specific collection, use Collections() to manage all collections or Collection(name) to interact with a specific one using map[string]any.
For type-safe operations, use GenericCollection[T](client, collectionName) where T is a struct representing your document schema.
// Using map[string]any for dynamic documents
collection := client.Collection("products")
// Using a custom struct for typed operations
type Product struct {
ID string `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
}
productCollection := typesense.GenericCollection[Product](client, "products")The Typesense Go client uses the X-TYPESENSE-API-KEY header for authentication. This is exposed via the APIKeyHeader constant.
const APIKeyHeader = "X-TYPESENSE-API-KEY"When an API call fails due to an HTTP error, the client returns an HTTPError. This error type contains the status code and the raw response body, which can be used for debugging or programmatic error handling.
type HTTPError struct {
Status int
Body []byte
}