### Run Task Management Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/manage_tasks/README.md Execute the Go example to demonstrate task management functionalities. ```bash go run ./examples/manage_tasks ``` -------------------------------- ### Run the Meilisearch Go Search Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/search/README.md Executes the Go example program. Ensure you have Go installed and the Meilisearch server is running. ```bash go run ./examples/search ``` -------------------------------- ### Run Meilisearch Document Management Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/add_documents/README.md Executes the Meilisearch document management example using Go. Ensure you have the Go toolchain installed and the example code is in the specified path. ```bash go run ./examples/add_documents ``` -------------------------------- ### Run Chat Streaming Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/chat_stream/README.md Execute the Go example to start an interactive chat session with streaming responses. Type 'quit' or 'exit' to end. ```bash go run ./examples/chat_stream ``` -------------------------------- ### Run Multi-Search Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/multi_search/README.md Execute the Go example to perform multiple searches concurrently. Ensure you have the Go environment set up. ```bash go run ./examples/multi_search ``` -------------------------------- ### Run Meilisearch Go Index Creation Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/create_index_settings/README.md Execute the Go example to create an index, configure its settings, add documents, and test search functionality. ```bash go run ./examples/create_index_settings ``` -------------------------------- ### Install Meilisearch Go Client Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Use `go get` to install the Meilisearch Go client library. Ensure you are using version 1.21 or later. ```bash go get github.com/meilisearch/meilisearch-go ``` -------------------------------- ### Run Facet Search Example Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/facet_search/README.md Execute the Go example to demonstrate facet search functionality. This command assumes you are in the root directory of the meilisearch-go project. ```bash go run ./examples/facet_search ``` -------------------------------- ### Install Project Requirements Source: https://github.com/meilisearch/meilisearch-go/blob/main/CONTRIBUTING.md Run this command to install all necessary tools and dependencies for development, including Docker, easyjson, and SDK dependencies. ```shell make requirements ``` -------------------------------- ### Set Meilisearch Environment Variables Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/create_index_settings/README.md Before running the example, set the MEILI_HOST and MEILI_API_KEY environment variables to connect to your Meilisearch instance. ```bash export MEILI_HOST="http://localhost:7700" export MEILI_API_KEY="your-api-key" ``` -------------------------------- ### Set Meilisearch Environment Variables Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/chat_stream/README.md Configure the Meilisearch host and API key using environment variables before running the example. ```bash export MEILI_HOST="http://localhost:7700" export MEILI_API_KEY="your-enterprise-api-key" ``` -------------------------------- ### Update, Get, and Reset Settings Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates how to update all index settings at once, retrieve the current settings, and reset all settings to their default values. ```APIDOC ## UpdateSettings / GetSettings / ResetSettings — Configure index behavior Settings control ranking, searchable/filterable/sortable attributes, typo tolerance, synonyms, stop words, faceting, pagination, embedders, and more. Individual setting groups can be updated independently. ### UpdateSettings Updates all settings for an index at once. ```go // Example of updating all settings task, err := index.UpdateSettings(&meilisearch.Settings{ ... }) ``` ### GetSettings Retrieves the current settings for an index. ```go // Example of getting settings settings, err := index.GetSettings() ``` ### ResetSettings Resets all settings for an index to their default values. ```go // Example of resetting settings resetTask, _ := index.ResetSettings() ``` ``` -------------------------------- ### Manage Meilisearch Indexes with Go SDK Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Use this snippet to create, list, get, rename (swap), and delete Meilisearch indexes. Ensure the Meilisearch instance is running and accessible. The `WaitForTask` function is crucial for ensuring operations complete before proceeding. ```go package main import ( "context" "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Create an index with a primary key task, err := client.CreateIndex(&meilisearch.IndexConfig{ Uid: "movies", PrimaryKey: "id", }) if err != nil { log.Fatalf("create index: %v", err) } completedTask, _ := client.WaitForTask(task.TaskUID, 100*time.Millisecond) fmt.Printf("CreateIndex task %d: %s\n", task.TaskUID, completedTask.Status) // List all indexes (paginated) indexes, err := client.ListIndexes(&meilisearch.IndexesQuery{Limit: 20, Offset: 0}) if err != nil { log.Fatalf("list indexes: %v", err) } fmt.Printf("Total indexes: %d\n", indexes.Total) for _, idx := range indexes.Results { fmt.Printf(" %s pk=%s\n", idx.UID, idx.PrimaryKey) } // Get a single index info, err := client.GetIndex("movies") if err != nil { log.Fatalf("get index: %v", err) } fmt.Printf("movies created: %s\n", info.CreatedAt) // Rename index by swapping // First create "movies_v2", then swap movies <-> movies_v2 client.CreateIndex(&meilisearch.IndexConfig{Uid: "movies_v2", PrimaryKey: "id"}) swapTask, _ := client.SwapIndexes([]*meilisearch.SwapIndexesParams{ {Indexes: []string{"movies", "movies_v2"}}, }) client.WaitForTask(swapTask.TaskUID, 100*time.Millisecond) // Delete index ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() delTask, _ := client.DeleteIndexWithContext(ctx, "movies_v2") client.WaitForTask(delTask.TaskUID, 100*time.Millisecond) fmt.Println("movies_v2 deleted") } ``` -------------------------------- ### Update, Get, and Reset Meilisearch Index Settings in Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates how to update all index settings, retrieve current settings, and reset settings to their default values using the Meilisearch Go SDK. Ensure the Meilisearch instance is running and accessible. ```go package main import ( "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() index := client.Index("movies") // Update all settings at once task, err := index.UpdateSettings(&meilisearch.Settings{ RankingRules: []string{"words", "typo", "proximity", "attribute", "sort", "exactness"}, SearchableAttributes: []string{"title", "overview", "genres"}, FilterableAttributes: []interface{}{"genres", "year", "rating"}, SortableAttributes: []string{"year", "rating"}, DisplayedAttributes: []string{"id", "title", "year", "genres", "overview"}, StopWords: []string{"the", "a", "an"}, Synonyms: map[string][]string{"wolverine": {"Logan", "James Howlett"}}, TypoTolerance: &meilisearch.TypoTolerance{ Enabled: meilisearch.BoolPtr(true), MinWordSizeForTypos: meilisearch.MinWordSizeForTypos{ OneTypo: meilisearch.Int64(5), TwoTypos: meilisearch.Int64(9), }, }, Pagination: &meilisearch.Pagination{MaxTotalHits: 1000}, Faceting: &meilisearch.Faceting{MaxValuesPerFacet: 100}, }) if err != nil { log.Fatalf("update settings: %v", err) } done, _ := client.WaitForTask(task.TaskUID, 100*time.Millisecond) fmt.Printf("Settings update: %s\n", done.Status) // Read settings back settings, err := index.GetSettings() if err != nil { log.Fatalf("get settings: %v", err) } fmt.Printf("Searchable: %v\n", *settings.SearchableAttributes) // Update only ranking rules rrTask, _ := index.UpdateRankingRules(&[]string{"words", "typo", "exactness"}) client.WaitForTask(rrTask.TaskUID, 100*time.Millisecond) // Update only filterable attributes faTask, _ := index.UpdateFilterableAttributes(&[]interface{}{"genres", "year"}) client.WaitForTask(faTask.TaskUID, 100*time.Millisecond) // Configure embedder for AI search embedderTask, _ := index.UpdateEmbedders(map[string]meilisearch.Embedder{ "default": { Source: meilisearch.OpenaiEmbedderSource, Model: meilisearch.StringPtr("text-embedding-3-small"), APIKey: meilisearch.StringPtr("sk-..."), }, }) client.WaitForTask(embedderTask.TaskUID, 500*time.Millisecond) // Reset all settings to defaults resetTask, _ := index.ResetSettings() client.WaitForTask(resetTask.TaskUID, 100*time.Millisecond) } ``` -------------------------------- ### Perform a Basic Search with Typo Tolerance Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Executes a search query against a Meilisearch index. Meilisearch is typo-tolerant by default. This example demonstrates a search for 'philoudelphia' which will match 'Philadelphia'. ```go package main import ( "fmt" "os" "github.com/meilisearch/meilisearch-go" ) func main() { // Meilisearch is typo-tolerant: searchRes, err := client.Index("movies").Search("philoudelphia", &meilisearch.SearchRequest{ Limit: 10, }) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println(searchRes.Hits) } ``` -------------------------------- ### Similar Document Search in Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Finds documents similar to a given document ID using a configured embedder. Requires the AI-powered search experimental feature and a configured embedder. This example shows how to retrieve similar movies based on a reference document. ```go package main import ( "fmt" "log" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() index := client.Index("movies") var result meilisearch.SimilarDocumentResult err := index.SearchSimilarDocuments(&meilisearch.SimilarDocumentQuery{ Id: "3", // reference document Embedder: "default", // embedder name configured in index settings Limit: 5, Offset: 0, Filter: "year > 2000", Fields: []string{"id", "title", "year"}, }, &result) if err != nil { log.Fatalf("similar docs: %v", err) } type Movie struct { ID int `json:"id"` Title string `json:"title"` } var movies []Movie result.Hits.DecodeInto(&movies) for _, m := range movies { fmt.Printf("Similar: %s (id=%d)\n", m.Title, m.ID) } } ``` -------------------------------- ### Experimental Features Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Manage experimental features in Meilisearch using the Go client. This includes getting the current state and updating feature flags. ```APIDOC ## ExperimentalFeatures().Get() / .Update() ### Description Allows users to retrieve the current status of experimental features and to enable or disable them using a fluent setter chain before updating. ### Method GET (for Get) POST (for Update) ### Endpoint /experimental-features (for Get) /experimental-features (for Update) ### Parameters #### Request Body (for Update) - **chatCompletions** (bool) - Optional - Whether to enable AI chat completions. - **containsFilter** (bool) - Optional - Whether to enable the contains filter. - **metrics** (bool) - Optional - Whether to enable metrics. ### Request Example (Update) ```go client.ExperimentalFeatures().SetChatCompletions(true).SetContainsFilter(true).SetMetrics(true).Update() ``` ### Response #### Success Response (200) - **chatCompletions** (bool) - Status of the chat completions feature. - **containsFilter** (bool) - Status of the contains filter feature. - **metrics** (bool) - Status of the metrics feature. - **logsRoute** (bool) - Status of the logs route feature. ``` -------------------------------- ### Test Meilisearch ServiceManager with Mocks in Go Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Example of unit testing a function that depends on `meilisearch.ServiceManager` using generated mocks. This requires setting up expectations on the mock object before calling the function under test. ```go func CreateMyIndex(client meilisearch.ServiceManager, uid string) error { _, err := client.CreateIndex(&meilisearch.IndexConfig{Uid: uid, PrimaryKey: "id"}) return err } ``` ```go 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 // The naming convention is Mock + PackageName + InterfaceName mockClient := mocks.NewMockmeilisearchServiceManager(t) // Set up expectations // Expect CreateIndex to be called with a specific config, and return a successful TaskInfo and nil error 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) } ``` -------------------------------- ### Create Database Dump and Snapshot with Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Asynchronously create a full database dump as a `.dump` file or a binary snapshot. Use `WaitForTask` to monitor the completion status of these operations. ```go package main import ( "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Create a dump dumpTask, err := client.CreateDump() if err != nil { log.Fatalf("create dump: %v", err) } done, err := client.WaitForTask(dumpTask.TaskUID, 500*time.Millisecond) if err != nil { log.Fatalf("wait for dump: %v", err) } fmt.Printf("Dump task %d: %s\n", done.UID, done.Status) // Create a snapshot snapshotTask, err := client.CreateSnapshot() if err != nil { log.Fatalf("create snapshot: %v", err) } snapDone, _ := client.WaitForTask(snapshotTask.TaskUID, 500*time.Millisecond) fmt.Printf("Snapshot task %d: %s\n", snapDone.UID, snapDone.Status) } ``` -------------------------------- ### Initialize Meilisearch Go Client Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Create a Meilisearch client using `meilisearch.New` with basic or advanced options. Use `meilisearch.Connect` to verify server health upon initialization. Remember to close the client when done. ```go package main import ( "fmt" "log" "net/http" "time" "github.com/meilisearch/meilisearch-go" "github.com/bytedance/sonic" ) func main() { // Minimal client client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Client with all options customHTTP := &http.Client{Timeout: 30 * time.Second} richClient := meilisearch.New( "http://localhost:7700", meilisearch.WithAPIKey("masterKey"), meilisearch.WithCustomClient(customHTTP), meilisearch.WithContentEncoding(meilisearch.GzipEncoding, meilisearch.BestCompression), meilisearch.WithCustomRetries([]int{502, 503}, 5), meilisearch.WithCustomJsonMarshaler(sonic.Marshal), meilisearch.WithCustomJsonUnmarshaler(sonic.Unmarshal), ) defer richClient.Close() // Connect variant — verifies health before returning verified, err := meilisearch.Connect("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) if err != nil { log.Fatalf("cannot connect: %v", err) } defer verified.Close() v, _ := verified.Version() fmt.Printf("Meilisearch %s (pkg: %s)\n", v.PkgVersion, v.CommitSha) } ``` -------------------------------- ### Client Initialization Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates how to initialize the Meilisearch Go client using `meilisearch.New` and `meilisearch.Connect`. It shows minimal and rich client configurations, including options for API keys, custom HTTP clients, content encoding, retries, and custom JSON marshaling/unmarshaling. ```APIDOC ## Client Initialization ### `meilisearch.New` — Create a service manager `New(host string, options ...Option) ServiceManager` creates a client without verifying connectivity. `Connect` does the same but also calls `/health` and returns an error if Meilisearch is unavailable. Options include `WithAPIKey`, `WithCustomClient`, `WithCustomClientWithTLS`, `WithContentEncoding`, `WithCustomRetries`, `DisableRetries`, `WithCustomJsonMarshaler`, and `WithCustomJsonUnmarshaler`. ```go package main import ( "fmt" "log" "net/http" "time" "github.com/meilisearch/meilisearch-go" "github.com/bytedance/sonic" ) func main() { // Minimal client client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Client with all options customHTTP := &http.Client{Timeout: 30 * time.Second} richClient := meilisearch.New( "http://localhost:7700", meilisearch.WithAPIKey("masterKey"), meilisearch.WithCustomClient(customHTTP), meilisearch.WithContentEncoding(meilisearch.GzipEncoding, meilisearch.BestCompression), meilisearch.WithCustomRetries([]int{502, 503}, 5), meilisearch.WithCustomJsonMarshaler(sonic.Marshal), meilisearch.WithCustomJsonUnmarshaler(sonic.Unmarshal), ) defer richClient.Close() // Connect variant — verifies health before returning verified, err := meilisearch.Connect("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) if err != nil { log.Fatalf("cannot connect: %v", err) } defer verified.Close() v, _ := verified.Version() fmt.Printf("Meilisearch %s (pkg: %s)\n", v.PkgVersion, v.CommitSha) } ``` ``` -------------------------------- ### Facet Search in Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Searches for values within a specific facet attribute. The index must have the attribute listed in `filterableAttributes`. This example demonstrates autocompleting facet values with a filter. ```go package main import ( "encoding/json" "fmt" "log" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() index := client.Index("movies") raw, err := index.FacetSearch(&meilisearch.FacetSearchRequest{ FacetName: "genres", FacetQuery: "Dra", // autocomplete on facet values Filter: "year > 2000", }) if err != nil { log.Fatalf("facet search: %v", err) } var result struct { FacetHits []struct { Value string `json:"value"` Count int `json:"count"` } `json:"facetHits"` } json.Unmarshal(*raw, &result) for _, hit := range result.FacetHits { fmt.Printf(" %s: %d\n", hit.Value, hit.Count) } // Output: // Drama: 42 } ``` -------------------------------- ### Dumps and Snapshots Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Create full database dumps or binary snapshots for backup and restore purposes using the Meilisearch Go client. ```APIDOC ## CreateDump / CreateSnapshot ### Description Asynchronously creates a full database dump as a `.dump` file or a binary snapshot. These operations are used for backup and can be monitored via tasks. ### Method POST ### Endpoint /dumps /snapshots ### Parameters None ### Request Example ```go // Create a dump client.CreateDump() // Create a snapshot client.CreateSnapshot() ``` ### Response #### Success Response (200) - **taskUid** (int) - The unique identifier of the task created for the dump or snapshot operation. - **status** (string) - The status of the task (e.g., "enqueued", "processing", "succeeded"). ``` -------------------------------- ### Perform Full-Text Search with Meilisearch Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates basic and advanced search queries, including filtering, sorting, highlighting, and faceting. Handles decoding search results into a Go struct and shows how to perform raw searches for custom unmarshaling. ```go package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) type Movie struct { ID int `json:"id"` Title string `json:"title"` Year int `json:"year"` Genres []string `json:"genres"` } func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() index := client.Index("movies") // Basic search res, err := index.Search("wonder", &meilisearch.SearchRequest{Limit: 5}) if err != nil { log.Fatalf("search: %v", err) } var movies []Movie if err := res.Hits.DecodeInto(&movies); err != nil { log.Fatalf("decode: %v", err) } for _, m := range movies { fmt.Printf("%s (%d)\n", m.Title, m.Year) } // Advanced search: filter, sort, highlight, facets, pagination ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() advanced, err := index.SearchWithContext(ctx, "drama", &meilisearch.SearchRequest{ Filter: "year > 2000 AND genres = Drama", Sort: []string{"year:desc"}, Facets: []string{"genres"}, AttributesToHighlight: []string{"title"}, AttributesToRetrieve: []string{"id", "title", "year", "genres"}, MatchingStrategy: meilisearch.Last, HitsPerPage: meilisearch.Int64(10), Page: meilisearch.Int64(1), }) if err != nil { log.Fatalf("advanced search: %v", err) } fmt.Printf("EstimatedTotalHits: %d ProcessingTime: %dms\n", advanced.EstimatedTotalHits, advanced.ProcessingTimeMs) // Facet distribution var facets map[string]map[string]float64 if err := json.Unmarshal(advanced.FacetDistribution, &facets); err == nil { for facet, counts := range facets { fmt.Printf("Facet %q: %v\n", facet, counts) } } // Raw search (custom struct / avoid double decode) raw, err := index.SearchRaw("action", &meilisearch.SearchRequest{Limit: 3}) if err != nil { log.Fatalf("raw search: %v", err) } var custom struct { Hits []Movie `json:"hits"` } json.Unmarshal(*raw, &custom) fmt.Printf("Raw hits: %d\n", len(custom.Hits)) } ``` -------------------------------- ### Configure Meilisearch Connection Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/manage_tasks/README.md Set environment variables for Meilisearch host and API key. An admin API key is required for task management. ```bash export MEILI_HOST="http://localhost:7700" export MEILI_API_KEY="your-admin-api-key" ``` -------------------------------- ### Using Opt Helpers for Optional Search Parameters in Meilisearch Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates the use of `Opt[T]` generics and helper functions like `Int64`, `Bool`, and `StringPtr` for setting optional and nullable fields in `SearchRequest` and other configurations. This ensures correct distinction between unset, null, and zero-value fields. ```go package main import ( "fmt" "github.com/meilisearch/meilisearch-go" ) func main() { index := meilisearch.New("http://localhost:7700").Index("movies") // Use Opt helpers for optional search parameters res, err := index.Search("action", &meilisearch.SearchRequest{ Limit: meilisearch.Int64(20), Offset: meilisearch.Int64(0), ShowRankingScore: meilisearch.Bool(true), ShowMatchesPosition: meilisearch.Bool(true), HitsPerPage: meilisearch.Int64(10), Page: meilisearch.Int64(1), }) if err != nil { fmt.Printf("search error: %v\n", err) return } fmt.Printf("Hits: %d\n", len(res.Hits)) // Null[T]() explicitly sends null (resets a nullable field on the server) nullField := meilisearch.Null[int64]() fmt.Printf("Null valid: %v IsNull: %v\n", nullField.Valid(), nullField.Null()) // Pointer helpers (used in Settings, Key, etc.) pk := meilisearch.StringPtr("id") fmt.Printf("PK pointer: %s\n", *pk) flag := meilisearch.BoolPtr(true) fmt.Printf("Flag pointer: %v\n", *flag) } ``` -------------------------------- ### Toggle Experimental Features with Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Configure and update experimental features using a fluent setter chain. Ensure the experimental feature is enabled before use. ```go package main import ( "fmt" "log" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Read current experimental feature state current, err := client.ExperimentalFeatures().Get() if err != nil { log.Fatalf("get features: %v", err) } fmt.Printf("Metrics: %v LogsRoute: %v\n", current.Metrics, current.LogsRoute) // Enable AI chat completions and vector search updated, err := client.ExperimentalFeatures(). SetChatCompletions(true). SetContainsFilter(true). SetMetrics(true). Update() if err != nil { log.Fatalf("update features: %v", err) } fmt.Printf("ChatCompletions: %v ContainsFilter: %v Metrics: %v\n", updated.ChatCompletions, updated.ContainsFilter, updated.Metrics) } ``` -------------------------------- ### Unit Test with Testify Mocks for Meilisearch Go SDK Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Demonstrates how to use generated testify mocks from the `mocks` package for unit testing Meilisearch SDK interactions without a running Meilisearch instance. This is useful for isolating logic and ensuring correct API calls. ```go package myapp_test import ( "testing" "github.com/meilisearch/meilisearch-go" "github.com/meilisearch/meilisearch-go/mocks" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) // CreateMyIndex wraps client.CreateIndex func CreateMyIndex(client meilisearch.ServiceManager, uid string) error { _, err := client.CreateIndex(&meilisearch.IndexConfig{Uid: uid, PrimaryKey: "id"}) return err } func TestCreateMyIndex(t *testing.T) { mockClient := mocks.NewMockmeilisearchServiceManager(t) expectedConfig := &meilisearch.IndexConfig{Uid: "movies", PrimaryKey: "id"} mockClient.On("CreateIndex", expectedConfig). Return(&meilisearch.TaskInfo{TaskUID: 42}, nil) err := CreateMyIndex(mockClient, "movies") assert.NoError(t, err) mockClient.AssertExpectations(t) } func TestSearchWithMock(t *testing.T) { mockIndex := mocks.NewMockmeilisearchIndexManager(t) expectedResp := &meilisearch.SearchResponse{EstimatedTotalHits: 1} mockIndex.On("Search", "wonder", mock.AnythingOfType("*meilisearch.SearchRequest")). Return(expectedResp, nil) res, err := mockIndex.Search("wonder", &meilisearch.SearchRequest{Limit: 5}) assert.NoError(t, err) assert.Equal(t, int64(1), res.EstimatedTotalHits) mockIndex.AssertExpectations(t) } ``` -------------------------------- ### Manage API Keys with Meilisearch Go SDK Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Create, retrieve, update, and delete API keys to manage access control. `CreateKey` allows defining key permissions, indexes, and expiration. `GenerateTenantToken` creates short-lived JWT tokens for multi-tenant applications. ```go package main import ( "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() expiresAt := time.Now().Add(30 * 24 * time.Hour) // 30 days // Create a scoped API key key, err := client.CreateKey(&meilisearch.Key{ Name: "Search-Only Key", Description: "Read-only key for the frontend", Actions: []string{"search"}, Indexes: []string{"movies", "products"}, ExpiresAt: &expiresAt, }) if err != nil { log.Fatalf("create key: %v", err) } fmt.Printf("Key UID: %s\nKey value: %s\n", key.UID, key.Key) // List all keys keys, err := client.GetKeys(&meilisearch.KeysQuery{Limit: 20}) if err != nil { log.Fatalf("get keys: %v", err) } for _, k := range keys.Results { fmt.Printf(" [%s] %s actions=%v\n", k.UID, k.Name, k.Actions) } // Update key metadata updated, err := client.UpdateKey(key.UID, &meilisearch.Key{ Name: "Frontend Search Key", Description: "Updated description", }) if err != nil { log.Fatalf("update key: %v", err) } fmt.Printf("Updated name: %s\n", updated.Name) // Generate a tenant token (multi-tenancy) // The apiKeyUID must be a valid UUID v4 of an existing key token, err := client.GenerateTenantToken( key.UID, map[string]interface{}{ "movies": map[string]interface{}{ "filter": "user_id = 42", }, }, &meilisearch.TenantTokenOptions{ APIKey: key.Key, ExpiresAt: time.Now().Add(1 * time.Hour), }, ) if err != nil { log.Fatalf("tenant token: %v", err) } fmt.Printf("Tenant JWT: %s\n", token[:20]+"...") // Delete the key ok, err := client.DeleteKey(key.UID) if err != nil { log.Fatalf("delete key: %v", err) } fmt.Printf("Deleted: %v\n", ok) } ``` -------------------------------- ### Customize Meilisearch Client Configuration Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Initializes the Meilisearch client with various customization options, including API key, custom HTTP client, content encoding, and retry behavior. ```go package main import ( "net/http" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("foobar"), meilisearch.WithCustomClient(http.DefaultClient), meilisearch.WithContentEncoding(meilisearch.GzipEncoding, meilisearch.BestCompression), meilisearch.WithCustomRetries([]int{502}, 20), ) } ``` -------------------------------- ### Run Integration Tests and Linter Source: https://github.com/meilisearch/meilisearch-go/blob/main/CONTRIBUTING.md Execute this command to run all integration tests and perform linter checks on the codebase. ```shell make test ``` -------------------------------- ### Configure Meilisearch Connection Environment Variables Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/add_documents/README.md Sets environment variables for Meilisearch server URL and API key. The MEILI_HOST defaults to http://localhost:7700 if not specified. An API key is recommended for production environments. ```bash # 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" ``` -------------------------------- ### Execute Multiple Search Queries with Meilisearch Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Shows how to send multiple search queries, potentially across different indexes, in a single HTTP request using `MultiSearch`. Results are returned in the order the queries were sent. ```go package main import ( "fmt" "log" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() req := &meilisearch.MultiSearchRequest{ Queries: []*meilisearch.SearchRequest{ {IndexUID: "movies", Query: "action", Limit: 3}, {IndexUID: "movies", Query: "drama", Filter: "year > 2000", Limit: 3}, {IndexUID: "movies", Query: "", Sort: []string{"year:desc"}, Limit: 5}, }, } resp, err := client.MultiSearch(req) if err != nil { log.Fatalf("multi-search: %v", err) } for i, result := range resp.Results { fmt.Printf("Query %d → %d estimated hits\n", i+1, result.EstimatedTotalHits) type Movie struct { Title string `json:"title"` Year int `json:"year"` } var movies []Movie result.Hits.DecodeInto(&movies) for _, m := range movies { fmt.Printf(" %s (%d)\n", m.Title, m.Year) } } } ``` -------------------------------- ### Product Data Structure Source: https://github.com/meilisearch/meilisearch-go/blob/main/examples/multi_search/README.md Defines the structure for product data that will be indexed and searched. Ensure this matches your actual data schema. ```go type Product struct { ID int `json:"id"` Name string `json:"name"` Description string `json:"description"` Category string `json:"category"` Price float64 `json:"price"` Brand string `json:"brand"` Tags []string `json:"tags"` InStock bool `json:"in_stock"` } ``` -------------------------------- ### Perform a Custom Search with Highlighting Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Conducts a search query and requests that matching attributes be highlighted in the results. This is useful for visually indicating search terms within the returned documents. ```go func main() { searchRes, err := client.Index("movies").Search("wonder", &meilisearch.SearchRequest{ AttributesToHighlight: []string{"*"}, }) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println(searchRes.Hits) } ``` -------------------------------- ### Generate Mocks for New Features Source: https://github.com/meilisearch/meilisearch-go/blob/main/CONTRIBUTING.md If you modify or create new interfaces, use this command to regenerate the necessary mock files. ```shell make mock ``` -------------------------------- ### Check Meilisearch Health and Version Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Use `IsHealthy` for a quick boolean check, or `HealthWithContext` for detailed status with context support. Retrieve server version information using `Version` and `GetStats`. ```go package main import ( "context" "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Simple boolean check if !client.IsHealthy() { log.Fatal("Meilisearch is not available") } // Detailed health with context ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() health, err := client.HealthWithContext(ctx) if err != nil { log.Fatalf("health check failed: %v", err) } fmt.Printf("Status: %s\n", health.Status) // "available" version, err := client.Version() if err != nil { log.Fatalf("version check failed: %v", err) } fmt.Printf("Version: %s Commit: %s\n", version.PkgVersion, version.CommitSha) stats, err := client.GetStats() if err != nil { log.Fatalf("stats failed: %v", err) } fmt.Printf("Total DB size: %d bytes, indexes: %d\n", stats.DatabaseSize, len(stats.Indexes)) } ``` -------------------------------- ### Track Async Operations with Meilisearch Go SDK Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Use `WaitForTaskWithContext` to block until an asynchronous operation completes, with support for context-based timeouts. `GetTasks` allows filtering tasks by status, type, index, and time ranges. Tasks can be cancelled if they are still enqueued, and old finished tasks can be deleted. ```go package main import ( "context" "fmt" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() index := client.Index("movies") // Start a long-running operation docs := []map[string]interface{}{{"id": 1, "title": "Test"}} taskInfo, err := index.AddDocuments(docs, nil) if err != nil { log.Fatalf("add documents: %v", err) } // Wait with context (timeout) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() task, err := client.WaitForTaskWithContext(ctx, taskInfo.TaskUID, 100*time.Millisecond) if err != nil { log.Fatalf("wait: %v", err) } fmt.Printf("Task %d status: %s\n", task.UID, task.Status) // "succeeded" // Query multiple tasks tasks, err := client.GetTasks(&meilisearch.TasksQuery{ Statuses: []string{string(meilisearch.TaskStatusSucceeded)}, Types: []string{string(meilisearch.TaskTypeDocumentAdditionOrUpdate)}, IndexUIDS: []string{"movies"}, Limit: 20, }) if err != nil { log.Fatalf("get tasks: %v", err) } fmt.Printf("Succeeded document tasks: %d\n", len(tasks.Results)) // Cancel tasks that are still enqueued cancelResult, err := client.CancelTasks(&meilisearch.CancelTasksQuery{ Statuses: []string{string(meilisearch.TaskStatusEnqueued)}, }) if err != nil { log.Fatalf("cancel tasks: %v", err) } fmt.Printf("CancelTasks uid: %d\n", cancelResult.TaskUID) // Delete old finished tasks deleteResult, _ := client.DeleteTasks(&meilisearch.DeleteTasksQuery{ Statuses: []string{ string(meilisearch.TaskStatusSucceeded), string(meilisearch.TaskStatusFailed), }, }) fmt.Printf("DeleteTasks uid: %d\n", deleteResult.TaskUID) } ``` -------------------------------- ### AI Chat Completions with Meilisearch Go Source: https://context7.com/meilisearch/meilisearch-go/llms.txt Interact with AI chat completions, requiring the `chatCompletions` experimental feature and an LLM provider. Streams SSE responses. Configure chat workspaces before use. ```go package main import ( "context" "errors" "fmt" "io" "log" "time" "github.com/meilisearch/meilisearch-go" ) func main() { client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey")) defer client.Close() // Configure chat workspace with an LLM provider _, err := client.UpdateChatWorkspace("default", &meilisearch.ChatWorkspaceSettings{ Source: meilisearch.OpenaiChatSource, APIKey: meilisearch.StringPtr("sk-வுகளை"), }) if err != nil { log.Fatalf("update workspace: %v", err) } // Stream a chat completion ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() stream, err := client.ChatCompletionStreamWithContext(ctx, "default", &meilisearch.ChatCompletionQuery{ Model: "gpt-4o-mini", Messages: []*meilisearch.ChatCompletionMessage{ {Role: "system", Content: "You are a helpful assistant. Answer using only the indexed documents."}, {Role: "user", Content: "What are some good action movies from 2010 onwards?"}, }, Stream: true, }) if err != nil { log.Fatalf("start stream: %v", err) } defer stream.Close() fmt.Print("Assistant: ") for stream.Next() { chunk := stream.Current() if chunk != nil && len(chunk.Choices) > 0 && chunk.Choices[0].Delta.Content != nil { fmt.Print(*chunk.Choices[0].Delta.Content) } } if err := stream.Err(); err != nil && !errors.Is(err, io.EOF) { log.Fatalf("stream error: %v", err) } fmt.Println() // List all chat workspaces workspaces, err := client.ListChatWorkspaces(&meilisearch.ListChatWorkSpaceQuery{Limit: 10}) if err != nil { log.Fatalf("list workspaces: %v", err) } for _, ws := range workspaces.Results { fmt.Printf("Workspace: %s\n", ws.UID) } } ``` -------------------------------- ### Configure Custom JSON Marshaler/Unmarshaler in Go Source: https://github.com/meilisearch/meilisearch-go/blob/main/README.md Use this snippet to configure the Meilisearch client with a custom JSON marshaler and unmarshaler for improved performance. Ensure the chosen library is imported. ```go 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), ) } ```