Categorygithub.com/meilisearch/meilisearch-go
modulepackage
0.31.0
Repository: https://github.com/meilisearch/meilisearch-go.git
Documentation: pkg.go.dev

# README

Meilisearch-Go

Meilisearch Go

Meilisearch | Meilisearch Cloud | Documentation | Discord | Roadmap | Website | FAQ

GitHub Workflow Status Test CodeCov Go Reference License Bors enabled

⚡ The Meilisearch API client written for Golang

Meilisearch Go is the Meilisearch API client for Go developers.

Meilisearch is an open-source search engine. Learn more about Meilisearch.

Table of Contents

📖 Documentation

This readme contains all the documentation you need to start using this Meilisearch SDK.

For general information on how to use Meilisearch—such as our API reference, tutorials, guides, and in-depth articles—refer to our main documentation website.

🔧 Installation

With go get in command line:

go get github.com/meilisearch/meilisearch-go

Run Meilisearch

⚡️ Launch, scale, and streamline in minutes with Meilisearch Cloud—no maintenance, no commitment, cancel anytime. Try it free now.

🪨 Prefer to self-host? Download and deploy our fast, open-source search engine on your own infrastructure.

🚀 Getting started

Add documents

package main

import (
	"fmt"
	"os"

	"github.com/meilisearch/meilisearch-go"
)

func main() {
	client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("foobar"))

	// An index is where the documents are stored.
	index := client.Index("movies")

	// If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
	documents := []map[string]interface{}{
        { "id": 1, "title": "Carol", "genres": []string{"Romance", "Drama"} },
        { "id": 2, "title": "Wonder Woman", "genres": []string{"Action", "Adventure"} },
        { "id": 3, "title": "Life of Pi", "genres": []string{"Adventure", "Drama"} },
        { "id": 4, "title": "Mad Max: Fury Road", "genres": []string{"Adventure", "Science Fiction"} },
        { "id": 5, "title": "Moana", "genres": []string{"Fantasy", "Action"} },
        { "id": 6, "title": "Philadelphia", "genres": []string{"Drama"} },
	}
	task, err := index.AddDocuments(documents)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(task.TaskUID)
}

With the taskUID, you can check the status (enqueued, canceled, processing, succeeded or failed) of your documents addition using the task endpoint.

Basic Search

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

JSON output:

{
  "hits": [{
    "id": 6,
    "title": "Philadelphia",
    "genres": ["Drama"]
  }],
  "offset": 0,
  "limit": 10,
  "processingTimeMs": 1,
  "query": "philoudelphia"
}

Custom Search

All the supported options are described in the search parameters section of the documentation.

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

JSON output:

{
    "hits": [
        {
            "id": 2,
            "title": "Wonder Woman",
            "genres": ["Action", "Adventure"],
            "_formatted": {
                "id": 2,
                "title": "<em>Wonder</em> Woman"
            }
        }
    ],
    "offset": 0,
    "limit": 20,
    "processingTimeMs": 0,
    "query": "wonder"
}

Custom Search With Filters

If you want to enable filtering, you must add your attributes to the filterableAttributes index setting.

task, err := index.UpdateFilterableAttributes(&[]string{"id", "genres"})

You only need to perform this operation once.

Note that Meilisearch will rebuild your index whenever you update filterableAttributes. Depending on the size of your dataset, this might take time. You can track the process using the task status.

Then, you can perform the search:

searchRes, err := index.Search("wonder",
    &meilisearch.SearchRequest{
        Filter: "id > 1 AND genres = Action",
    })
{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action","Adventure"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "estimatedTotalHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

Customize Client

The client supports many customization options:

  • WithCustomClient sets a custom http.Client.
  • WithCustomClientWithTLS enables TLS for the HTTP client.
  • WithAPIKey sets the API key or master key.
  • WithContentEncoding configures content encoding for requests and responses. Currently, gzip, deflate, and brotli are supported.
  • WithCustomRetries customizes retry behavior based on specific HTTP status codes (retryOnStatus, defaults to 502, 503, and 504) and allows setting the maximum number of retries.
  • DisableRetries disables the retry logic. By default, retries are enabled.
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),
    )
}

🤖 Compatibility with Meilisearch

This package guarantees compatibility with version v1.x of Meilisearch, but some features may not be present. Please check the issues for more info.

⚡️ Benchmark Performance

The Meilisearch client performance was tested in client_bench_test.go.

goos: linux
goarch: amd64
pkg: github.com/meilisearch/meilisearch-go
cpu: AMD Ryzen 7 5700U with Radeon Graphics

Results

Benchmark_ExecuteRequest-16                  	   10000	    105880 ns/op	    7241 B/op	      87 allocs/op
Benchmark_ExecuteRequestWithEncoding-16      	    2716	    455548 ns/op	 1041998 B/op	     169 allocs/op
Benchmark_ExecuteRequestWithoutRetries-16    	       1	3002787257 ns/op	   56528 B/op	     332 allocs/op

💡 Learn more

The following sections in our main documentation website may interest you:

⚙️ Contributing

Any new contribution is more than welcome in this project!

If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!


Meilisearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.

# Functions

Connect create service manager and check connection with meilisearch.
DisableRetries disable retry logic in client.
No description provided by the author
No description provided by the author
New create new service manager for operating on meilisearch.
VersionErrorHintMessage a hint to the error message if it may come from a version incompatibility with meilisearch.
WithAPIKey is API key or master key.
WithContentEncoding support the Content-Encoding header indicates the media type is compressed by a given algorithm.
WithCustomClient set custom http.Client.
WithCustomClientWithTLS client support tls configuration.
WithCustomRetries set retry on specific http error code and max retries (min: 1, max: 255).

# Constants

All only returns documents that contain all query terms.
No description provided by the author
No description provided by the author
No description provided by the author
ByAttribute determine if multiple query terms are present in the same attribute.
ByWord calculate the precise distance between query terms.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ErrCodeMarshalRequest impossible to serialize request body.
ErrCodeResponseUnmarshalBody impossible deserialize the response body.
ErrCodeUnknown default error code, undefined.
Frequency returns documents containing all the query terms first.
No description provided by the author
No description provided by the author
Last returns documents containing all the query terms first.
MeilisearchApiError send by the meilisearch api.
MeilisearchApiErrorWithoutMessage MeilisearchApiError send by the meilisearch api.
MeilisearchCommunicationError impossible execute a request.
MeilisearchMaxRetriesExceeded used max retries and exceeded.
MeilisearchTimeoutError.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
TaskStatusCanceled the task was canceled.
TaskStatusEnqueued the task request has been received and will be processed soon.
TaskStatusFailed a failure occurred when processing the task, no changes were made to the database.
TaskStatusProcessing the task is being processed.
TaskStatusSucceeded the task has been successfully processed.
TaskStatusUnknown is the default TaskStatus, should not exist.
TaskTypeDocumentAdditionOrUpdate represents a document addition or update in an index.
TaskTypeDocumentDeletion represents a document deletion from an index.
TaskTypeDumpCreation represents a dump creation.
TaskTypeIndexCreation represents an index creation.
TaskTypeIndexDeletion represents an index deletion.
TaskTypeIndexSwap represents an index swap.
TaskTypeIndexUpdate represents an index update.
TaskTypeSettingsUpdate represents a settings update.
TaskTypeSnapshotCreation represents a snapshot creation.
TaskTypeTaskCancelation represents a task cancelation.
TaskTypeTaskDeletion represents a task deletion.
No description provided by the author

# Variables

General errors.
General errors.
General errors.
General errors.
General errors.

# Structs

CancelTasksQuery is a list of filter available to send as query parameters.
CreateIndexRequest is the request body for create index method.
No description provided by the author
DeleteTasksQuery is a list of filter available to send as query parameters.
No description provided by the author
Distribution represents a statistical distribution with mean and standard deviation (sigma).
DocumentQuery is the request body get one documents method.
DocumentsQuery is the request body for list documents method.
No description provided by the author
Embedder represents a unified configuration for various embedder types.
Error is the internal error structure that all exposed method use.
Type for experimental features with additional client field.
ExperimentalFeaturesResult represents the experimental features result from the API.
No description provided by the author
Faceting is the type that represents the faceting setting in meilisearch.
No description provided by the author
No description provided by the author
Health is the request body for set meilisearch health.
No description provided by the author
No description provided by the author
IndexesResults return of multiple indexes is wrap in a IndexesResults.
No description provided by the author
Key allow the user to connect to the meilisearch instance Documentation: https://www.meilisearch.com/docs/learn/security/master_api_keys#protecting-a-meilisearch-instance.
KeyParsed this structure is used to send the exact ISO-8601 time format managed by meilisearch.
No description provided by the author
KeysResults return of multiple keys is wrap in a KeysResults.
KeyUpdate this structure is used to update a Key.
No description provided by the author
MinWordSizeForTypos is the type that represents the minWordSizeForTypos setting in the typo tolerance setting in meilisearch.
No description provided by the author
No description provided by the author
No description provided by the author
Pagination is the type that represents the pagination setting in meilisearch.
No description provided by the author
SearchRequest is the request url param needed for a search query.
No description provided by the author
SearchResponse is the response body for search method.
Settings is the type that represents the settings in meilisearch.
SimilarDocumentQuery is query parameters of similar documents.
No description provided by the author
Stats is the type that represent all stats.
StatsIndex is the type that represent the stats of an index in meilisearch.
No description provided by the author
Task indicates information about a task resource Documentation: https://www.meilisearch.com/docs/learn/advanced/asynchronous_operations.
TaskInfo indicates information regarding a task returned by an asynchronous method Documentation: https://www.meilisearch.com/docs/reference/api/tasks#tasks.
TaskResult return of multiple tasks is wrap in a TaskResult.
TasksQuery is a list of filter available to send as query parameters.
TenantTokenClaims custom Claims structure to create a Tenant Token.
TenantTokenOptions information to create a tenant token ExpiresAt is a time.Time when the key will expire.
TypoTolerance is the type that represents the typo tolerance setting in meilisearch.
No description provided by the author
UpdateIndexRequest is the request body for update Index primary key.
Version is the type that represents the versions in meilisearch.

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
ErrCode are all possible errors found during requests.
No description provided by the author
No description provided by the author
No description provided by the author
RawType is an alias for raw byte[].
No description provided by the author
No description provided by the author
No description provided by the author
Unknown is unknown json type.