Typesense Go Client (v4)

repository·master·Indexed 43 days ago

https://github.com/typesense/typesense-go

The 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.

Tokens
3K
Snippets
11
Records
13
Agent score
53%

What's inside Typesense

  1. Untitled record

    master

    Import the package and use typesense.NewClient to create a client. You can provide various configuration options using functional options.

    Basic Client

    import "github.com/typesense/typesense-go/v4/typesense"
    
    client := typesense.NewClient(
        typesense.WithServer("http://localhost:8108"),
        typesense.WithAPIKey("<API_KEY>"),
    )

    Advanced Configuration

    Use options like WithConnectionTimeout, WithCircuitBreakerMaxRequests, WithCircuitBreakerInterval, and WithCircuitBreakerTimeout for fine-grained control.

    Multi-node Configuration

    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>"),
    )
  2. Initialize a Typesense Client

    master

    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),
    )
  3. Untitled record

    master

    Efficiently move data in and out of collections.

    Import an array of documents

    params := &api.ImportDocumentsParams{
        Action:    pointer.String("create"),
        BatchSize: pointer.Int(40),
    }
    
    client.Collection("companies").Documents().Import(context.Background(), documents, params)

    Import a JSONL file

        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)

    Export documents

    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())
  4. Untitled record

    master

    Perform standard CRUD operations on documents within a collection.

    Index a document (Create)

    		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)

    Upsert a 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)

    Update a document

    		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)
  5. Untitled record

    master

    Configure how search terms relate to each other using multi-way or one-way synonyms.

    Multi-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)

    One-way Synonyms

    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, List, and Delete

    // 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)
  6. Configure Circuit Breaker settings

    master

    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.
  7. Configure the API Key using WithAPIKey

    master

    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"),
    )
  8. Access other Typesense resources via Client

    master

    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.
  9. Access Collections and Typed Documents

    master

    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")