A Meilisearch client: indexes, documents, full text, faceted, hybrid and federated search, settings, tasks and API keys.
import db.meilisearch
Meilisearch is a fast search engine with typo tolerance, filters, facets and AI powered hybrid search. This package talks to its HTTP API directly with net.http and covers all of it: indexes, documents in JSON, NDJSON or CSV, every search parameter, multi-search and federated search, facet search, similar documents, every index setting, tasks and batches, API keys and tenant tokens, webhooks, dynamic search rules and chat workspaces. This page starts with a tutorial; the full reference of every function and type comes after it.
Tutorial: a movie search in eleven steps
The steps below build one small movie catalogue and search it. Each step is a complete program, and the output under it is what it printed against a real Meilisearch 1.55. Run them in order, because each step uses the data the earlier ones left behind.
First start a server. With Docker that is one command; without it, download the meilisearch binary from the Meilisearch releases page and run it with the same key:
docker run -p 7700:7700 -e MEILI_MASTER_KEY=masterKey getmeili/meilisearch:v1.55.0
The programs assume http://127.0.0.1:7700 and the master key masterKey. A real deployment uses a long random master key and gives applications smaller keys, as step 9 shows.
1. Connect
New makes a client: a plain value with the address and the key, which threads can share. WithTimeout returns a copy that stops waiting after the given milliseconds; without it a request waits as long as the server takes. Every call that can fail takes an Error as its last argument. Ok tells you whether the call worked and ErrorString turns the error into one line.
meili-connect.salam
import db.meilisearch
funcmain:
c := meilisearch.WithTimeout(meilisearch.New("http://127.0.0.1:7700", "masterKey"), 5000)
ifnot meilisearch.IsHealthy(c):
println"Meilisearch is not running at " + c.host
ret1endmut err := meilisearch.Error {}
version := meilisearch.GetVersion(c, err)
println"connected to Meilisearch " + version.pkg_version
meilisearch.GetIndex(c, "no_such_index", err)
ifnot meilisearch.Ok(err):
println meilisearch.ErrorString(err)
endret0end
Output
connected to Meilisearch 1.55.0
meilisearch 404 [index_not_found]: Index `no_such_index` not found.
The error carries everything Meilisearch sent: the HTTP status, the code to branch on (here index_not_found), the message and a link to its documentation. When the server cannot be reached at all, code is communication_error, or timeout when the time limit ran out.
2. Create an index and add documents
An index is a named collection of documents, each with a unique primary key. Documents can be Salam structs: AddDocumentsOf turns each one into JSON. AddDocuments takes JSON text instead, and AddDocumentsNdjson and AddDocumentsCsv take those formats.
meili-index.salam
import db.meilisearch
structMovie:
pub id: int = 0pub title: str = ""pub genre: str = ""pub year: int = 0pub overview: str = ""endfuncmovie(id: int, title: str, genre: str, year: int, overview: str): Movie:
ret Movie {
id = id,
title = title,
genre = genre,
year = year,
overview = overview
}
endfuncmain:
c := meilisearch.New("http://127.0.0.1:7700", "masterKey")
mut err := meilisearch.Error {}
meilisearch.Wait(c, meilisearch.CreateIndex(c, "movies", "id", err), err)
mut movies := Vector {} asVector<Movie>
movies.Push(
movie(
1,
"Heat",
"Crime",
1995,
"A detective hunts a crew of professional thieves in Los Angeles."
)
)
movies.Push(
movie(2, "Moana", "Family", 2016, "A girl sails across the ocean to save her island.")
)
movies.Push(
movie(3, "Alien", "Horror", 1979, "The crew of a space freighter meets a deadly creature.")
)
movies.Push(
movie(
4, "Up", "Family", 2009, "An old man flies his house away with thousands of balloons."
)
)
movies.Push(
movie(
5,
"Arrival",
"Drama",
2016,
"A linguist learns to talk with visitors from another world."
)
)
movies.Push(movie(6, "Dune", "Adventure", 2021, "A young noble fights for a desert planet."))
movies.Push(
movie(
7,
"Interstellar",
"Drama",
2014,
"Explorers travel through a wormhole to find a new home."
)
)
movies.Push(
movie(8, "Coco", "Family", 2017, "A boy enters the land of the dead to find his family.")
)
task := meilisearch.Wait(c, meilisearch.AddDocumentsOf(c, "movies", movies, "id", err), err)
ifnot meilisearch.Ok(err):
println meilisearch.ErrorString(err)
ret1endprintln"indexing: " + task.status
stats := meilisearch.GetIndexStats(c, "movies", err)
println"documents in movies: " + stats.number_of_documents
ret0end
Output
indexing: succeeded
documents in movies: 8
Meilisearch does not apply a change at once. A write returns a TaskInfo, a receipt with a task number, and the server applies the tasks in order in the background. Wait blocks until that task has finished, which is what you want when the next line depends on the change. A batch import does not need to wait after every call; wait once at the end, or not at all.
3. Search
Query searches for some words with every option at its default. The hits come back as JSON text, and HitsAs reads them into your own struct. A struct with fewer fields than the document is fine: the extra fields are ignored.
meili-search.salam
import db.meilisearch
structMovie:
pub id: int = 0pub title: str = ""pub year: int = 0endfuncmain:
c := meilisearch.New("http://127.0.0.1:7700", "masterKey")
mut err := meilisearch.Error {}
res := meilisearch.Query(c, "movies", "spcae", err)
println"hits for \"" + res.query + "\": " + res.estimated_total_hits
mut movies := Vector {} asVector<Movie>
if meilisearch.HitsAs(res, movies, err):
each m in movies:
println" " + m.title + " (" + m.year + ")"endendret0end
Output
hits for "spcae": 1
Alien (1979)
The query was misspelled on purpose: spcae still finds the movie whose overview says space, because Meilisearch tolerates typos out of the box.
4. Filter, sort and count facets
Filtering and sorting need to be switched on for the fields involved; that is a setting of the index, and UpdateSettings changes several settings in one task. A SearchRequest holds every search option and sends only the ones you set.
meili-filter.salam
import db.meilisearch
funcmain:
c := meilisearch.New("http://127.0.0.1:7700", "masterKey")
mut err := meilisearch.Error {}
settings := `{"filterableAttributes": ["genre", "year"], "sortableAttributes": ["year"]}`
meilisearch.Wait(c, meilisearch.UpdateSettings(c, "movies", settings, err), err)
mut req := meilisearch.SearchRequest { filter = "genre = Family AND year > 2010" }
req.sort.Push("year:desc")
req.facets.Push("genre")
req.attributes_to_retrieve.Push("title")
req.attributes_to_retrieve.Push("year")
res := meilisearch.Search(c, "movies", req, err)
ifnot meilisearch.Ok(err):
println meilisearch.ErrorString(err)
ret1endeach hit in res.hits:
println hit
end
all := meilisearch.Search(
c, "movies", meilisearch.SearchRequest { facets = req.facets, limit = 0 }, err
)
println"genres: " + all.facet_distribution
ret0end
facets asks how many hits have each value of a field, which is how a search page shows filter options with counts. attributes_to_retrieve keeps the hits small by returning only the fields you need.
5. Highlight, crop and page through results
For a results page you usually want the matched words marked and long text cut down around them. Meilisearch adds a _formatted copy of each hit with both done. page and hits_per_page give numbered pages with an exact total; offset and limit are the cheaper choice for endless scrolling.
page 1 of 2, 2 hits
Alien: The [crew] of a space freighter…
6. Tune relevancy
Every index setting has its own Get, Update and Reset function. Synonyms make different words find each other, stop words are ignored in queries, and the searchable attributes choose which fields are searched and how much each one counts.
hits for "cartoon", a synonym of family: 1
hits for "space": 3
searchable: ["title","overview"]
Other settings follow the same pattern: UpdateRankingRules, UpdateTypoTolerance, UpdateDistinctAttribute, UpdatePagination, UpdateFaceting, UpdateDictionary and the rest in the reference below. GetSetting and UpdateSetting reach any setting by its route name, including ones newer than this package.
7. Search several indexes at once
MultiSearch sends several searches in one request and returns one result each. FederatedSearch merges them into a single ranked list, which suits one search box over different kinds of content. FacetSearch searches the values of one facet, for a filter box that completes as you type.
movies: 1 hit
books: 1 hit
federated: 2 hits in one list
genre Family: 3
8. Vector and hybrid search
Meilisearch can also search by meaning. An embedder turns documents into vectors; it can call a model such as OpenAI or Hugging Face, or take vectors you computed yourself, which is what the userProvided source in this step does. A search with hybrid_embedder mixes keyword and vector results; a hybrid_semantic_ratio of 1 uses vectors only. SimilarDocuments finds the documents nearest to one you already have.
vectors stored: succeeded
close to the query: {"title":"Dune"}
close to the query: {"title":"Arrival"}
like Moana: {"title":"Coco"}
like Moana: {"title":"Up"}
A userProvided embedder needs a vector in every document, so this step uses its own index. Add the embedder while the index is still empty and send the vectors in each document under _vectors.
9. API keys and tenant tokens
The master key can do everything, so applications should get smaller keys. CreateKey makes a key limited to some actions and indexes. A tenant token goes one step further: TenantToken signs, in your own program and without asking the server, a key that adds a filter to every search. Give each user their own token and they can search directly from the browser while seeing only their rows.
meili-keys.salam
import db.meilisearch
import time
funcmain:
admin := meilisearch.New("http://127.0.0.1:7700", "masterKey")
mut err := meilisearch.Error {}
mut r := meilisearch.KeyRequest {
name = "Shop front end", description = "Search the movies index only"
}
r.actions.Push("search")
r.indexes.Push("movies")
key := meilisearch.CreateKey(admin, r, err)
println"new key " + key.name + " can: " + key.actions.Get(0)
rules := `{"movies": {"filter": "genre = Family"}}`
token := meilisearch.TenantToken(key.uid, key.key, rules, time.Now() + 3600, err)
kids := meilisearch.New("http://127.0.0.1:7700", token)
res := meilisearch.Query(kids, "movies", "", err)
println"the token sees " + res.estimated_total_hits + " family movies"
meilisearch.Query(kids, "books", "", err)
println"books with the token: " + err.code
println"key deleted: " + meilisearch.DeleteKey(admin, key.uid, err)
ret0end
Output
new key Shop front end can: search
the token sees 3 family movies
books with the token: invalid_api_key
key deleted: true
10. Update and delete documents
AddDocuments replaces a whole document with the same id; UpdateDocuments changes only the fields you send. Documents can be deleted one by one, by a list of ids, by a filter, or all at once.
renamed: Dune: Part One (2021)
after delete: document_not_found
delete by filter: succeeded {"providedIds":0,"deletedDocuments":1,"originalFilter":"\"year < 2000\""}
left: 6
11. Tasks and failures
A write that is accepted can still fail later, while the server applies it. The error then lives on the task, not on the call that queued it. WaitForTask copies it into your Error, so the usual check works. GetTasks lists past tasks with filters on index, type, status and dates.
meili-tasks.salam
import db.meilisearch
funcmain:
c := meilisearch.New("http://127.0.0.1:7700", "masterKey")
mut err := meilisearch.Error {}
info := meilisearch.AddDocuments(c, "movies", `[{"title": "No id here"}]`, "", err)
println"queued task " + info.task_uid + ": " + info.status
task := meilisearch.WaitForTask(c, info.task_uid, 10000, 50, err)
println"finished as " + task.status
ifnot meilisearch.Ok(err):
println"why: " + err.code
endmut q := meilisearch.TaskQuery { limit = 3 }
q.index_uids.Push("movies")
q.statuses.Push(meilisearch.STATUS_SUCCEEDED)
page := meilisearch.GetTasks(c, q, err)
println"recent successful tasks on movies:"each t inpage.results:
println" " + t.kind
endret0end
Output
queued task 13: enqueued
finished as failed
why: missing_document_id
recent successful tasks on movies:
documentDeletion
documentDeletion
documentAdditionOrUpdate
More
The rest of the API works the same way; the reference below covers each function. A few pointers:
•
CreateWebhook registers a URL that Meilisearch calls when tasks finish, so you do not need to poll.
•
UpdateSearchRule pins or boosts chosen documents for chosen queries, such as a sale banner for sale; it needs the dynamicSearchRules experimental feature.
•
UpdateChatSettings and ChatCompletion answer questions in plain language from your indexes through an LLM; they need the chatCompletions feature.
•
WithMetadata tags every document write with a label that comes back on the task, to follow one import through the task list.
•
CreateDump, CreateSnapshot, GetStats, GetMetrics and SetStderrLogs are for running the server.
•
For a route with no function of its own, Request sends any method, path and JSON body.
The Salam repository has one runnable example for each part of the API, in English under tests/en/stdlib/meilisearch/examples and in Persian under tests/fa/stdlib/meilisearch/examples.
Signs a tenant token for one user: a search key that applies your filter rules to every search, made with no request to the server. Pass the uid and value of a key that may search, the search rules as JSON (empty means every index) and a Unix expiry time (0 for none).
Renders a document template or an embedder fragment and returns the result as raw JSON, to check a template before you use it; needs the renderRoute feature.
Asks the workspace a question in the OpenAI chat format. Meilisearch searches your indexes for the answer; with "stream": true the whole stream of data: lines comes back at once.
Polls a task every few milliseconds until it ends. A failed task fills the error with the task error; running past the timeout gives the code timeout. A timeout of 0 waits forever.
Makes a client. A missing http:// is added and a trailing slash is dropped; a path after the host, such as https://example.com/search behind a proxy, is kept as a prefix of every route.