Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A strapi plugin to add your collections to Meilisearch

License

NotificationsYou must be signed in to change notification settings

meilisearch/strapi-plugin-meilisearch

Repository files navigation

Meilisearch-Strapi

Meilisearch Strapi Plugin

npm versionTestsPrettierLicenseBors enabled

⚡ The Meilisearch plugin for Strapi

Meilisearch is an open-source search engine.Discover what Meilisearch is!

Add your Strapi content-types into a Meilisearch instance. The plugin listens to modifications made on your content-types and updates Meilisearch accordingly.

Table of Contents

📖 Documentation

To understand Meilisearch and how it works, see theMeilisearch's documentation.

To understand Strapi and how to create an app, seeStrapi's documentation.

🔧 Installation

This package version works with thev5 of Strapi. If you are usingStrapi v4, refer to versions underv0.12, if you are usingStrapi v3, considerthis README.

Inside your Strapi app, add the package:

Withnpm:

npm install strapi-plugin-meilisearch

Withyarn:

yarn add strapi-plugin-meilisearch

To apply the plugin to Strapi, a re-build is needed:

strapi build

You will need both a running Strapi app and a running Meilisearch instance. Forspecific version compatibility, see this section.

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.

🏃‍♂️ Run Strapi

If you don't have a running Strapi project yet, you can either launch theplayground present in this project orcreate a Strapi project.

We recommend indexing your content-types to Meilisearch in development mode to allow the server reloads needed to apply or remove listeners.

To start playground project you first need to run from the root of the repo

yarn watch:link

and after that in the playground

yarn dlx yalc add --link strapi-plugin-meilisearch&& yarn installstrapi develop// oryarn dlx yalc add --link strapi-plugin-meilisearch&& yarn installyarn develop

Run Both with Docker

You can use Docker to run Meilisearch and Strapi on the same server. A Docker configuration example can be found in the directoryresources/docker of this repository.

To run the Docker script add both filesDockerfile anddocker-compose.yaml at the root of your Strapi project and run it with the following command:docker-compose up.

🚀 Getting started

Now that you have installed the plugin, a running Meilisearch instance and, a running Strapi app, let's go to the plugin page on your admin dashboard.

On the left-navbar,Meilisearch appears under thePLUGINS category. If it does not, ensure that you have installed the plugin and re-build Strapi (seeinstallation).

🤫 Add Credentials

First, you need to configure credentials via the Strapi config, or on the plugin page.The credentials are composed of:

  • Thehost: The url to your running Meilisearch instance.
  • Theapi_key: Themaster orprivate key as the plugin requires administration permission on Meilisearch.More about permissions here.

⚠️ Themaster orprivate key should never be used tosearch on your front end. For searching, use thepublic key available onthekey route.

Using the plugin page

You can add your Meilisearch credentials in thesettings tab on the Meilisearch plugin page.

For example, using the credentials from the section above:Run Meilisearch, the following screen shows where the information should be.

Add your credentials

Once completed, click on theadd button.

Using a config file

To use the Strapi config add the following toconfig/plugins.js:

// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{// Your meili hosthost:'http://localhost:7700',// Your master key or private keyapiKey:'masterKey',},},})

Note that if you use both methods, the config file overwrites the credentials added through the plugin page.

🚛 Add your content-types to Meilisearch

If you don't have any content-types yet in your Strapi Plugin, please followStrapi quickstart.

We will use, asexample, the content-types provided by Strapi's quickstart (plus the user content-type).

On your plugin homepage, you should have two content-types appearing:restaurant,category anduser.

Content-types

By clicking on the left checkbox, the content-type is automatically indexed in Meilisearch. For example, if you click on therestaurant checkbox, the indexing to Meilisearch starts.

Content-types

Once the indexing is done, your restaurants are in Meilisearch. We will see instart searching how to try it out.

🪝 Apply Hooks

Hooks are listeners that update Meilisearch each time you add/update/delete an entry in your content-types.They are activated as soon as you add a content-type to Meilisearch. For example by clicking on the checkbox ofrestaurant.

Nonetheless, if youremove a content-type from Meilisearch by unchecking the checkbox, you need to reload the server. If you don't, actions are still listened to and applied to Meilisearch.The reload is only possible in develop mode; click on theReload Server button. If not, reload the server manually!

Remove hook from content-type

💅 Customization

It is possible to add settings for every collection. Start by creating a sub-object with the name of the collection inside yourplugins.js file.

// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{restaurant:{},},},})

Settings:

🏷 Custom index name

By default, when indexing a content-type in Meilisearch, the index in Meilisearch has the same name as the content-type. This behavior can be changed by setting theindexName property in the configuration file of the plugin.

To link a single collection to multiple indexes, you can assign an array of index names to theindexName property.

Example 1: Linking a Single Collection to a Single Index

In the following examples, therestaurant content-type in Meilisearch is calledmy_restaurant instead of the defaultrestaurant.

// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{restaurant:{indexName:'my_restaurants',},},},})
// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{restaurant:{indexName:['my_restaurants'],},},},})

It is possible to bind multiple content-types to the same index. They all have to share the sameindexName.

For example ifshoes andshirts should be bound to the same index, they must have the sameindexName in the plugin configuration:

// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{shirts:{indexName:['products'],},shoes:{indexName:['products'],},},},})

Now, on each entry addition from bothshoes andshirts the entry is added in theproduct index of Meilisearch.

Example 2: Linking a Single Collection to Multiple Indexes

Suppose you want therestaurant content-type to be indexed under bothmy_restaurants andall_food_places indexes in Meilisearch. You can achieve this by setting theindexName property to an array containing both index names, as shown in the configuration below:

// config/plugins.jsmodule.exports=()=>({//...meilisearch:{config:{restaurant:{indexName:['my_restaurants','all_food_places'],},},},})

disclaimer

Nonetheless, it is not possible to know how many entries from each content-type is added to Meilisearch.

For example, given two content-types:

  • Shoes: with 300 entries and anindexName set toproduct
  • Shirts: 200 entries and anindexName set toproduct

The indexproduct has both the entries of shoes and shirts. If the indexproduct has350 documents in Meilisearch, it is not possible to know how many of them are fromshoes orshirts.

When removingshoes orshirts from Meilisearch, both are removed as it would require too much processing to only remove one. You can still re-index only one after that.

Example with two single types:

Example of two content-types with same indexName

Examples can be foundthis directory.

🪄 Transform entries

By default, the plugin sent the data the way it is stored in your Strapi content-type. It is possible to remove or transform fields before sending your entries to Meilisearch.

Create the alteration functiontransformEntry in the plugin's configuration file. Before sending the data to Meilisearch, every entry passes through this function where the alteration is applied.

transformEntry can besynchronous orasynchronous.

You can find a lot of examples inthis directory.

Example

For example, therestaurant content-type has a relation with thecategory content-type. Inside arestaurant entry thecategories field contains an array of each category in anobject format:[{ name: "Brunch" ...}, { name: "Italian ... }].

The following transformscategories in an array of strings containing only the name of the category:

// config/plugins.jsmodule.exports={meilisearch:{config:{restaurant:{transformEntry({ entry}){// can also be asyncreturn{            ...entry,categories:entry.categories.map(category=>category.name),}},},},},}

Result:

{"id":2,"name":"Squared Pizza","categories": ["Brunch","Italian"]// other fields}

By transforming thecategories into an array of names, it is now compatible with thefiltering feature in Meilisearch.

Important: You should always return the id of the entry without any transformation toallow sync when unpublished or deleting some entries in Strapi.

🤚 Filter entries

You might want to filter out some entries. This is possible with thefilterEntry. Imagine you don't likeAlfredo's restaurant. You can filter out this specific entry.

filterEntry can besynchronous orasynchronous.

// config/plugins.jsmodule.exports={meilisearch:{config:{restaurant:{filterEntry({ entry}){// can also be asyncreturnentry.title!==`Alfredo`},},},},}

Alfredo's restaurant is not added to Meilisearch.

🏗 Add Meilisearch settings

Each index in Meilisearch can be customized with specific settings. It is possible to add yourMeilisearch settings configuration to the indexes you create using thesettings field in the plugin configuration file.

The settings are added when either: adding a content-type to Meilisearch or when updating a content-type in Meilisearch. The settings are not updated when documents are added through thelisteners.

For example

module.exports={meilisearch:{config:{restaurant:{settings:{filterableAttributes:['categories'],synonyms:{healthy:['pokeball','vegan'],},},},},},}

See resources for more settings examples.

🔎 Entries query

When indexing a content type to Meilisearch, the plugin has to fetch the documents from your database. WithentriesQuery it is possible to specify some options are applied during the fetching of the entries.The options you can set are described in thefindMany documentation of Strapi. However, we do not accept any changes on thestart parameter.

Common use cases

If you are localizing your Strapi content, an additional fieldlocale should also be added inentriesQuery.

⚠️ Warning: if you do not specifylocale: "*" inentriesQuery, you may not index all available entries, potentially leading to missing products in your search results. To ensure all entries in every language are indexed in Meilisearch, include thelocale field with the value 'all'.

module.exports={meilisearch:{config:{restaurant:{entriesQuery:{locale:'*',},},},},}

If you are using Strapi 4 with the🌍 Internationalization (i18n) plugin, thelocale field should be set toall.

If you want to add a collection with a relation to the collection being included, you have to configure thepopulate parameter inentriesQuery. Seethe docs on how it works, andan example in our resources.

Example

If you want your documents to be fetched in batches of1000 you specify it in theentriesQuery option.

module.exports={meilisearch:{config:{restaurant:{entriesQuery:{limit:1000,},},},},}

See resources for more entriesQuery examples.

🔐 Selectively index private fields

Private fields are sanitized by default to prevent data leaks. However, you might want to allow some of these private fields to be used forsearch,filter orsort. This is possible with thenoSanitizePrivateFields. For example, if you have a private field calledinternal_notes in your content-type schema that you wish to include in searching, you can add it to thenoSanitizePrivateFields array to allow it to be indexed.

// config/plugins.jsmodule.exports={meilisearch:{config:{restaurant:{noSanitizePrivateFields:['internal_notes'],// All attributes: ["*"]settings:{searchableAttributes:['internal_notes'],},},},},}

🕵️‍♀️ Start Searching

Once you have a content-type indexed in Meilisearch, you canstart searching.

To search in Meilisearch, you can use theinstant-meilisearch library that integrates a whole search interface, or ourmeilisearch-js SDK.

⚡️ Using Instant Meilisearch

You can have a front up and running in record time withinstant-meilisearch.

Restaurant demo

In Instant Meilisearch, you only have to provide your credentials and index name (uid).restaurant is the index name in our example.

You can have a quick preview with the following code in an HTML file. Create an HTML file, copy-paste the code below and open the file in your browser (or find it in/front_examples/restaurant.html).

<!doctype html><htmllang="en"><head><metacharset="utf-8"/><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css"/></head><body><divclass="wrapper"><divid="searchbox"focus></div><divid="hits"></div></div><scriptsrc="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script><scriptsrc="https://cdn.jsdelivr.net/npm/instantsearch.js@4"></script><script>constsearch=instantsearch({indexName:'restaurant',searchClient:instantMeiliSearch('http://localhost:7700','publicKey',// Use the public key not the private or master key to search.),})search.addWidgets([instantsearch.widgets.searchBox({container:'#searchbox',}),instantsearch.widgets.configure({hitsPerPage:8}),instantsearch.widgets.hits({container:'#hits',templates:{item:`                      <div>                      <div>                          {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}                      </div>                      </div>                  `,},}),])search.start()</script></body></html>

💛 Using Meilisearch for JS

You can also usemeilisearch-js to communicate with Meilisearch.

The following code is a setup that will output a restaurant after a search.

import{MeiliSearch}from'meilisearch';(async()=>{constclient=newMeiliSearch({host:'http://127.0.0.1:7700',apiKey:'publicKey',// Use the public key not the private or master key to search.})// An index is where the documents are stored.constresponse=client.index('movies').search('Biscoutte')})()

response content:

{"hits": [    {"id":3,"name":"Biscotte Restaurant","description":"Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.","categories": []    }  ],"offset":0,"limit":20,"nbHits":1,"exhaustiveNbHits":false,"processingTimeMs":1,"query":"biscoutte"}

💡 Run the Playground

Instead of adding the plugin to an existing project, you can try it out using the playground in this project.

# Root of repositoryyarn watch:link# Build the plugin and release it with yalc# Playground diryarn dlx yalc add --link strapi-plugin-meilisearch&& yarn install# Root of repositoryyarn playground:build# Build the playgroundyarn playground:dev# Start the development server

This command will install the required dependencies and launch the app in development mode. You should be able to reach it on theport 8000 of your localhost.

🤖 Compatibility with Meilisearch and Strapi

Supported Strapi versions:

Complete installation requirements are the same as for Strapi itself and can be found in the documentation underinstallation Requirements.

  • Strapi>=v5.x.x

If you are usingStrapi v3, please refer tothis README.

Supported Meilisearch versions:

This package guarantees compatibility withversion v1.x of Meilisearch, but some features may not be present. Please check theissues for more info.

Node:

  • NodeJS >= 18

We recommend always using the latest version of Strapi to start your new projects.

⚙️ Development Workflow and 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 ourcontributing guidelines for detailed instructions!

🌎 Community support

🤩 Just for the pleasure of the eyes

Using thefoodadvisor restaurant demo Strapi provided. We added a searchbar to it usinginstant-meilisearch.

Foodadvisor demo


[8]ページ先頭

©2009-2025 Movatter.jp