Logo

dev-resources.site

for different kinds of informations.

How to integrate Elasticsearch in Express

Published at
10/26/2024
Categories
elasticsearch
express
docker
node
Author
quanphat
Categories
4 categories in total
elasticsearch
open
express
open
docker
open
node
open
Author
8 person written this
quanphat
open
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!

elasticsearch Article's
30 articles in total
Favicon
Intelligent PDF Data Extraction and database creation
Favicon
Debugging Elasticsearch Cluster Issues: Insights from the Field
Favicon
Search Engine Optimisation
Favicon
Advantages of search databases
Favicon
Advanced Search in .NET with Elasticsearch(Full Video)
Favicon
Real-Time Data Indexing: Powering Instant Insights and Scalable Querying
Favicon
Coding challenge: Design and Implement an Advanced Text Search System
Favicon
tuistash: A Terminal User Interface for Logstash
Favicon
Navigating Search Solutions: A Comprehensive Comparison Guide to Meilisearch, Algolia, and ElasticSearch
Favicon
Elastic Cloud on Kubernetes (ECK) with custom domain name
Favicon
Step-by-Step Guide to Configuring Cribl and Grafana for Data Processing
Favicon
Exploring Logging Best Practices
Favicon
Building a Smart Log Pipeline: Syslog Parsing, Data Enrichment, and Analytics with Logstash, Elasticsearch, and Ruby
Favicon
How to connect to AWS OpenSearch or Elasticsearch clusters using python
Favicon
Elasticsearch Was Great, But Vector Databases Are the Future
Favicon
Building Real-Time Data Pipelines with Debezium and Kafka: A Practical Guide
Favicon
AI + Search + Real Time Data = ๐Ÿ”ฅ (๐’ฎ๐‘’๐’ถ๐“‡๐’ธ๐’ฝ ๐“Œ๐’พ๐“๐“ ๐’ท๐‘’ ๐“‰๐’ฝ๐‘’ ๐’ป๐“Š๐“‰๐“Š๐“‡๐‘’ ๐‘œ๐’ป ๐’œ๐ผ)
Favicon
Size Doesn't Matter: Why Your Elasticsearch Fields Need to Stop Caring About Length
Favicon
ELK Stack Mastery: Building a Scalable Log Management System
Favicon
Elastop: An HTOP Inspired Elasticsearch Monitoring Tool
Favicon
Hybrid Search with Elasticsearch in .NET
Favicon
Proximity Search: A Complete Guide for Developers
Favicon
How I can run elasticsearch locally for development using docker?
Favicon
Improving search experience using Elasticsearch
Favicon
How to integrate Elasticsearch in Express
Favicon
Advanced Techniques for Search Indexing with Go: Implementing Full-Text Search for Product Catalogs
Favicon
Semantic Search with Elasticsearch in .NET
Favicon
15 WordPress Search Plugins to Supercharge Your Websiteโ€™s Search Functionality
Favicon
Building a Web Search Engine in Go with Elasticsearch
Favicon
github action services: mysql, redis and elasticsearch

Featured ones: