meilisearch-go

repository·main·Indexed 20 days ago

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

The official Go API client for the Meilisearch search engine and Meilisearch Cloud. It provides developers with tools for document management (creation, addition, updating, retrieval, and deletion), index settings configuration, faceted search, multi-search operations, and asynchronous task monitoring. The client also supports chat features and streaming responses for users of Meilisearch Enterprise.

Tokens
48.4K
Snippets
146
Records
207
Agent score
71%

What's inside meilisearch-go

  1. Compatibility with Meilisearch

    main
    The meilisearch-go package guarantees compatibility with Meilisearch version v1.x. Note that while the client is compatible, certain specific Meilisearch features might not yet be implemented in this SDK. For the most up-to-date information on feature availability, check the project's GitHub issues.
  2. Best practices for Meilisearch task management

    main

    When implementing task management in your own application, follow these best practices:

    • Wait for critical tasks: Always ensure essential operations (like index creation) are complete before proceeding to dependent steps.
    • Use timeouts: When waiting for tasks to complete, implement appropriate timeouts to prevent infinite blocking.
    • Efficient filtering: Use filters when listing tasks to reduce payload size and improve monitoring efficiency.
    • Graceful error handling: Always check the task status and handle errors returned in the task details.
    • Monitor performance: Use task duration and statistics to monitor the health and performance of your Meilisearch instance.
  3. Configure environment variables for Meilisearch

    main

    Before running the facet search example or connecting the Go client, ensure the following environment variables are set in your shell:

    • MEILI_HOST: The base URL of your Meilisearch instance (e.g., http://localhost:7700).
    • MEILI_API_KEY: Your Meilisearch master key or tenant key.
    export MEILI_HOST="http://localhost:7700"
    export MEILI_API_KEY="your-api-key"
  4. Optimize SDK performance with custom JSON marshaling

    main

    By default, the SDK uses encoding/json. For higher performance, you can provide custom marshaling and unmarshaling functions using third-party libraries like sonic.

    package main
    
    import (
        "net/http"
        "github.com/meilisearch/meilisearch-go"
        "github.com/bytedance/sonic"
    )
    
    func main() {
    	client := meilisearch.New("http://localhost:7700",
            meilisearch.WithAPIKey("foobar"),
            meilisearch.WithCustomJsonMarshaler(sonic.Marshal),
            meilisearch.WithCustomJsonUnmarshaler(sonic.Unmarshal),
        )
    }
  5. Monitor and manage Meilisearch tasks

    main

    Meilisearch operations like creating an index, adding documents, or updating settings are asynchronous and generate tasks. You can monitor these tasks to ensure operations complete successfully.

    Key capabilities demonstrated in the task management workflow include:

    • Waiting for completion: Blocking until a specific task reaches a terminal state.
    • Retrieving details: Fetching specific information for a single task using its ID.
    • Listing tasks: Retrieving a collection of tasks.
    • Filtering: Narrowing down task lists by specific criteria, such as task type (e.g., filtering for only documentAdditionOrUpdate operations).

    Task metadata includes the Task ID, type, status (enqueued, processing, succeeded, failed), start/finish timestamps, duration, and error details in case of failure.

  6. Search with filters

    main

    To use filtering in searches, you must first register the attributes you want to filter by using UpdateFilterableAttributes. This is an asynchronous operation that triggers an index rebuild. Once the task is complete, you can use the Filter field in a SearchRequest to apply filters (e.g., id > 1 AND genres = Action).

    // 1. Enable filtering for specific attributes (run once)
    task, err := index.UpdateFilterableAttributes(&[]string{"id", "genres"})
    
    // 2. Perform the search with a filter
    searchRes, err := index.Search("wonder",
        &meilisearch.SearchRequest{
            Filter: "id > 1 AND genres = Action",
        })
  7. Set up environment variables for meilisearch-go

    main

    Before running examples or applications using the meilisearch-go client, ensure you have configured the connection details via environment variables:

    • MEILI_HOST: The URL of your Meilisearch instance (e.g., http://localhost:7700).
    • MEILI_API_KEY: Your Meilisearch API key.
    export MEILI_HOST="http://localhost:7700"
    export MEILI_API_KEY="your-api-key"
  8. Use mocks for testing Meilisearch interactions

    main

    The SDK provides generated mocks in the mocks package to facilitate unit testing. These mocks are built using mockery and testify/mock. To use them, add github.com/stretchr/testify to your project dependencies.

    Commonly available mocks include:

    • ServiceManager: mocks.NewMockmeilisearchServiceManager(t)
    • IndexManager: mocks.NewMockmeilisearchIndexManager(t)
    • DocumentManager: mocks.NewMockmeilisearchDocumentManager(t)
    package main
    
    import (
    	"testing"
    
    	"github.com/meilisearch/meilisearch-go"
    	"github.com/meilisearch/meilisearch-go/mocks"
    	"github.com/stretchr/testify/assert"
    )
    
    func TestCreateMyIndex(t *testing.T) {
    	// Create the mock object
    	mockClient := mocks.NewMockmeilisearchServiceManager(t)
    
    	// Set up expectations
    	expectedConfig := &meilisearch.IndexConfig{Uid: "movies", PrimaryKey: "id"}
    	mockClient.On("CreateIndex", expectedConfig).
    		Return(&meilisearch.TaskInfo{TaskUID: 1}, nil)
    
    	// Call the code under test
    	err := CreateMyIndex(mockClient, "movies")
    
    	// Assertions
    	assert.NoError(t, err)
    
    	// Verify that the expectations were met
    	mockClient.AssertExpectations(t)
    }
  9. Production-ready patterns for Meilisearch indexing

    main

    When building search implementations with meilisearch-go, follow these best practices demonstrated in the search example:

    • Settings Configuration: Always configure filterableAttributes and sortableAttributes before indexing documents to ensure search capabilities are available immediately.
    • Task Completion: Meilisearch operations (like indexing or updating settings) are asynchronous. You must wait for the task to complete before proceeding to dependent steps (e.g., waiting for settings to apply before searching with filters).
    • Resource Management: Use defer client.Close() to ensure the client is properly cleaned up.
    • Timeout Management: Implement timeouts (e.g., 10 seconds) for indexing operations to prevent hanging processes.
    • Batch Operations: Use bulk document indexing for efficiency rather than indexing documents one by one.
    • Error Handling: Implement comprehensive error handling for network calls, task failures, and JSON unmarshalling (especially when processing facets).
  10. Configure Meilisearch client environment variables

    main

    Before running the document management example, configure the connection to your Meilisearch instance using environment variables. By default, the client expects the server at http://localhost:7700.

    # Set Meilisearch server URL (defaults to http://localhost:7700)
    export MEILI_HOST="http://localhost:7700"
    
    # Set API key (recommended for production)
    export MEILI_API_KEY="your-api-key"
  11. Best practices for Multi-Search operations

    main

    When implementing multi-search patterns with meilisearch-go, follow these best practices demonstrated in the example:

    • Settings Configuration: Always configure filterableAttributes and sortableAttributes on your index before attempting to use them in search queries.
    • Task Completion: Meilisearch operations (like updating settings or adding documents) are asynchronous. You must wait for the task to complete before executing searches that rely on those changes.
    • Resource Management: Always use defer client.Close() to ensure the client is properly cleaned up.
    • Performance Optimization: Use the multi-search capability to batch multiple queries into a single API call to reduce network overhead and improve efficiency.
    • Error Handling: Implement comprehensive error handling for each individual search within the multi-search batch to handle partial failures gracefully.