From ecommerce platforms to Content Management Systems (CMSs), web apps generate and handle enormous amounts of data. Extracting relevant information from this data efficiently is crucial for a seamless user experience. So, traditional search functionality that uses literal, word-for-word query matching doesn’t suffice. You need a full-text search.

A full-text search examines the complete content of documents or databases, allowing you to retrieve relevant information from large datasets based on specific words or phrases. It accounts for factors like frequency of occurrence and multilingual content, yielding more accurate and comprehensive search results.

Meilisearch is a frontrunner in this class of search engines, harnessing the power of full-text search to offer a flexible and powerful tool built with developers and end users in mind.

This tutorial demonstrates how to integrate Meilisearch into a Node.js web project.

What Is Meilisearch?

Meilisearch is an open-source search engine that provides fast, relevant search results for end users. It’s typo-tolerant and works out of the box with default settings to accommodate most projects.

Meilisearch is also highly customizable, offering numerous features to tune the relevance of search results. Among these features, the most notable is ranking rules, which you can tailor to suit your project.

It offers an intuitive RESTful API for seamless integration into virtually any business website. You can host it yourself or use its official cloud-hosted solution, Meilisearch Cloud, to get started quickly and effortlessly. This tutorial uses Meilisearch Cloud.

Prerequisites

To follow along, you need:

How To Set Up Meilisearch

  1. Navigate to Meilisearch Cloud and either create an account or log in. Ensure you confirm your email address.
  2. Next, click Create a project, a server running a Meilisearch instance — where you’ll add your website’s datasets.
  3. Add a Project name (for example, book-app) and choose your preferred region. Then, click Create. After creating your project, you can click Settings to see details about your project, like the URL for accessing the datasets, API keys for protecting your Meilisearch instance, and other information.
    The book-app project overview page
    The book-app project overview page.

    There are three API keys, each representing a different authorization level:

    • Master key — This key unlocks all routes and is the only one with access to endpoints for creating and deleting API keys. Only use the master key to manage API keys from a protected environment.
    • Default Search API key — This key only grants access to the search route. You can use it in the client-side code.
    • Default Admin API key — This key accesses all API routes except /keys, which is for creating and deleting API keys. You can only use this key from a protected environment.

How To Index Data With Meilisearch

Indexes are the core components that store and organize searchable data. They act as containers for documents — objects containing one or more fields.

Each index in Meilisearch is independent and customizable, allowing for individualized search ranking rules and filtering options.

How To Create an Index and Add Documents

  1. In the navigation bar, click the Indexes tab in your project.
  2. Click Create an index. Next, enter an index name (for example, books) and click Create index.
  3. Select how you wish to import your documents. For this guide, import a JSON file, which includes 13 book entries from the Google Book API.
  4. Click File upload and upload the JSON file, then click Import documents.

How To Update and Delete Documents

Meilisearch Cloud currently doesn’t include a way to modify or delete documents, but you can use the REST API routes or SDK. The code below demonstrates how to update or delete documents using the REST API endpoints. This tutorial uses cURL to work with the routes, but you can also use an API platform like Postman.

  1. For updating documents, send a PUT request on the following route:
    /indexes/{index_uid}/documents

    The index_uid above is the index name of your project:

    Highlighted index name
    Highlighted index name.

  2. With this route, you can add or update a list of documents if they already exist. To update a document, you must attach its primary key. The old document undergoes a partial update based on the fields in the new document. The update preserves any fields not included in the new document, allowing them to remain unaltered.Below is an example of how to update the title of a document in the book’s index from JavaScript for Kids to JavaScript Coding for Kids and add a publisher field:
    curl \
        -X PUT '/indexes/books/documents' \
        -H 'Content-Type: application/json' \
        -H 'Authorization: Bearer ' \
            --data-binary '[
            {
                "id": "71nDBQAAQBAJ",
                "title": "JavaScript Coding for Kids",
                "publisher": "No Starch Press"
            }
        ]'
  3. Replace <your-project-url> and <your-admin-api-key> with the corresponding values in your Project overview page:
    "taskUid": 26, "indexUid": "books", "status": "enqueued", "type": "documentAdditionOrUpdate", "equeuedAt": "2023-05-26T07:52:24.127920065Z"
  4. For deleting documents, Meilisearch includes three routes (endpoints):
    /indexes/{index_uid}/documents // Deleting all documents
    /indexes/{index_uid}/documents/{document_id} // Deleting a single document
    /indexes/{index_uid}/documents/delete-batch // Deleting a selection of  
    documents

    You can get the document_id from the original data from the books.json file after fetching the document from MeiliSearch Cloud or your database.

Below is an example of how to delete the book you updated above:

curl \
    -H 'Authorization: Bearer ' \
    -X DELETE '/indexes/books/documents/71nDBQAAQBAJ'

After sending the request, your response should look like this:

"taskUid": 10, "indexUid": "books", "status": "enqueued", "type": "documentDeletion", "equeuedAt": "2023-05-26T07:20:11.1291066"

How To Add MeiliSearch to a Web Service

  1. Start by cloning the starter project from GitHub by running the following commands in your terminal:
    git clone https://github.com/Tammibriggs/meilisearch-app.git
    cd meilisearch​-app
    npm install

    If you check the package.json file, you should see the start command. Run npm start to run the Node.js project on localhost port3000. When you enter http://localhost:3000/ in your browser, should see the following:

    Meilisearch demo starter app
    Meilisearch demo starter app.

  2. Once the app is up and running, you can add Meilisearch to it so the search form begins returning the results from Meilisearch when submitted. To do this, install Meilisearch by executing the following command in the terminal:
    npm install meilisearch
  3. You also need to install the dotenv npm package to load sensitive credentials from a .env file. Run the following command in the terminal:
    npm install dotenv
  4. Create a .env file in the project root folder and add the following:
    YOUR_PROJECT_URL= '<your-project-url>'
    YOUR_SEARCH_API_KEY= '<your-admin-api-key>'

    Make sure to replace <your-project-url> and <your-admin-api-key> with their corresponding values.

  5. Next, import meilisearch and the dotenv package to the server.js file and configure dotenv:
    import {MeiliSearch} from 'meilisearch'
    import dotenv from 'dotenv';
    dotenv.config();
  6. Then, initialize Meilisearch so you can start working on your books-app project. Navigate to the server.js file and add the following code after the searchValue variable definition:
    const client = new MeiliSearch({ host: process.env.YOUR_PROJECT_URL, apiKey: process.env.YOUR_SEARCH_API_KEY })
  7. One important functionality is searching through your book index in Meilisearch using the search value attached to the URL when submitting the form. To enable this functionality, add the following code after the client variable definition:
    const index = client.index('books')  
    const searchResults = !!searchValue && await index.search(searchValue)

    This code creates a reference to the book’s index. Then, it uses the search() method to search for documents matching the search value in the book’s index if you define searchValue.

  8. Finally, to display the search results, modify the render() method as follows:
    res.render('index', {
        books: searchResults ? searchResults.hits : [],
        searchValue
    })

    You’re now ready to start searching through the book’s index:

    Searching through the 'books' index with the search form
    Searching through the ‘books’ index with the search form

  9. After adding the above codes, your server.js file should look like this:
    import express from 'express';
    import { MeiliSearch } from 'meilisearch';
    import dotenv from 'dotenv';
    dotenv.config();
    
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.set('view engine', 'ejs');
    app.use(express.static('public'));
    
    app.get('/', async (req, res) => {
    	const searchValue = req.query.search;
    	const client = new MeiliSearch({
    		host: process.env.YOUR_PROJECT_URL,
    		apiKey: process.env.YOUR_SEARCH_API_KEY,
    	});
    	const index = client.index('books');
    	const searchResults = !!searchValue && (await index.search(searchValue));
    
    	res.render('index', {
    		books: searchResults ? searchResults.hits : [],
    		searchValue,
    	});
    });
    
    app.listen(PORT, () => {
    	console.log(`listening at http://localhost:${PORT}`);
    });

You can access the complete code for this tutorial on GitHub.

Summary

Meilisearch is an excellent search engine solution that enhances a website’s search capabilities and user experience. Its exceptional speed, relevance-focused ranking algorithm, and seamless integration process make it an invaluable tool if you’re looking to optimize your website search functionality.

Kinsta’s Application Hosting service seamlessly elevates the performance of Meilisearch-powered apps. With robust infrastructure and streamlined server environments, Kinsta ensures rapid search functionality, enhancing user experience. The platform’s scalability accommodates Meilisearch’s demands, guaranteeing reliable and efficient search operations.

Which search engine do you rely on for your projects? Let us know in the comment section!

Jeremy Holcombe

Kinsta

Content & Marketing Editor at Kinsta, WordPress Web Developer, and Content Writer. Outside of all things WordPress, I enjoy the beach, golf, and movies. I also have tall people problems ;).