Skip to main content
โšก Calmops

Meilisearch: The Complete Guide to Lightning-Fast Search

Introduction

Search is a fundamental component of modern applications. Whether you are building an e-commerce platform, a documentation site, or an enterprise application, users expect fast and relevant search results. Traditional database queries often fall short when it comes to text search, leading to poor user experiences and lost opportunities.

Meilisearch is an open-source search engine that delivers lightning-fast search experiences with minimal configuration. Designed with developer experience in mind, it provides typo-tolerant results, faceted search, and instant feedback that users have come to expect from modern search solutions.

In this comprehensive guide, we will explore Meilisearch from the ground up, covering installation, core concepts, indexing strategies, and advanced search features. By the end of this article, you will have a solid foundation to implement Meilisearch in your own projects.

What is Meilisearch?

Meilisearch is a fast, open-source search engine written in Rust that provides instant search results with typo tolerance. It is designed to be easy to use while delivering production-ready performance. Unlike complex enterprise search solutions, Meilisearch prioritizes developer experience and simplicity without sacrificing functionality.

Key Characteristics

Meilisearch stands out in the search engine landscape through several defining characteristics. First, it offers instant search results, typically responding in under 50 milliseconds, making search feel instantaneous to users. Second, it provides built-in typo tolerance, allowing users to make mistakes in their queries while still finding relevant results. Third, it features a developer-friendly API with comprehensive SDKs available for most popular programming languages.

The search engine also offers faceted search and filters, enabling users to narrow down results based on multiple criteria. It supports geo-search for location-based queries and provides full-text search across multiple languages. Additionally, Meilisearch is designed to be horizontally scalable, though it works perfectly as a single-node solution for most use cases.

Meilisearch vs Other Search Engines

When comparing Meilisearch to other search solutions, several distinctions become apparent. Unlike Elasticsearch, which requires significant configuration and expertise, Meilisearch works out of the box with minimal setup. Unlike Algolia, which is a managed service with usage-based pricing, Meilisearch can be self-hosted entirely for free. Unlike SQLite FTS5, which is limited to single-node deployments, Meilisearch provides a more feature-rich solution with better scaling options.

Meilisearch occupies a unique position as a middle ground between simple full-text search capabilities and enterprise-grade search solutions. It offers enough features for most use cases while remaining accessible to developers who do not have specialized search expertise.

Installation and Setup

Meilisearch can be installed through multiple methods depending on your environment and requirements. This section covers the most common installation approaches.

Docker Installation

The easiest way to get started with Meilisearch is through Docker. This method works on any system that supports Docker and provides isolation from your host system.

# Pull the latest Meilisearch image
docker pull getmeili/meilisearch:latest

# Run Meilisearch with a master key
docker run -d \
  --name meilisearch \
  -p 7700:7700 \
  -e MEILI_MASTER_KEY=your_master_key \
  getmeili/meilisearch:latest

# Verify the container is running
docker ps

Once running, you can access the Meilisearch dashboard at http://localhost:7700. The Docker installation is suitable for development and testing environments. For production deployments, you would want to add persistent storage and proper security configurations.

Binary Installation

For production deployments or systems without Docker, you can install Meilisearch directly from pre-built binaries. Meilisearch provides binaries for Linux, macOS, and Windows.

# Download the latest version
curl -L https://install.meilisearch.com | sh

# Make the binary executable
chmod +x meilisearch

# Run Meilisearch with a master key
./meilisearch --master-key="your_master_key"

On macOS, you can also use Homebrew for installation:

brew install meilisearch
meilisearch --master-key="your_master_key"

Cloud Providers

Meilisearch Cloud provides a fully managed solution for those who prefer not to manage their own infrastructure. It offers automatic scaling, managed backups, and enterprise-grade security features. The cloud service includes a free tier suitable for small projects and development.

To get started with Meilisearch Cloud, visit the official website and create an account. You will receive an API endpoint and API key to use with your applications.

Core Concepts

Understanding Meilisearch requires familiarity with several core concepts that form the foundation of how the search engine operates.

Documents

Documents are the fundamental unit of data in Meilisearch. They are JSON objects that you add to an index, and they represent the items that will be searchable. Each document must contain a unique identifier field, typically named id, though this can be configured.

{
  "id": "1",
  "title": "The Great Gatsby",
  "author": "F. Scott Fitzgerald",
  "genre": "Classic Literature",
  "publication_year": 1925,
  "description": "A novel about the American Dream set in the Jazz Age"
}

Documents in Meilisearch are schemaless, meaning you do not need to define a rigid structure before adding data. Each document can have different fields, though for consistency and optimal search performance, it is recommended to use a uniform structure.

Indexes

An index is a collection of documents that share similar search functionality. You can create multiple indexes within a single Meilisearch instance to organize different types of content. For example, you might have separate indexes for products, customers, and blog posts.

Creating an index is straightforward:

curl -X POST 'http://localhost:7700/indexes' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{"uid": "books", "primaryKey": "id"}'

The uid identifies the index for subsequent operations, and the primaryKey specifies which field contains the unique identifier for each document.

Settings

Meilisearch provides extensive configuration options through settings that control how search behaves. These settings include searchable attributes, filterable attributes, sortable attributes, and ranking rules.

Searchable attributes determine which fields are searched when a query is executed:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "searchableAttributes": ["title", "author", "description"]
  }'

Filterable attributes enable filtering on specific fields:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "filterableAttributes": ["genre", "publication_year", "author"]
  }'

Sortable attributes allow results to be ordered by specific fields:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "sortableAttributes": ["publication_year", "title"]
  }'

Indexing Documents

Adding documents to Meilisearch is called indexing. The search engine processes incoming documents, creates the necessary data structures for fast search, and makes them available for queries.

Adding Documents

You can add documents using the Meilisearch API:

curl -X POST 'http://localhost:7700/indexes/books/documents' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "id": "1",
      "title": "The Great Gatsby",
      "author": "F. Scott Fitzgerald",
      "genre": "Classic Literature",
      "publication_year": 1925
    },
    {
      "id": "2",
      "title": "1984",
      "author": "George Orwell",
      "genre": "Dystopian Fiction",
      "publication_year": 1949
    },
    {
      "id": "3",
      "title": "To Kill a Mockingbird",
      "author": "Harper Lee",
      "genre": "Classic Literature",
      "publication_year": 1960
    }
  ]'

Meilisearch processes documents asynchronously in the background. For small datasets, this happens almost instantly, but larger datasets may take longer to index.

Batch Operations

For large datasets, batch processing is more efficient than adding documents one at a time. You can add thousands of documents in a single API call:

curl -X POST 'http://localhost:7700/indexes/books/documents' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  --data-binary @large_dataset.json

When dealing with very large datasets, consider splitting them into smaller batches to avoid timeout issues and memory constraints.

Updating Documents

To update existing documents, use the same endpoint with the documents containing the updated data and the same identifiers:

curl -X PUT 'http://localhost:7700/indexes/books/documents' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "id": "1",
      "title": "The Great Gatsby",
      "author": "F. Scott Fitzgerald",
      "genre": "Classic Literature",
      "publication_year": 1925,
      "rating": 4.5
    }
  ]'

Meilisearch handles updates efficiently, merging the new data with existing documents.

Deleting Documents

You can delete individual documents by their ID, or delete all documents in an index:

# Delete a single document
curl -X DELETE 'http://localhost:7700/indexes/books/documents/1' \
  -H 'Authorization: Bearer your_master_key"

# Delete multiple documents
curl -X POST 'http://localhost:7700/indexes/books/documents/delete' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{"ids": ["1", "2", "3"]}'

# Delete all documents
curl -X DELETE 'http://localhost:7700/indexes/books/documents' \
  -H 'Authorization: Bearer your_master_key'

Search Fundamentals

Meilisearch provides a powerful search API that supports various query types and parameters. Understanding these capabilities allows you to build sophisticated search experiences.

The simplest search query searches across all searchable attributes:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{"q": "great gatsby"}'

The response includes the matching documents along with additional information:

{
  "hits": [
    {
      "id": "1",
      "title": "The Great Gatsby",
      "author": "F. Scott Fitzgerald",
      "genre": "Classic Literature",
      "publication_year": 1925
    }
  ],
  "query": "great gatsby",
  "processingTimeMs": 2,
  "hitsPerPage": 20,
  "page": 1,
  "totalHits": 1
}

For exact phrase matching, enclose the query in quotation marks:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{"q": "\"great gatsby\""}'

This returns only documents containing the exact phrase “great gatsby”.

Filters

Filters allow users to narrow down results based on specific criteria. First, ensure the field is configured as a filterable attribute:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "filter": "genre = \"Dystopian Fiction\""
  }'

You can combine multiple filters using AND and OR operators:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "filter": "genre = \"Dystopian Fiction\" AND publication_year > 1940"
  }'

Facets

Facets provide aggregated information about the search results, useful for building filter interfaces:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "facets": ["genre", "author"]
  }'

The response includes facet distribution counts:

{
  "hits": [...],
  "facetDistribution": {
    "genre": {
      "Dystopian Fiction": 1,
      "Classic Literature": 2
    },
    "author": {
      "George Orwell": 1,
      "F. Scott Fitzgerald": 1,
      "Harper Lee": 1
    }
  }
}

Sorting

Sort results by any sortable attribute:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "sort": ["publication_year:desc"]
  }'

You can sort in ascending or descending order by using :asc or :desc suffixes.

Pagination

Meilisearch supports both offset-based and page-based pagination:

# Offset-based
curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "offset": 20,
    "limit": 20
  }'

# Page-based
curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "fiction",
    "page": 2,
    "hitsPerPage": 20
  }'

Highlighting

Highlight matching terms in results to improve user experience:

curl -X POST 'http://localhost:7700/indexes/books/search' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "q": "gatsby",
    "attributesToHighlight": ["title", "description"]
  }'

The response includes highlighted snippets:

{
  "hits": [
    {
      "id": "1",
      "title": "The Great <em>Gatsby</em>",
      "_formatted": {
        "title": "The Great <em>Gatsby</em>"
      }
    }
  ]
}

Typo Tolerance

One of Meilisearch’s most distinctive features is its built-in typo tolerance. This feature allows users to find results even when they make spelling mistakes, typos, or use partial words.

How Typo Tolerance Works

Meilisearch automatically handles typos without any configuration. The search engine uses a combination of techniques to match queries with documents despite spelling errors. It considers the edit distance between words, which measures how many character changes are needed to transform one word into another.

By default, Meilisearch allows up to one typo for short words (less than five characters) and up to two typos for longer words. This behavior can be customized through settings.

Configuring Typo Tolerance

You can adjust typo tolerance settings to match your use case:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "typoTolerance": {
      "enabled": true,
      "minWordSizeForTypos": {
        "oneTypo": 4,
        "twoTypos": 8
      },
      "words": ["meilisearch", "documentation"]
    }
  }'

This configuration increases the minimum word size for typo tolerance and specifies certain words that should always be treated as single words for typo matching.

Disabling Typo Tolerance

For certain use cases, you might want to disable typo tolerance. For example, when searching codes, IDs, or other exact-match fields:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "typoTolerance": {
      "enabled": false
    }
  }'

You can also disable typo tolerance for specific attributes:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "typoTolerance": {
      "disableOnAttributes": ["isbn", "product_code"]
    }
  }'

Ranking and Relevance

Meilisearch uses a sophisticated ranking system to order results by relevance. Understanding how this works helps you optimize search results for your specific needs.

Ranking Rules

Meilisearch applies ranking rules in a specific order to determine result relevance. The default order is:

  1. Words - Number of query words matched
  2. Typo - Fewer typos preferred
  3. Proximity - Query words closer together in document
  4. Attribute - Matches in more important attributes
  5. Sort - Results sorted by specified criteria
  6. Exactness - Exact matches preferred

You can customize this order:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "rankingRules": [
      "words",
      "typo",
      "proximity",
      "attribute",
      "sort",
      "exactness",
      "custom_rule"
    ]
  }'

Custom Ranking

You can create custom ranking rules based on numeric fields:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "rankingRules": [
      "words",
      "typo",
      "proximity",
      "attribute",
      "sort",
      "exactness",
      "rating:desc"
    ]
  }'

This example adds a custom rule that prioritizes books with higher ratings.

Stop Words

Stop words are common words that are ignored during search. By default, Meilisearch handles this intelligently, but you can customize the list:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "stopWords": ["the", "a", "an", "and", "or", "but"]
  }'

Synonyms

Define synonyms to ensure related terms return similar results:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "synonyms": {
      "sci-fi": ["science fiction"],
      "fantasy": ["fantasy fiction"],
      "classic": ["classic literature", "classics"]
    }
  }'

Now searches for “sci-fi” will also match documents containing “science fiction”.

SDK Integration

Meilisearch provides official SDKs for many programming languages, making integration straightforward.

JavaScript/TypeScript

import { MeiliSearch } from 'meilisearch'

const client = new MeiliSearch({
  host: 'http://localhost:7700',
  apiKey: 'your_master_key'
})

const index = client.index('books')

// Search
const results = await index.search('gatsby')

// Add documents
await index.addDocuments([
  { id: '1', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' }
])

Python

from meilisearch import Client

client = Client('http://localhost:7700', 'your_master_key')
index = client.index('books')

# Search
results = index.search('gatsby')

# Add documents
index.add_documents([
    {'id': '1', 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'}
])

Go

package main

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

func main() {
    client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("your_master_key"))
    
    // Search
    client.Index("books").Search("gatsby", nil)
    
    // Add documents
    client.Index("books").AddDocuments([]map[string]interface{}{
        {"id": "1", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
    })
}

Best Practices

Following best practices ensures optimal performance and user experience when implementing Meilisearch.

Index Design

Design your indexes with search patterns in mind. Group related content into the same index, and consider the types of queries users will make. If you have very different content types, use separate indexes.

Attribute Ordering

The order of searchable attributes matters. Place the most important attributes first in the searchable attributes list:

curl -X PATCH 'http://localhost:7700/indexes/books/settings' \
  -H 'Authorization: Bearer your_master_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "searchableAttributes": [
      "title",
      "author",
      "description",
      "genre"
    ]
  }'

Matches in “title” are considered more important than matches in “description”.

Data Types

Use appropriate data types for your fields. Numeric fields used in filtering or sorting should be numbers, not strings. Date fields should be in ISO 8601 format for proper comparison operations.

Index Size and Performance

Meilisearch is optimized for datasets up to several million documents. For larger datasets, consider splitting data across multiple indexes or implementing a sharding strategy. Monitor memory usage and adjust resource allocation as needed.

Common Pitfalls

Avoid these common mistakes when implementing Meilisearch.

Forgetting to Configure Attributes

Many developers forget to configure searchable, filterable, and sortable attributes. Without these settings, Meilisearch uses all attributes by default, which can impact performance and relevance. Always explicitly configure these settings for production deployments.

Indexing Too Much Data

Not all document fields need to be searchable. Including large text fields like full article content can slow down indexing and search. Only make essential fields searchable.

Ignoring API Keys

In production, always use appropriate API keys. The master key should be kept secure and never exposed to clients. Create specific API keys with limited permissions for different use cases.

Not Setting Up Backups

Meilisearch does not have built-in backup functionality. Implement regular snapshots of your data if durability is important for your application.

External Resources

Conclusion

Meilisearch provides an excellent balance of simplicity and power for implementing search functionality. Its typo-tolerant, instant search results make it ideal for applications where user experience is paramount. With straightforward installation, comprehensive SDKs, and extensive configuration options, Meilisearch serves both beginners and advanced use cases.

In this guide, we covered installation methods, core concepts, document indexing, search fundamentals, typo tolerance, and ranking strategies. You now have the foundation to implement Meilisearch in your applications. In subsequent articles, we will explore operational aspects, internal architecture, and AI integrations.

Comments