Integrate Meilisearch with Statamic

Arlind Musliu Portrait
Arlind Musliu

April 17, 2024 · 3 min read · 131 views

Statamic and Meilisearch logos

Are you aiming to enhance your Statamic site's search capabilities and deliver fast results? Meilisearch is the perfect solution for you. In this guide, we'll walk through the steps to seamlessly integrate Meilisearch with Statamic, ensuring that your users can easily find what they need.

Statamic Searching

Before you start mixing Meilisearch into your Statamic site, it's really important to get how Statamic's search works. We urge you to read our detailed write-up on Statamic Search first. Knowing this stuff well will help you make the most of what Meilisearch can do to improve your site's search function.

Installing Meilisearch

Let's install Meilisearch on your local machine. Ensure you have Homebrew installed, then execute the following command in your terminal:

brew install meilisearch

Once installed, start Meilisearch with the command:

meilisearch

This will run Meilisearch on your system.

Meilisearch Statamic Addon

Now that Meilisearch is installed and running, you can proceed to install the Meilisearch addon for Statamic. The addon provides the necessary functionality to integrate Meilisearch with your Statamic site. To install the addon, run the following command:

composer require statamic-rad-pack/meilisearch

Configure a New Search Driver

Next, we'll adjust our Statamic configuration. In your config/statamic/search.php config file, add a new Meilisearch driver to the drivers array. This configuration should include your Meilisearch host and secret, which you'll reference from your environment variables for security and flexibility.

Setup a New Search Index

We also need to define the Meilisearch driver, set the news collection as the searchable content, and choose title and url as the fields for indexing. This will ensure the most relevant information is readily searchable. Now let's edit the statamic search file config/statamic/search.php.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default search index
    |--------------------------------------------------------------------------
    |
    | This option controls the search index that gets queried when performing
    | search functions without explicitly selecting another index.
    |
    */

    'default' => env('STATAMIC_DEFAULT_SEARCH_INDEX', 'default'),

    /*
    |--------------------------------------------------------------------------
    | Search Indexes
    |--------------------------------------------------------------------------
    |
    | Here you can define all of the available search indexes.
    |
    */

    'indexes' => [

        'default' => [
            'driver' => 'local',
            'searchables' => ['collection:posts'],
            'fields' => ['title', 'categories', 'tags'],
        ],

		'news' => [
			'driver' => 'meilisearch',
			'searchables' => 'collection:news',
			'fields' => ['title', 'url'],
		],

    ],

    /*
    |--------------------------------------------------------------------------
    | Driver Defaults
    |--------------------------------------------------------------------------
    |
    | Here you can specify default configuration to be applied to all indexes
    | that use the corresponding driver. For instance, if you have two
    | indexes that use the "local" driver, both of them can have the
    | same base configuration. You may override for each index.
    |
    */

    'drivers' => [

        'local' => [
            'path' => storage_path('statamic/search'),
        ],

		'meilisearch' => [
			'credentials' => [
				'url' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
				'secret' => env('MEILISEARCH_KEY'),
			],
		],

    ],

    /*
    |--------------------------------------------------------------------------
    | Search Defaults
    |--------------------------------------------------------------------------
    |
    | Here you can specify default configuration to be applied to all indexes
    | regardless of the driver. You can override these per driver or per index.
    |
    */

    'defaults' => [
        'fields' => ['title'],
    ],

];

Refresh Your News Index

To synchronize your content with Meilisearch, use the following command to update your news index:

php please search:update name

This command will refresh the index with your latest content, making it immediately searchable.

Verify Your Setup Locally

After indexing, navigate to your local Meilisearch web interface to confirm that your news collection entries populate the index. You can access it via:

http://localhost:7700

Seeing your content indexed confirms that you're on the right track and ready for the next step.

Frontend Searching with Alpine.js

To enhance the user experience on the front end, integrate Meilisearch's official JavaScript library with Alpine.js. This combination allows you to create a responsive search component that provides instant and accurate results as users type their queries.

Alpine.data("search", () => ({
    modalOpen: false,
    query: "",
    index: null,
    results: null,

    init() {
        const client = new MeiliSearch({
            host: process.env.MIX_MEILISEARCH_HOST,
            apiKey: process.env.MIX_MEILISEARCH_KEY,
        });

        this.index = client.index("news");
    },

    search() {
        this.$watch("query", async (query) => {
            if (query === "") return (this.results = null);

            this.results = await this.index.search(query, { limit: 10 });
        });
    },

    clear() {
        this.results = null;
        this.query = "";
        this.modalOpen = false;
    },
}));

Template code:

<div x-data="search">
    <input placeholder="Search for news" type="text"
		   x-model="query" @click.outside="clear" @input="search">
    <template x-if="results">
        <template x-show="results.hits.length > 0" x-for="(hit, index) in results.hits">
            <a x-bind:href="hit.url">
                <h2 x-text="hit.title"></h2>
            </a>
        </template>
    </template>
</div>

Take Meilisearch to the Cloud

As you prepare to scale, sign up for a Meilisearch Cloud account and set up a new project. After your project is activated, update your environment variables with your new Meilisearch host and key.

After changing this, make sure to update the search index again:

php please search:update news

With this, your documents are now searchable in the cloud, providing a scalable and professional search experience for your Statamic site.

Conclusion

By following these steps, you've successfully integrated Meilisearch with your Statamic site, providing an exceptional search experience for your users. Whether you're working locally or in the cloud, Meilisearch ensures your content is discoverable at blazing speeds.


Bring Your Ideas to Life 🚀

Kickstart Your Statamic Project with the #1 Statamic Agency

Are you planning a new Statamic project or thinking about migrating your WordPress site to Statamic?

Learn more about our expertise as a renowned Statamic development agency.

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Statamic
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!