### Testing Setup with Docker and Client Initialization Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Set up a testing environment for the Typesense Go client. This example shows how to initialize the client for testing, including checking server availability and skipping tests if the server is not ready. ```go // Using docker: // docker run -p 8108:8108 typesense/typesense:latest --data-dir=/tmp/typesense-server-data import "testing" var client *typesense.Client func setup(t *testing.T) { var err error client, err = typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), ) if err != nil { t.Fatal(err) } // Check server is ready healthy, err := client.Health(context.Background(), 5*time.Second) if err != nil || !healthy { t.Skip("Typesense server not available") } } ``` -------------------------------- ### Install typesense-go Client Source: https://github.com/typesense/typesense-go/blob/master/README.md Use `go get` to install the typesense-go client library. ```bash go get github.com/typesense/typesense-go/v4/typesense ``` -------------------------------- ### Configure Circuit Breaker with Example Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md An example demonstrating how to configure various circuit breaker settings including max requests, interval, and timeout when initializing the Typesense client. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), typesense.WithCircuitBreakerMaxRequests(100), typesense.WithCircuitBreakerInterval(5*time.Minute), typesense.WithCircuitBreakerTimeout(2*time.Minute), ) ``` -------------------------------- ### Multi-Node Client Setup Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Configure a Typesense client for a multi-node setup, specifying nearest node, a list of nodes, API key, and retry count. ```go client := typesense.NewClient( typesense.WithNearestNode("https://nearest.typesense.net:443"), typesense.WithNodes([]string{ "https://node1.typesense.net:443", "https://node2.typesense.net:443", "https://node3.typesense.net:443", }), typesense.WithAPIKey("xyz"), typesense.WithNumRetries(5), ) ``` -------------------------------- ### Install Dependencies Source: https://github.com/typesense/typesense-go/blob/master/README.md Installs project dependencies using Go modules. ```bash go mod download ``` -------------------------------- ### Synonym Set Creation Examples Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/types.md Demonstrates how to create both multi-way and one-way synonym sets using the SynonymSetCreateSchema. ```go // Multi-way synonym schema := &api.SynonymSetCreateSchema{ Synonyms: []string{"blazer", "coat", "jacket"}, } ``` ```go // One-way synonym schema := &api.SynonymSetCreateSchema{ Root: "blazer", Synonyms: []string{"blazer", "coat", "jacket"}, } ``` -------------------------------- ### Example SearchCollectionParams Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/types.md Demonstrates how to set up search parameters for a collection query, specifying search terms, fields, filters, and result limits. ```go params := &api.SearchCollectionParams{ Q: pointer.String("laptop"), QueryBy: pointer.String("title,description"), FilterBy: pointer.String("price:>1000"), SortBy: &([]string{"popularity:desc", "price:asc"}), Limit: pointer.Int(20), Offset: pointer.Int(0), } ``` -------------------------------- ### Create Typesense Client for Multi-Node Setup Source: https://github.com/typesense/typesense-go/blob/master/README.md Configure a Typesense client for a multi-node cluster, specifying nearest node, other nodes, and retry configurations. ```go 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(""), typesense.WithNumRetries(5), typesense.WithRetryInterval(1*time.Second), typesense.WithHealthcheckInterval(2*time.Minute), ) ``` -------------------------------- ### Retrieve All Presets Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Retrieves all presets. Use this to get a list of all saved search configurations. ```go func (p *PresetsInterface) Retrieve(ctx context.Context) ([]*api.PresetSchema, error) ``` ```go presets, err := client.Presets().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, preset := range presets { fmt.Printf("Preset: %s\n", preset.Name) } ``` -------------------------------- ### Retrieve All Presets Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Retrieves all configured presets in Typesense. Use this to get a list of all available preset configurations. ```go p.Retrieve(ctx) ``` -------------------------------- ### Get Metrics Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for retrieving server metrics. No parameters are required. ```go func (c *Client) Metrics() MetricsInterface ``` -------------------------------- ### Example of Circuit Breaker State Change Callback Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Demonstrates how to implement and provide a callback function to log circuit breaker state transitions when initializing the Typesense client. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), typesense.WithCircuitBreakerOnStateChange(func(name string, from, to string) { log.Printf("Circuit breaker %s: %s -> %s\n", name, from, to) }), ) ``` -------------------------------- ### Example Field Definitions for Collection Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/types.md Illustrates how to define multiple fields for a collection schema, including setting options like sorting and faceting. ```go fields := []api.Field{ { Name: "company_name", Type: "string", }, { Name: "num_employees", Type: "int32", Sort: pointer.Bool(true), }, { Name: "country", Type: "string", Facet: pointer.Bool(true), }, } ``` -------------------------------- ### Initialize Typesense Client Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Create a new Typesense client with server and API key configuration. Supports single node or multi-node setups with optional retry and health check intervals. ```go import "github.com/typesense/typesense-go/v4/typesense" client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz")) ``` ```go // Multi-node configuration 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(""), typesense.WithNumRetries(5), typesense.WithRetryInterval(1*time.Second), typesense.WithHealthcheckInterval(2*time.Minute), ) ``` -------------------------------- ### Example Search Result Processing Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/types.md Shows how to execute a search query using the typesense-go client and process the returned results, including iterating through hits and displaying document details. ```go result, err := client.Collection("products").Documents().Search(ctx, params) if err != nil { log.Fatal(err) } fmt.Printf("Found %d hits\n", result.Found) for _, hit := range result.Hits { doc := hit.Document.(map[string]interface{}) fmt.Printf("Score: %.2f, Document: %v\n", hit.TextMatch, doc) } ``` -------------------------------- ### Get Preset Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns an interface for operations on a specific search preset. Requires the preset name. ```go func (c *Client) Preset(presetName string) PresetInterface ``` -------------------------------- ### Get Presets Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for all search preset operations. No parameters are required. ```go func (c *Client) Presets() PresetsInterface ``` -------------------------------- ### Handle 404 Not Found Error Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/errors.md Example for handling a 404 Not Found error, which indicates that a requested resource such as a collection, document, or key does not exist. This can occur if you try to retrieve a non-existent document. ```go doc, err := client.Collection("nonexistent").Document("123").Retrieve(context.Background()) if err != nil { if httpErr, ok := err.(*typesense.HTTPError); ok { if httpErr.Status == 404 { fmt.Println("Document not found") } } } ``` -------------------------------- ### Get SynonymSet Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns an interface for operations on a specific synonym set. Requires the synonym set name. ```go func (c *Client) SynonymSet(synonymSetName string) SynonymSetInterface ``` -------------------------------- ### Document Indexing with DirtyValues Parameter Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Configure how to handle fields with invalid data types during document creation or upsert operations. This example demonstrates coercing or dropping invalid fields. ```go params := &api.DocumentIndexParameters{ DirtyValues: pointer.Any(api.CoerceOrDrop), } client.Collection("companies").Documents().Create(context.Background(), doc, params) ``` -------------------------------- ### Retrieve All Stopwords Sets Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Retrieves all stopwords sets configured in Typesense. Use this to get a list of all available stopwords configurations. ```go stopwordsSets, err := client.Stopwords().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, set := range stopwordsSets { fmt.Printf("Stopwords Set: %s\n", set.Id) } ``` -------------------------------- ### Handle 400 Bad Request Error Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/errors.md Example of how to check for and handle a 400 Bad Request error, which occurs due to malformed requests or invalid parameters. This often happens with incorrect filter syntax or missing query parameters. ```go result, err := client.Collection("companies").Documents().Search(context.Background(), &api.SearchCollectionParams{ Q: pointer.String("test"), // Missing QueryBy parameter }) if err != nil { if httpErr, ok := err.(*typesense.HTTPError); ok { if httpErr.Status == 400 { fmt.Printf("Bad request: %s\n", string(httpErr.Body)) } } } ``` -------------------------------- ### Handle Typesense HTTP Errors Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md This example demonstrates how to catch and process HTTP errors returned by the Typesense client. It checks if the error is of type typesense.HTTPError and prints the status code and body. ```go collection := client.Collection("companies") response, err := collection.Retrieve(ctx) if err != nil { if httpErr, ok := err.(*typesense.HTTPError); ok { fmt.Printf("HTTP Error %d: %s\n", httpErr.Status, string(httpErr.Body)) } } ``` -------------------------------- ### Get CurationSets Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for all curation operations. No parameters are required. ```go func (c *Client) CurationSets() CurationSetsInterface ``` -------------------------------- ### Get Stats Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for retrieving API statistics. No parameters are required. ```go func (c *Client) Stats() StatsInterface ``` -------------------------------- ### Basic Client Creation Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Create a new Typesense client for a single server instance. Ensure the server address and API key are correctly provided. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz")) ``` -------------------------------- ### Get Conversations Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for conversation model operations. No parameters are required. ```go func (c *Client) Conversations() ConversationsInterface ``` -------------------------------- ### Configure Client with ClientConfig Struct Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use this option to set all client configurations at once using a ClientConfig struct. This is useful for initializing the client with a comprehensive set of parameters. ```go config := &typesense.ClientConfig{ ServerURL: "http://localhost:8108", APIKey: "xyz", NumRetries: 5, ConnectionTimeout: 10 * time.Second, CircuitBreakerMaxRequests: 100, } client := typesense.NewClient( typesense.WithClientConfig(config), ) ``` -------------------------------- ### Get Stemming Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for stemming dictionary operations. No parameters are required. ```go func (c *Client) Stemming() StemmingInterface ``` -------------------------------- ### Create Snapshot Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Creates a point-in-time backup of the Typesense data directory. Use this to back up your data. ```go success, err := client.Operations().Snapshot(context.Background(), "/tmp/typesense-snapshot") if err != nil { log.Fatal(err) } if success { fmt.Println("Snapshot created successfully") } ``` -------------------------------- ### Get Stopwords Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for all stopwords set operations. No parameters are required. ```go func (c *Client) Stopwords() StopwordsInterface ``` -------------------------------- ### Create Typesense Client with Advanced Options Source: https://github.com/typesense/typesense-go/blob/master/README.md Configure a Typesense client with advanced settings like connection timeouts and circuit breaker parameters. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey(""), typesense.WithConnectionTimeout(5*time.Second), typesense.WithCircuitBreakerMaxRequests(50), typesense.WithCircuitBreakerInterval(2*time.Minute), typesense.WithCircuitBreakerTimeout(1*time.Minute), ) ``` -------------------------------- ### Get Operations Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for cluster operations, such as snapshot and vote. No parameters are required. ```go func (c *Client) Operations() OperationsInterface ``` -------------------------------- ### Client Entry Point Function Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md The main entry point for creating a Typesense client. It accepts a variadic number of ClientOption arguments to configure the client's behavior. ```go client := typesense.NewClient(opts ...ClientOption) *Client ``` -------------------------------- ### Package Import Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Import the Typesense Go client package. ```go import "github.com/typesense/typesense-go/v4/typesense" ``` -------------------------------- ### Get NLSearchModels Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for natural language search model operations. No parameters are required. ```go func (c *Client) NLSearchModels() NLSearchModelsInterface ``` -------------------------------- ### Get Analytics Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns the manager for analytics operations, including event and rule operations. No parameters are required. ```go func (c *Client) Analytics() AnalyticsInterface ``` -------------------------------- ### Thread-Safe Client Initialization and Usage Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Initialize a single client instance and safely share it across multiple goroutines for concurrent operations. This pattern ensures efficient resource utilization and avoids race conditions. ```go // Safe to use from multiple goroutines var client = typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), ) // All of these can run concurrently go func() { client.Collections().Retrieve(ctx, nil) }() go func() { client.Collection("products").Documents().Search(ctx, searchParams) }() ``` -------------------------------- ### Get Stopword Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns an interface for operations on a specific stopwords set. Requires the stopwords set ID. ```go func (c *Client) Stopword(stopwordsSetId string) StopwordInterface ``` -------------------------------- ### Configure Single Typesense Server Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use `WithServer` to set the base URL for a single Typesense server instance. This is suitable for single-node deployments. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), ) ``` -------------------------------- ### Get CurationSet Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns an interface for operations on a specific curation set. Requires the curation set name. ```go func (c *Client) CurationSet(curationSetName string) CurationSetInterface ``` -------------------------------- ### Create Snapshot for Backups Source: https://github.com/typesense/typesense-go/blob/master/README.md Creates a snapshot of the Typesense data for backup purposes. Specify the directory path for the snapshot. ```go client.Operations().Snapshot(context.Background(), "/tmp/typesense-data-snapshot") ``` -------------------------------- ### Retrieve Collection Metadata Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/collection-operations.md Retrieves metadata and schema for a specific collection. Use this to get information about an existing collection. ```go response, err := client.Collection("companies").Retrieve(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Collection: %s\n", response.Name) fmt.Printf("Fields: %v\n", response.Fields) fmt.Printf("Default Sort: %v\n", response.DefaultSortingField) ``` -------------------------------- ### NewClient Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Creates and initializes a new Typesense client with optional configuration. This is the primary entry point for using the Typesense Go SDK. ```APIDOC ## NewClient ### Description Creates and initializes a new Typesense client with optional configuration. ### Method `func NewClient(opts ...ClientOption) *Client` ### Parameters #### Path Parameters - **opts** (...ClientOption) - Required - Variable number of configuration options ### Returns - `*Client` - Configured Typesense client ### Example ```go import "github.com/typesense/typesense-go/v4/typesense" client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz")) // Multi-node configuration 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(""), typesense.WithNumRetries(5), typesense.WithRetryInterval(1*time.Second), typesense.WithHealthcheckInterval(2*time.Minute), ) ``` ``` -------------------------------- ### Retrieve Debug Information from Typesense Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Call this method to get debug information from the Typesense server. It only requires a context for the request. ```go response, err := client.Debug(ctx) ``` -------------------------------- ### Get NLSearchModel Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Returns an interface for operations on a specific natural language search model. Requires the model ID. ```go func (c *Client) NLSearchModel(modelID string) NLSearchModelInterface ``` -------------------------------- ### WithServer Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Sets a single Typesense server URL for the client. This is a functional option used during client initialization. ```APIDOC ## WithServer ### Description Sets a single Typesense server URL. ### Method ClientOption ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), ) ``` ### Response N/A ``` -------------------------------- ### Client Configuration with Functional Options Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Configure the Typesense client using functional options passed to `NewClient`. This allows for flexible customization of server details, authentication, retry behavior, connection timeouts, and circuit breaker settings. ```go client := typesense.NewClient( // Server typesense.WithServer("http://localhost:8108"), // Authentication typesense.WithAPIKey("xyz"), // Retry behavior typesense.WithNumRetries(5), typesense.WithRetryInterval(100 * time.Millisecond), // Connection typesense.WithConnectionTimeout(5 * time.Second), typesense.WithHealthcheckInterval(1 * time.Minute), // Circuit breaker typesense.WithCircuitBreakerMaxRequests(50), typesense.WithCircuitBreakerInterval(2 * time.Minute), typesense.WithCircuitBreakerTimeout(1 * time.Minute), ) ``` -------------------------------- ### Configure Client with Custom API Client Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use this advanced option to provide a completely custom API client implementation. This is not commonly used and is intended for highly specialized scenarios. ```go func WithAPIClient(apiClient APIClientInterface) ClientOption ``` -------------------------------- ### Get Aliases Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Access the Aliases manager to perform operations related to alias management. This includes upserting and retrieving aliases. ```go aliases := client.Aliases() ``` -------------------------------- ### Configure Client with Custom HTTP Client Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Provide a custom http.Client for advanced network configurations, such as setting timeouts and transport options. This allows for fine-grained control over network requests. ```go httpClient := &http.Client{ Timeout: 15 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 100, DisableKeepAlives: false, }, } client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), typesense.WithCustomHTTPClient(httpClient), ) ``` -------------------------------- ### Create a Collection Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Defines the schema for a new collection and then creates it using the Typesense client. Ensure the schema fields and types are correctly specified. ```go schema := &api.CollectionSchema{ Name: "products", Fields: []api.Field{ {Name: "name", Type: "string"}, {Name: "price", Type: "float"}, {Name: "category", Type: "string", Facet: true}, }, DefaultSortingField: pointer.String("price"), } response, err := client.Collections().Create(ctx, schema) ``` -------------------------------- ### Curation Retrieve (All) Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/synonyms-and-curation.md Retrieves all curation sets available in the system. This is useful for getting an overview of all manually managed search result sets. ```APIDOC ## Curation Retrieve (All) ### Description Retrieves all curation sets. ### Method Not applicable (Go SDK method) ### Endpoint Not applicable (Go SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go curations, err := client.CurationSets().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, curation := range curations { fmt.Printf("Curation: %s (Query: %s)\n", curation.Id, curation.Rule.Query) } ``` ### Response #### Success Response (200) - **curations** ([]api.CurationSetSchema) - Array of curation sets #### Response Example ```go // Example response structure (actual fields may vary) [ { "id": "apple-curation", "rule": { "query": "apple", "match": "exact" }, "includes": [ { "id": "422", "position": 1 } ], "excludes": [] } ] ``` ``` -------------------------------- ### Run Integration Tests Source: https://github.com/typesense/typesense-go/blob/master/README.md Executes all integration tests with verbose output. Requires setting environment variables for Typesense URL and API key. ```bash # 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 ``` -------------------------------- ### Retrieve All Collections Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/collections.md Retrieves a list of all collections in Typesense. Pass `nil` for parameters to get all collections. Useful for listing existing collections. ```go // Retrieve all collections collections, err := client.Collections().Retrieve(context.Background(), nil) if err != nil { log.Fatal(err) } for _, col := range collections { fmt.Printf("Collection: %s (ID: %s)\n", col.Name, col.Id) } ``` -------------------------------- ### Create API Key Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/keys.md Creates a new API key with specified permissions and restrictions. Ensure you have the necessary permissions to create keys. ```go import ( "github.com/typesense/typesense-go/v4/typesense" "github.com/typesense/typesense-go/v4/typesense/api" "github.com/typesense/typesense-go/v4/typesense/api/pointer" ) keySchema := &api.ApiKeySchema{ Description: "Search-only key for products collection", Actions: []string{"documents:search"}, Collections: []string{"products"}, ExpiresAt: pointer.Int64(time.Now().AddDate(0, 6, 0).Unix()), } apiKey, err := client.Keys().Create(context.Background(), keySchema) if err != nil { log.Fatal(err) } fmt.Printf("Created API key with ID: %d, Value: %s\n", apiKey.Id, apiKey.Value) ``` -------------------------------- ### Create an API Key Source: https://github.com/typesense/typesense-go/blob/master/README.md Creates a new API key with specified actions, collections, and expiration. ```go keySchema := &api.ApiKeySchema{ Description: "Search-only key.", Actions: []string{"documents:search"}, Collections: []string{"companies"}, ExpiresAt: time.Now().AddDate(0, 6, 0).Unix(), } client.Keys().Create(context.Background(), keySchema) ``` -------------------------------- ### Update Documents Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Updates existing documents in a collection based on a filter. This example updates the 'price' field for documents matching a specific filter. ```go count, err := client.Collection("products").Documents().Update(ctx, map[string]interface{}{"price": 799.99}, &api.UpdateDocumentsParams{FilterBy: "name:Laptop"}), ) ``` -------------------------------- ### Create or Update a Preset Source: https://github.com/typesense/typesense-go/blob/master/README.md Creates or updates a preset with specified search parameters. Presets can be defined using multi-search or single search parameters. ```go preset := &api.PresetUpsertSchema{} preset.Value.FromMultiSearchSearchesParameter(api.MultiSearchSearchesParameter{ Searches: []api.MultiSearchCollectionParameters{ { Collection: "books", }, }, }) // or: preset.Value.FromSearchParameters(api.SearchParameters{Q: "Books"}) client.Presets().Upsert(context.Background(), "listing-view-preset", preset) ``` -------------------------------- ### Search a Collection with Basic Parameters Source: https://github.com/typesense/typesense-go/blob/master/README.md Perform a search operation on a collection using basic parameters like query string, fields to query by, filtering, and sorting. ```go searchParameters := &api.SearchCollectionParams{ Q: pointer.String("stark"), QueryBy: pointer.String("company_name"), FilterBy: pointer.String("num_employees:>100"), SortBy: &([]string{"num_employees:desc"}), } client.Collection("companies").Documents().Search(context.Background(), searchParameters) ``` -------------------------------- ### Get Collections Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Access the Collections manager to perform CRUD operations on collections. This is the entry point for managing your collection schemas and data. ```go collections := client.Collections() ``` -------------------------------- ### Get Keys Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Access the Keys manager for managing API keys. This manager provides functionalities to create, retrieve, and generate scoped search keys. ```go keys := client.Keys() ``` -------------------------------- ### Get Specific Alias Resource Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Obtain an Alias resource interface to perform operations on a specific alias by its name. Supports retrieving and deleting a particular alias. ```go alias := client.Alias("my-alias") ``` -------------------------------- ### Import Documents into a Collection (Array) Source: https://github.com/typesense/typesense-go/blob/master/README.md Imports documents into a collection using an array of document objects. Specify action and batch size. ```go 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.String("create"), BatchSize: pointer.Int(40), } client.Collection("companies").Documents().Import(context.Background(), documents, params) ``` -------------------------------- ### Get Specific Collection Resource Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Obtain a Collection resource interface to perform operations on a specific collection by its name. Requires the collection name as a string parameter. ```go collection := client.Collection("companies") schema, err := collection.Retrieve(ctx) ``` -------------------------------- ### Configure Connection Timeout Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use `WithConnectionTimeout` to set the total timeout for HTTP requests. The default is 5 seconds. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), typesense.WithConnectionTimeout(10*time.Second), ) ``` -------------------------------- ### List All API Keys Source: https://github.com/typesense/typesense-go/blob/master/README.md Retrieves a list of all API keys in the Typesense instance. ```go client.Keys().Retrieve(context.Background()) ``` -------------------------------- ### Get Synonym Sets Manager Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Access the Synonym Sets manager for managing synonym rules within your Typesense instance. Supports upserting and retrieving synonym sets. ```go synonymSets := client.SynonymSets() ``` -------------------------------- ### Import Documents into a Collection (JSONL) Source: https://github.com/typesense/typesense-go/blob/master/README.md Imports documents into a collection from a newline-delimited JSON file. Specify action and batch size. ```go params := &api.ImportDocumentsParams{ Action: pointer.String("create"), BatchSize: pointer.Int(40), } importBody, err := os.Open("documents.jsonl") // defer close, error handling ... client.Collection("companies").Documents().ImportJsonl(context.Background(), importBody, params) ``` -------------------------------- ### Retrieve a Preset Source: https://github.com/typesense/typesense-go/blob/master/README.md Retrieves a specific preset by its name. ```go client.Preset("listing-view-preset").Retrieve(context.Background()) ``` -------------------------------- ### WithCustomHTTPClient Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Provides a custom HTTP client for advanced network configuration. This allows users to specify detailed settings for the underlying HTTP transport, such as timeouts and connection pooling. ```APIDOC ## WithCustomHTTPClient ### Description Provides a custom HTTP client for advanced network configuration. This allows users to specify detailed settings for the underlying HTTP transport, such as timeouts and connection pooling. ### Method Signature ```go func WithCustomHTTPClient(client *http.Client) ClientOption ``` ### Parameters #### client - **client** (*http.Client) - Custom HTTP client ### Example ```go httpClient := &http.Client{ Timeout: 15 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 100, DisableKeepAlives: false, }, } client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("xyz"), typesense.WithCustomHTTPClient(httpClient), ) ``` ``` -------------------------------- ### WithClientConfig Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Sets all configuration at once using a ClientConfig struct. This option allows for comprehensive configuration of the Typesense client, including server URLs, retry mechanisms, timeouts, and circuit breaker settings. ```APIDOC ## WithClientConfig ### Description Sets all configuration at once using a ClientConfig struct. This option allows for comprehensive configuration of the Typesense client, including server URLs, retry mechanisms, timeouts, and circuit breaker settings. ### Method Signature ```go func WithClientConfig(config *ClientConfig) ClientOption ``` ### Parameters #### ClientConfig Struct - **ServerURL** (string) - Single server URL - **NearestNode** (string) - Load-balanced endpoint - **Nodes** ([]string) - Multiple node URLs - **NumRetries** (int) - Number of retries - **RetryInterval** (time.Duration) - Wait between retries - **HealthcheckInterval** (time.Duration) - Unhealthy node check interval - **APIKey** (string) - API authentication key - **ConnectionTimeout** (time.Duration) - HTTP request timeout - **CircuitBreakerName** (string) - Circuit breaker identifier - **CircuitBreakerMaxRequests** (uint32) - Max requests in half-open - **CircuitBreakerInterval** (time.Duration) - Failure count reset period - **CircuitBreakerTimeout** (time.Duration) - Open state duration - **CircuitBreakerReadyToTrip** (func) - Custom trip function - **CircuitBreakerOnStateChange** (func) - State change callback ### Example ```go config := &typesense.ClientConfig{ ServerURL: "http://localhost:8108", APIKey: "xyz", NumRetries: 5, ConnectionTimeout: 10 * time.Second, CircuitBreakerMaxRequests: 100, } client := typesense.NewClient( typesense.WithClientConfig(config), ) ``` ``` -------------------------------- ### Index a Document in Typesense Source: https://github.com/typesense/typesense-go/blob/master/README.md Index a new document into a collection. The document structure must match the collection's schema. ```go 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) ``` -------------------------------- ### Configure API Key Authentication Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use `WithAPIKey` to set the API key for authenticating requests to the Typesense server. The key is sent in the `X-TYPESENSE-API-KEY` header. ```go client := typesense.NewClient( typesense.WithServer("http://localhost:8108"), typesense.WithAPIKey("your-api-key-here"), ) ``` -------------------------------- ### Get Specific Key Resource Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Obtain a Key resource interface to perform operations on a specific API key using its numeric ID. Supports retrieving and deleting a particular key. ```go key := client.Key(12345) ``` -------------------------------- ### Upsert Preset Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Creates or updates a preset for saved search configurations. Provide the preset name and its definition to upsert. ```go func (p *PresetsInterface) Upsert(ctx context.Context, presetName string, presetValue *api.PresetUpsertSchema) (*api.PresetSchema, error) ``` ```go preset := &api.PresetUpsertSchema{} preset.Value.FromSearchParameters(api.SearchParameters{ Q: "books", QueryBy: "title,author", Limit: 10, }) result, err := client.Presets().Upsert(context.Background(), "listing-view", preset) if err != nil { log.Fatal(err) } fmt.Printf("Created preset: %s\n", result.Name) ``` -------------------------------- ### Get Typed Collection Resource Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/client.md Retrieve a typed Collection resource for operations on a specific collection, supporting custom document types. Define your document structure using a Go struct. ```go type CompanyDoc struct { ID string `json:"id"` CompanyName string `json:"company_name"` NumEmployees int `json:"num_employees"` } typedCollection := typesense.GenericCollection[*CompanyDoc](client, "companies") doc, err := typedCollection.Document("123").Retrieve(ctx) ``` -------------------------------- ### Create an API Key Source: https://github.com/typesense/typesense-go/blob/master/README.md Creates a new API key with specified permissions, collections, and expiration. ```APIDOC ## Create an API Key ### Description Creates a new API key with specified permissions, collections, and expiration. ### Method POST ### Endpoint /keys ### Parameters #### Request Body - **keySchema** (object) - Required - Schema defining the API key properties. - **description** (string) - Optional - A description for the API key. - **actions** (array of strings) - Required - List of actions the key can perform (e.g., "documents:search"). - **collections** (array of strings) - Required - List of collections the key can access. - **expires_at** (integer) - Optional - Unix timestamp for key expiration. ### Response #### Success Response (200) - **api_key** (object) - The newly created API key details. #### Response Example ```json { "id": "key123", "description": "Search-only key.", "actions": ["documents:search"], "collections": ["companies"], "expires_at": 1678886400 } ``` ``` -------------------------------- ### Handle 422 Unprocessable Entity Error Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/errors.md Example for handling a 422 Unprocessable Entity error, returned when request data is valid but violates business logic or schema constraints. This can occur due to missing required fields or type mismatches. ```go doc := struct { ID string `json:"id"` Name int `json:"name"` // Schema expects string }{ ID: "123", Name: 456, } _, err := client.Collection("companies").Documents().Create(context.Background(), doc, params) if err != nil { if httpErr, ok := err.(*typesense.HTTPError); ok { if httpErr.Status == 422 { fmt.Printf("Validation error: %s\n", string(httpErr.Body)) } } } ``` -------------------------------- ### Retrieve Server Metrics Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Retrieves server performance metrics. Use this to monitor the health and performance of your Typesense instance. ```go type MetricsInterface interface { Retrieve(ctx context.Context) (map[string]interface{}, error) } ``` ```go metrics, err := client.Metrics().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for key, value := range metrics { fmt.Printf("%s: %v\n", key, value) } ``` -------------------------------- ### Handle 409 Conflict Error Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/errors.md Shows how to manage a 409 Conflict error, which arises when attempting to create a resource that already exists. This commonly happens when creating a document with an ID that is already in use; consider using Upsert in such cases. ```go // First creation succeeds client.Collection("companies").Documents().Create(context.Background(), doc, params) // Second creation with same ID fails with 409 doc2 := struct { ID string `json:"id"` }{ ID: "123", } _, err := client.Collection("companies").Documents().Create(context.Background(), doc2, params) if err != nil { if httpErr, ok := err.(*typesense.HTTPError); ok { if httpErr.Status == 409 { fmt.Println("Document already exists") // Use Upsert instead } } } ``` -------------------------------- ### List all keys Source: https://github.com/typesense/typesense-go/blob/master/README.md Retrieves a list of all API keys configured in the Typesense instance. ```APIDOC ## List all keys ### Description Retrieves a list of all API keys configured in the Typesense instance. ### Method GET ### Endpoint /keys ### Response #### Success Response (200) - **keys** (array) - An array of API key objects. #### Response Example ```json [ { "id": "1", "description": "Search-only key.", "actions": ["documents:search"], "collections": ["companies"], "expires_at": 1678886400 }, { "id": "2", "description": "Admin key.", "actions": ["*"], "collections": ["*"] } ] ``` ``` -------------------------------- ### ApiKeySchema Struct Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/types.md Defines the schema for creating a new API key. It allows specifying descriptions, allowed actions, restricted collections, and expiration times. ```go type ApiKeySchema struct { Description *string Actions []string Collections []string ExpiresAt *int64 } ``` -------------------------------- ### List All Collection Aliases Source: https://github.com/typesense/typesense-go/blob/master/README.md Retrieves a list of all collection aliases. ```go client.Aliases().Retrieve(context.Background()) ``` -------------------------------- ### Retrieve All Synonym Sets Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/synonyms-and-curation.md Retrieves all synonym sets configured in Typesense. Useful for auditing or displaying existing synonyms. ```go synonyms, err := client.SynonymSets().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, set := range synonyms { fmt.Printf("Synonym Set: %s (%v)\n", set.Id, set.Synonyms) } ``` -------------------------------- ### Handling Partial Document Imports Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/errors.md Process results from a bulk import operation, checking each document for success or failure. This allows for granular error reporting when some documents import correctly and others do not. ```go results, err := client.Collection("companies").Documents().Import(context.Background(), docs, params) if err != nil { // Import request itself failed log.Fatal(err) } // Check individual document results for i, result := range results { if result.Success { fmt.Printf("Document %d: imported with ID %s\n", i, result.Id) } else { fmt.Printf("Document %d: error - %s\n", i, result.Error) } } ``` -------------------------------- ### Create Analytics Rules Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/analytics.md Creates analytics rules for event tracking. Provide an array of rule definitions, each with a name, type, and optional parameters. ```go import ( "github.com/typesense/typesense-go/v4/typesense" "github.com/typesense/typesense-go/v4/typesense/api" "github.com/typesense/typesense-go/v4/typesense/api/pointer" ) rules := []*api.AnalyticsRuleCreate{ { Name: "popular_queries", Type: "popular_queries", Params: map[string]interface{}{ "limit": 10 }, }, { Name: "nohits_queries", Type: "nohits_queries", }, } result, err := client.Analytics().Rules().Create(context.Background(), rules) if err != nil { log.Fatal(err) } fmt.Printf("Created %d rules\n", len(result)) ``` -------------------------------- ### Define and Create Collection Schema Source: https://github.com/typesense/typesense-go/blob/master/README.md Define the schema for a new collection, including fields and default sorting. Use this to create a collection in Typesense. ```go schema := &api.CollectionSchema{ Name: "companies", Fields: []api.Field{ {Name: "company_name", Type: "string"}, {Name: "num_employees", Type: "int32"}, {Name: "country", Type: "string", Facet: true}, }, DefaultSortingField: pointer.String("num_employees"), } client.Collections().Create(context.Background(), schema) ``` -------------------------------- ### Batch Import Documents Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/README.md Imports multiple documents into a collection in a single batch operation. The documents are provided as a slice of maps. ```go docs := []interface{}{ map[string]interface{}{"id": "1", "name": "Product 1"}, map[string]interface{}{"id": "2", "name": "Product 2"}, } results, err := client.Collection("products").Documents().Import(ctx, docs, &api.ImportDocumentsParams{}) ``` -------------------------------- ### Retrieve All Curation Sets Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/synonyms-and-curation.md Retrieves all existing curation sets. This is useful for listing and reviewing all managed curation rules. ```go curations, err := client.CurationSets().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, curation := range curations { fmt.Printf("Curation: %s (Query: %s)\n", curation.Id, curation.Rule.Query) ``` -------------------------------- ### Create Collection Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/collections.md Creates a new collection in Typesense with the specified schema. Ensure the schema is valid and the collection name does not already exist to avoid errors. ```go response, err := client.Collections().Create(context.Background(), schema) if err != nil { log.Fatal(err) } fmt.Printf("Created collection: %s\n", response.Name) ``` -------------------------------- ### Preset Retrieve Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/additional-resources.md Retrieves all presets. This operation returns an array of preset configurations. ```APIDOC ## Preset Retrieve ### Description Retrieves all presets. ### Method GET ### Endpoint /presets ### Returns #### Success Response (200) - `[]*api.PresetSchema` - Array of presets ### Request Example ```go presets, err := client.Presets().Retrieve(context.Background()) if err != nil { log.Fatal(err) } for _, preset := range presets { fmt.Printf("Preset: %s\n", preset.Name) } ``` ``` -------------------------------- ### Create API Key Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/keys.md Creates a new API key with specified permissions and restrictions. The key can be configured with actions, collections it applies to, and an expiration time. ```APIDOC ## Create API Key ### Description Creates a new API key with specified permissions and restrictions. ### Method POST (Implied) ### Endpoint /keys ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (*api.ApiKeySchema) - Required - API key schema with permissions and restrictions. This includes: - **description** (string) - Optional - A description for the API key. - **actions** ([]string) - Optional - A list of actions the API key can perform. - **collections** ([]string) - Optional - A list of collections the API key can access. - **expires_at** (*int64) - Optional - Timestamp for when the API key should expire. ### Request Example ```go import ( "context" "fmt" "log" "time" "github.com/typesense/typesense-go/v4/typesense" "github.com/typesense/typesense-go/v4/typesense/api" "github.com/typesense/typesense-go/v4/typesense/api/pointer" ) // Assuming 'client' is an initialized Typesense client keySchema := &api.ApiKeySchema{ Description: "Search-only key for products collection", Actions: []string{"documents:search"}, Collections: []string{"products"}, ExpiresAt: pointer.Int64(time.Now().AddDate(0, 6, 0).Unix()), } apiKey, err := client.Keys().Create(context.Background(), keySchema) if err != nil { log.Fatal(err) } fmt.Printf("Created API key with ID: %d, Value: %s\n", apiKey.Id, apiKey.Value) ``` ### Response #### Success Response (200 OK) - **id** (int64) - The unique identifier of the created API key. - **value** (string) - The generated API key value. #### Response Example ```json { "id": 12345, "value": "some_api_key_value" } ``` ``` -------------------------------- ### Access Single Document Interface Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/api-reference/collection-operations.md Returns a Document interface for single document operations like retrieve, update, or delete. Supports both generic and typed documents. ```go doc, err := client.Collection("companies").Document("123").Retrieve(context.Background()) if err != nil { log.Fatal(err) } // For typed documents: type CompanyDoc struct { ID string `json:"id"` Name string `json:"company_name"` } typedDoc, err := typesense.GenericCollection[*CompanyDoc](client, "companies"). Document("123"). Retrieve(context.Background()) ``` -------------------------------- ### Configure Multiple Typesense Nodes Source: https://github.com/typesense/typesense-go/blob/master/_autodocs/configuration.md Use `WithNodes` to provide an array of node URLs for load-balanced reads and writes in a distributed cluster. This ensures high availability and distributes traffic across multiple servers. ```go client := typesense.NewClient( 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("xyz"), ) ```