Utilize the power of Meilisearch to Power your Web-based App (r)
-sidebar-toc>
From ecommerce platforms to Content Management Systems (CMSs) Web apps create and handle enormous amounts of data. Making sense of the information efficiently is essential to ensure a smooth user experience. So, traditional search functionality which relies on literal word-for-word query matching isn't sufficient. It is necessary to use a full-text search.
A full-text search analyzes all the content in documents or databases. It allows you to retrieve relevant information from large datasets based on particular words or phrases. It accounts for factors like the frequency of usage and the multilingual content. This results in more accurate and comprehensive search results.
Meilisearch is the leader within this category of search engines, harnessing the power of full-text search to give users an adaptable and effective device designed by designers and consumers in mind.
This video tutorial shows how you can incorporate Meilisearch in the Node.js web application.
What is Meilisearch?
Meilisearch also has a wide range of customization options with a wide range of options to tune the relevance of the results. Among these features, the most prominent is the ranking rule, which you can tailor to suit your project.
The prerequisites
To follow along to follow along, you'll need:
- A Node.js project. You can use this project as a starter from GitHub.
How To Set Up Meilisearch
- Go to Meilisearch Cloud and either create an account or log in. Ensure you confirm your email address.
- Then, then click to create a project or server -- a server operating an instance of Meilisearch -- in which you'll include your website's data.
- Add a Name of project (for example, book-app) or book-app) and select your preferred region. Then, click Create . After creating your project, you can click Settings for more information about your project, like your URL to access the databases, API keys for protecting your Meilisearch server, as well as additional details.
Three API keys are available, each one representing the distinct authorization level:
- Master Key The master key unlocks all routes and is the only one with access to the endpoints that allow for generating and deleting API keys. Only use the master key to control API keys in a secure environment.
- The default Search API key -- This key only grants access to the search route. It can be used on the client side code.
- Key for the default Admin API The key allows access to every API route, except
/keys
that is used to create and delete API keys. This key can only be used key in a secure setting.
How to Index Data Using Meilisearch
Indexes are the primary elements that organize and store searchable data. They act as containers for documents- objects containing one or more fields.
Every index on Meilisearch is independent and customizable which allows you to create your own filters and rules for ranking. choices.
How Do I Make an Index and add Documents
- Within the navigation bar Click on the Indexestab in your project.
- Click Make An Index. Next, enter an index name (for an example, books) and click Create index.
- Decide how you would like to import your documents. This guide will help you upload a JSON file. It contains 13 entries for books from Google Book API. Google Book API.
- Click the File Upload button and then upload the JSON file, then click Import documents.
How To Update and Delete Documents
Meilisearch Cloud currently doesn't include the ability to edit or delete documents, but you could use the REST API route or the SDK. This code demonstrates how to update or delete documents by using documents using the REST API endpoints. This tutorial uses cURL to work with the routes, but you can utilize an API platform such as Postman.
- For updating documents , send a
PUT
The following routes are available for your request:
/indexes/index_uid/documents
Index_uid above is the index name of your project. index_uid
above is the index name of your project:
- With this route, you can add or edit a collection of documents even if they do not exist. In order to update documents that you want to update, attach its primary key. Documents that are older undergo an incomplete update that is based on the information contained in the latest document. The updated document preserves fields that were not part of the new document, allowing these fields to remain unaltered.Below are some examples of ways you can update the name of a document within the index of the book. JavaScript for kids up 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"
]'
- Replace
"taskUid": 26, "indexUid": "books", "status": "enqueued", "type": "documentAdditionOrUpdate", "equeuedAt": "2023-05-26T07:52:24.127920065Z"
- 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 document_id and document_id
by examining the data from books.json. books.json file after downloading the document via MeiliSearch Cloud or your database.
Below is an example of how you can delete the updated book:
curl \
-H 'Authorization: Bearer ' \
-X DELETE '/indexes/books/documents/71nDBQAAQBAJ'
After sending the inquiry, your reply will look something like:
"taskUid": 10, "indexUid": "books", "status": "enqueued", "type": "documentDeletion", "equeuedAt": "2023-05-26T07:20:11.1291066"
How to Add MeiliSearch to an existing Web Service
- Create a clone of the project that you started from GitHub with the following commands in your terminal
git clone https://github.com/Tammibriggs/meilisearch-app.git
cd meilisearch -app
npm install
If you go to your package.json file, there should be a start command. Use NPM start
to launch the Node.js project locally on port 3000 of localhost. When you enter http://localhost:3000/ in your browser, should see the following:
- After the application is installed and operational, you'll be able to add Meilisearch to it so the search form will start with the search results returned by Meilisearch after you submit it. In order to do this, install Meilisearch by executing the following command in the terminal:
NPM install meilisearch
- You also need to install the dotenv NPM package that loads sensitive credentials from a .env file. Enter the following command into the terminal window:
npm install dotenv
- Make a .env file in the project root folder and add the following:
YOUR_PROJECT_URL= ''
YOUR_SEARCH_API_KEY= ''
It is important to change your-project-url
and your-admin-api-key>
with the values that correspond to them.
- Then, import
meilisearch
and thedotenv
The package will be delivered to server.js file and configureDotenv
:
import MeiliSearch from 'meilisearch dotenv', import it from 'dotenv';dotenv.config();
- Once you have done that, start Meilisearch and you are able to start working on your books-app project. Click on the server.js in the file, and include 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 )
- A key feature is the ability to search through your library's book index on Meilisearch with the search parameter that is included in the URL while filling out the form. In order to enable this feature you must add the code below after the
Customer
variable definition:
const index = client.index('books')
const searchResults = ! !searchValue && await index.search(searchValue)
The code generates a reference to the index in the book. Then, it uses the "search"()
method to find documents that correspond to the search value in the book's index when you specify searchValue
.
- For the final step, in order to show the search results, modify the
render()
method according to:
res.render('index',
books: searchResults ? searchResults.hits [],
searchValue)
You're now ready to start looking through the index of the book:
- When you've added these codes after which you can use after that, server.js Files should be as follows:
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`);
);
It is possible to access the full code for this tutorial via GitHub.
Summary
Meilisearch is an excellent alternative to a search engine that improves the capabilities of a site's search engine and user experience. Its speedy performance, relevant-focused ranking algorithm, and seamless integration make it an invaluable tool when you're trying to improve your search capabilities on your website.
Which one do you rely on to complete your work? Tell us in the comments section!
Jeremy Holcombe
Content & Marketing Editor at , WordPress Web Developer, and Content writer. Apart from everything related to WordPress I like playing golf, at the beach, and movies. Also, I have height problems ;).