Strapi plugin logo for Elasticsearch

Elasticsearch

Integrate Elasticsearch to your Strapi setup

thumbnail for Elasticsearch

Strapi plugin strapi-plugin-elasticsearch

A plugin to enable integrating Elasticsearch with Strapi CMS.

Installation

via npm:

1npm i @geeky-biz/strapi-plugin-elasticsearch

via yarn:

1yarn add @geeky-biz/strapi-plugin-elasticsearch

Plugin Configuration

Within your Strapi project's config/plugin.js, enable the plugin and provide the configuration details:

1module.exports = {
2    // ...
3    'elasticsearch': {
4      enabled: true,
5      config: {
6        indexingCronSchedule: "<cron schedule>",
7        searchConnector: {
8          host: "<hostname for Elasticsearch>",
9          username: "<username for Elasticsearch>",
10          password: "<password for Elasticsearch>",
11          certificate: "<path to the certificate required to connect to Elasticsearch>"
12        },
13        indexAliasName: "<Alias name for the Elasticsearch index>"
14      }  
15    },
16    // ...
17  }

Example plugin configuration (with adequate .env variables set up):

1module.exports = {
2    // ...
3    'elasticsearch': {
4      enabled: true,
5      config: {
6        indexingCronSchedule: "00 23 * * *", //run daily at 11:00 PM
7        searchConnector: {
8          host: process.env.ELASTIC_HOST,
9          username: process.env.ELASTIC_USERNAME,
10          password: process.env.ELASTIC_PASSWORD,
11          certificate: path.join(__dirname, process.env.ELASTIC_CERT_NAME)
12        },
13        indexAliasName: process.env.ELASTIC_ALIAS_NAME
14      }  
15    },
16    // ...
17  }

Ensuring connection to Elasticsearch

When connected to Elasticsearch, the Connected field within the Setup Information screen shall display true.

image

Configuring collections & attributes to be indexed

The Configure Collections view displays the collections and the fields setup to be indexed.

image

From this view, individual collection can be selected to modify configuration:

image

Configuring indexing for dynamic zone or component attributes

To enable indexing content for attributes of type component or dynamiczone, additional information needs to be provided via JSON in the following format:

1{
2  "subfields": [
3        {
4          "component": "<component name within schema.json>",
5          "field": "<field name from within that component>"
6        },
7        {...},
8        {...}
9      ]
10}

Example 1:

If we have an attribute called seo_details of type component like the following within our collection schema.json:

1    "seo_details": {
2      "type": "component",
3      "repeatable": false,
4      "component": "metainfo.seo"
5    },

And, if we seek to index the contents of the meta_description field belonging to the component seo, our subfields configuration should be:

1{
2  "subfields": [
3        {
4          "component": "metainfo.seo",
5          "field": "meta_description"
6        }
7      ]
8}

image

Example 2:

If we have an attribute called sections of type dynamiczone within our collection schema.json:

1    "sections": {
2      "type": "dynamiczone",
3      "components": [
4        "content.footer",
5        "content.paragraph",
6        "content.separator",
7        "content.heading"
8      ]
9    },
10...

And, if we seek to index the contents of the fields title for content.heading and details as well as subtext for content.paragraph, our subfields configuration should be:

1{
2  "subfields": [
3        {
4          "component": "content.paragraph",
5          "field": "details"
6        },
7        {
8          "component": "content.paragraph",
9          "field": "subtext"
10        },
11        {
12          "component": "content.heading",
13          "field": "title"
14        }
15      ]
16}

The subfields JSON also supports multiple level of nesting:

1{
2  "subfields": [
3        {
4          "component": "content.footer",
5          "field": "footer_link",
6          "subfields": [
7            {
8              "component": "content.link",
9              "field": "display_text"
10            }
11          ]
12        }
13      ]
14}

Note: Indexing of relations attributes isn't yet supported.

Exporting and Importing indexing configuration

To enable backing up the indexing configuration or transferring it between various environments, these can be Exported / Imported from the Configure Collections view.

image

Scheduling Indexing

Once the collection attributes are configured for indexing, any changes to the respective collections & attributes is marked for indexing. The cron job (configured via indexingCronSchedule) makes actual indexing requests to the connected Elasticsearch instance.

  • Trigger Indexing triggers the cron job immediately to perform the pending indexing tasks without waiting for the next scheduled run.
  • Rebuild Indexing completely rebuilds the index. It may be used if the Elasticsearch appears to be out of sync from the data within Strapi.

image

Whenever a collection is configured for indexing, it may already have data that needs to be indexed. To facilitate indexing of the past data, a collection can be scheduled for indexing in the next cron run from the Configure Collections view:

image

Searching

You may directly use the Elasticsearch search API or you may use the Search API exposed by the plugin (at /api/elasticsearch/search). The plugin search API is just a wrapper around the Elasticsearch search API that passes the query parameter to the Elasticsearch search API and returns the results coming from Elasticsearch:

For example, the below API call would result into the Elasticsearch search API being triggered with the query

1`/api/elasticsearch/search?query=query%5Bbool%5D%5Bshould%5D%5B0%5D%5Bmatch%5D%5Bcity%5D=atlanta`

would result into the Elasticsearch search API being triggered with query

1query[bool][should][0][match][city]=atlanta

The plugin's API would return the response from the Elasticsearch search API.

Note: To use the search API (at /api/elasticsearch/search), you will have to provide access via Settings -> Users & Permissions Plugin -> Roles -> (Select adequate role) -> Elasticsearch -> search.

Extending Search API

The recommended was to enhance the Search API is to write your own route and controller. Below is an example of how this can be achieved (this example adds pagination capability to the search API):

  • Within your setup, create src/extensions/elasticsearch/strapi-server.js with the following contents:
1const { Client } = require('@elastic/elasticsearch')
2const qs = require('qs');
3
4let client = null;
5
6module.exports = (plugin) => {
7
8    client = new Client({
9        node: plugin.config.searchConnector.host,
10        auth: {
11          username: plugin.config.searchConnector.username,
12          password: plugin.config.searchConnector.password
13        },
14        tls: {
15          ca: plugin.config.searchConnector.certificate,
16          rejectUnauthorized: false
17        }
18    });
19
20    plugin.controllers['performSearch'].enhancedSearch = async (ctx) => {
21            try
22            {
23                const params = qs.parse(ctx.request.query)
24                const query = params.search;
25                const pagesize = params.pagesize;
26                const from = params.from;
27                const result= await client.search({
28                    index: plugin.config.indexAliasName,
29                    query: { "bool" : { "should" : [ { "match": { "content": "dummy"} } ] } },
30                    size: pagesize,
31                    from: from 
32                });
33                return result;
34            }
35            catch(err)
36            {
37                console.log('Search : elasticClient.enhancedSearch : Error encountered while making a search request to ElasticSearch.')
38                throw err;
39            }
40    }
41
42    plugin.routes['search'].routes.push({
43        method: 'GET',
44        path: '/enhanced-search',
45        handler: 'performSearch.enhancedSearch',
46      });
47  
48    
49    return plugin;
50};
  • This will create a new route /api/elasticsearch/enhanced-search being served by the function defined above.
  • You can add / modify the routes and controllers as necessary.

Bugs

For any bugs, please create an issue here.

About

  • This plugin is created by Punit Sethi.
  • I'm an independent developer working on Strapi migrations, customizations, configuration projects (see here).
  • For any Strapi implementation requirement, write to me at punit@tezify.com.

Install now

npm install @geeky-biz/strapi-plugin-elasticsearch

STATS

9 GitHub stars46 weekly downloads

Last updated

408 days ago

Strapi Version

4.0.0 and above

Author

github profile image for Punit Sethi
Punit Sethi

Useful links

Create your own plugin

Check out the available plugin resources that will help you to develop your plugin or provider and get it listed on the marketplace.