How to integrate Elasticsearch in Express
Le Quan Phat
Posted on October 26, 2024
1. Install Elasticsearch Client for Node.js
Start by installing the official Elasticsearch client for Node.js in your Express project. This will allow you to interact with Elasticsearch from within your Node application.
npm install @elastic/elasticsearch
2. Set up Elasticsearch on Docker
If you haven’t already set up an Elasticsearch instance, you can use Docker to run it locally.
Create or update your docker-compose.yaml file with the following configuration:
version: '3.7'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.10.0
container_name: elasticsearch
environment:
- discovery.type=single-node
- xpack.security.enabled=false
ports:
- "9200:9200"
Run the following command to start Elasticsearch:
docker-compose up -d
3. Initialize Elasticsearch Client in Your Express Application
Create an elasticsearchClient.js file in your project/config folder to initialize the Elasticsearch client:
const { Client } = require('@elastic/elasticsearch');
const client = new Client({
node: 'http://localhost:9200', // Replace with your Elasticsearch instance URL
});
module.exports = client;
4. Create an Elasticsearch Service
In your project/services directory, create a new file named elasticsearchService.js. This file will contain the logic for indexing, searching, updating, and deleting documents.
const client = require('../config/elasticsearchClient');
// Indexing a document
async function indexDocument(index, id, document) {
await client.index({
index,
id,
body: document,
});
}
// Searching for documents
async function searchDocuments(index, query) {
const { body } = await client.search({
index,
body: query,
});
return body.hits.hits;
}
module.exports = {
indexDocument,
searchDocuments,
};
5. Create a Route for Elasticsearch Operations
Now, create a new route in the project/routes folder (e.g., elasticsearchRoutes.js) to expose endpoints for performing Elasticsearch operations.
const express = require('express');
const router = express.Router();
const elasticsearchService = require('../services/elasticsearchService');
// Route to index a document
router.post('/index', async (req, res) => {
const { index, id, document } = req.body;
try {
await elasticsearchService.indexDocument(index, id, document);
res.status(200).send('Document indexed successfully');
} catch (error) {
res.status(500).send(error.toString());
}
});
// Route to search documents
router.get('/search', async (req, res) => {
const { index, query } = req.query;
try {
const results = await elasticsearchService.searchDocuments(index, JSON.parse(query));
res.status(200).json(results);
} catch (error) {
res.status(500).send(error.toString());
}
});
module.exports = router;
6. Add the Route to the Express App
In your project/app.js file, import and use the elasticsearchRoutes.
const express = require('express');
const elasticsearchRoutes = require('./routes/elasticsearchRoutes');
const app = express();
app.use(express.json());
// Other routes...
app.use('/elasticsearch', elasticsearchRoutes);
module.exports = app;
7. Start Your Express Server
node app.js
8. Test the Integration
You can test the endpoints using a tool like Postman or by making HTTP requests from the frontend.
- Index a document: Send a POST request to http://localhost:3000/elasticsearch/index with a JSON body:
{
"index": "your_index",
"id": "1",
"document": { "field": "value" }
}
- Search documents: Send a GET request to http://localhost:3000/elasticsearch/search with query parameters:
index=your_index&query={"query": {"match_all": {}}}
This setup allows your Express application to interact with Elasticsearch by indexing and searching for documents, while maintaining a modular structure. Let me know if you'd like to go deeper into any specific part of this integration!
Posted on October 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.