How to integrate Elasticsearch in Express

quanphat

Le Quan Phat

Posted on October 26, 2024

How to integrate Elasticsearch in Express

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Run the following command to start Elasticsearch:


docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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,
};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

7. Start Your Express Server

node app.js
Enter fullscreen mode Exit fullscreen mode

8. Test the Integration
You can test the endpoints using a tool like Postman or by making HTTP requests from the frontend.

{
  "index": "your_index",
  "id": "1",
  "document": { "field": "value" }
}
Enter fullscreen mode Exit fullscreen mode
index=your_index&query={"query": {"match_all": {}}}
Enter fullscreen mode Exit fullscreen mode

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!

💖 💪 🙅 🚩
quanphat
Le Quan Phat

Posted on October 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to integrate Elasticsearch in Express
elasticsearch How to integrate Elasticsearch in Express

October 26, 2024