<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>codebase &#8211; Best DevOps</title>
	<atom:link href="https://www.bestdevops.com/tag/codebase/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.bestdevops.com</link>
	<description>Lets Learn, Do it &#38; Share! Thats a Best DevOps!!!</description>
	<lastBuildDate>Thu, 05 Feb 2026 05:35:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>
	<item>
		<title>Continuous Integration Tools Market Trends, Share, Industry Size, Growth and Forecast &#8211; 2026</title>
		<link>https://www.bestdevops.com/continuous-integration-tools-market-trends-share-industry-size-growth-and-forecast-2025/</link>
					<comments>https://www.bestdevops.com/continuous-integration-tools-market-trends-share-industry-size-growth-and-forecast-2025/#respond</comments>
		
		<dc:creator><![CDATA[anil]]></dc:creator>
		<pubDate>Wed, 28 Oct 2020 06:30:09 +0000</pubDate>
				<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[2025]]></category>
		<category><![CDATA[and price of Global Network Monitoring Software. Scope of the Report Product Type:]]></category>
		<category><![CDATA[codebase]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[Forecast]]></category>
		<category><![CDATA[Vertical]]></category>
		<guid isPermaLink="false">http://www.bestdevops.com/?p=14098</guid>

					<description><![CDATA[Source:-https://www.openpr.com CI (Continuous Integration) is the practice of frequently building and testing each change to the codebase. Continuous integration involves [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Source:-https://www.openpr.com</p>
<p>CI (Continuous Integration) is the practice of frequently building and testing each change to the codebase. Continuous integration involves developers uploading new code or code changes to a common code repository and then testing them automatically on upload to make sure the changes don&#8217;t cause problems or interruptions. By automating tests, users immediately verify that the code is sound and that critical software functions are working as expected. By integrating code into an integration source and testing code defects early in a project or sprint, development teams can save time and avoid delays in delivering new software, applications, and features.</p>
<p>Continuous integration (CI) tools market is expected to grow at a CAGR of 16% in the forecast period of 2019 to 2026.</p>
<p>Continuous Integration Tools Market &#8211; By Deployment Mode</p>
<p>• on Premises<br />
• Cloud</p>
<p>Continuous Integration Tools Market &#8211; By Organization</p>
<p>• Small &amp; Medium-Sized Enterprises<br />
• Large Enterprises</p>
<p>Continuous Integration Tools Market &#8211; By Vertical</p>
<p>• Retail &amp; Ecommerce<br />
• Telecommunication<br />
• Education<br />
• Media &amp; Entertainment<br />
• Healthcare<br />
• Manufacturing</p>
<p>Scope of the Report</p>
<p>The research study analyzes the global Continuous Integration Tools industry from 360-degree analysis of the market thoroughly delivering insights into the market for better business decisions, considering multiple aspects some of which are listed below as:</p>
<p>Recent Developments</p>
<p>o Market Overview and growth analysis<br />
o Import and Export Overview<br />
o Volume Analysis<br />
o Current Market Trends and Future Outlook<br />
o Market Opportunistic and Attractive Investment Segment</p>
<p>Geographic Coverage</p>
<p>o North America Market Size and/or Volume<br />
o Latin America Market Size and/or Volume<br />
o Europe Market Size and/or Volume<br />
o Asia-Pacific Market Size and/or Volume<br />
o Rest of the world Market Size and/or Volume</p>
<p>Key Questions Answered by Continuous Integration Tools Market Report</p>
<p>1. What was the Continuous Integration Tools Market size in 2018 and 2019; what are the estimated growth trends and market forecast (2019-2026).<br />
2. What will be the CAGR of Continuous Integration Tools Market during the forecast period (2019-2026)?<br />
3. Which segments (product type/applications/end-user) were most attractive for investments in 2018? How these segments are expected to grow during the forecast period (2019-2026).<br />
4. Which manufacturer/vendor/players in the Continuous Integration Tools Market was the market leader in 2018?<br />
5. Overview on the existing product portfolio, products in the pipeline, and strategic initiatives taken by key vendors in the market.</p>
<p>Orion Market Reports (OMR) endeavors to provide exclusive blend of qualitative and quantitative market research reports to clients across the globe. Our organization helps both multinational and domestic enterprises to bolster their business by providing in-depth market insights and most reliable future market trends. Our reports address all the major aspects of the markets providing insights and market outlook to global clients.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.bestdevops.com/continuous-integration-tools-market-trends-share-industry-size-growth-and-forecast-2025/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Full-text search with Node.js and ElasticSearch on Docker</title>
		<link>https://www.bestdevops.com/full-text-search-with-node-js-and-elasticsearch-on-docker/</link>
					<comments>https://www.bestdevops.com/full-text-search-with-node-js-and-elasticsearch-on-docker/#respond</comments>
		
		<dc:creator><![CDATA[anil]]></dc:creator>
		<pubDate>Mon, 16 Sep 2019 05:48:32 +0000</pubDate>
				<category><![CDATA[Docker]]></category>
		<category><![CDATA[Eleastic Search]]></category>
		<category><![CDATA[codebase]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Elasticsearch]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[server]]></category>
		<guid isPermaLink="false">http://www.bestdevops.com/?p=7747</guid>

					<description><![CDATA[Source:-blog.logrocket Full-text search can be both scary and exciting. Some popular databases such as&#160;MySql&#160;and&#160;Postgres&#160;are an amazing solution for storing data… [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Source:-blog.logrocket<br></p>



<p class="wp-block-paragraph">Full-text search can be both scary and exciting. Some popular databases such as&nbsp;<strong>MySql</strong>&nbsp;and&nbsp;<strong>Postgres</strong>&nbsp;are an amazing solution for storing data… but when it comes to full-text search performances, there’s no competition with&nbsp;<strong>ElasticSearch</strong>.</p>



<p class="wp-block-paragraph">For those who don’t know, ElasticSearch is a search engine server built on top of <strong>Lucene</strong> with an amazing distributed-architecture support. According to db-engines.com, it is currently the most used search engine out there.</p>



<p class="wp-block-paragraph">In this post, we are going to build a simple REST application called The Quotes Database which will allow us to store and search as many quotes as we want.</p>



<p class="wp-block-paragraph">I’ve prepared a JSON file containing 5000+ quotes with their authors, we’ll be using it as our starting data for populating ElasticSearch.</p>



<h2 class="wp-block-heading">Setting up Docker</h2>



<p class="wp-block-paragraph">First of all, we don’t want to install ElasticSearch on our machine. We’ll be using Docker for orchestrating both the Node.js server and the ES instance on a container, which will allow us to deploy a production-ready application with all the dependencies that it needs.</p>



<p class="wp-block-paragraph">Let’s create a&nbsp;<code>Dockerfile</code>&nbsp;inside our project root folder:</p>



<pre class="wp-block-preformatted">FROM node:10.15.3-alpine

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install
RUN npm install -g pm2

COPY . ./

EXPOSE 3000
EXPOSE 9200

CMD npm run start</pre>



<p class="wp-block-paragraph">As you can see, we’re telling Docker that we’ll run a&nbsp;<strong>Node.js 10.15.3-alpine</strong>&nbsp;runtime. We’ll also create a new working directory under&nbsp;<code>/usr/src/app</code>, where we’ll copy both the&nbsp;<code>package.json</code>&nbsp;and the&nbsp;<code>package-lock.json</code>&nbsp;files. That way, Docker will be able to run&nbsp;<code>npm install</code>&nbsp;inside our&nbsp;<code>WORKDIR</code>, installing our needed dependencies.</p>



<p class="wp-block-paragraph">We’ll also install <strong>PM2</strong> by running <code>RUN npm install -g pm2</code>. The Node.js runtime is single-threaded, so if a process crashes, the entire app needs to be restarted… <strong>PM2</strong> checks the Node.js process status and restarts it when the app goes down for any reason.</p>



<p class="wp-block-paragraph">After installing PM2, we’ll copy our codebase inside our&nbsp;<code>WORKDIR</code>&nbsp;(<code>COPY&nbsp;.&nbsp;./</code>), and we tell Docker to expose two ports,&nbsp;<code>3000</code>, which will expose our RESTful service, and&nbsp;<code>9200</code>, which exposes the ElasticSearch service (<code>EXPOSE&nbsp;3000</code>&nbsp;and&nbsp;<code>EXPOSE&nbsp;9200</code>).</p>



<p class="wp-block-paragraph">Last but not least, we tell Docker which command will start the Node.js app with&nbsp;<code>npm run start</code>.</p>



<h2 class="wp-block-heading">Setting up docker-compose</h2>



<p class="wp-block-paragraph">Now you may be saying, ‘<em>Great, I get it! But how do I handle the ElasticSearch instance inside Docker? I can’t find it in my Dockerfile!’</em>… you’re right! That’s where&nbsp;<strong>docker-compose</strong>&nbsp;becomes useful. It allows us to orchestrate multiple Docker containers and to create a connection between them. So, let’s write down the&nbsp;<code>docker-compose.yml</code>&nbsp;file, which will be stored inside our project root directory:</p>



<pre class="wp-block-preformatted">version: '3.6'
services:
  api:
    image: node:10.15.3-alpine
    container_name: tqd-node
    build: .
    ports:
      - 3000:3000
    environment:
     - NODE_ENV=local
     - ES_HOST=elasticsearch
     - NODE_PORT=3000
     - ELASTIC_URL=http://elasticsearch:9200
    volumes:
      - .:/usr/src/app/quotes
    command: npm run start
    links:
        - elasticsearch
    depends_on:
        - elasticsearch
    networks: 
      - esnet
  elasticsearch:
    container_name: tqd-elasticsearch
    image: docker.elastic.co/elasticsearch/elasticsearch:7.0.1
    volumes:
      - esdata:/usr/share/elasticsearch/data
    environment:
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - discovery.type=single-node
    logging:
      driver: none
    ports:
      - 9300:9300
      - 9200:9200
    networks: 
      - esnet
volumes:
  esdata:
networks:
  esnet:</pre>



<p class="wp-block-paragraph">This is a bit more complex than our Dockerfile, but let’s analyze it:</p>



<ul class="wp-block-list"><li>We declare which version of&nbsp;<code>docker-compose.yml</code>&nbsp;file we’re using (<code>3.6</code>)</li><li>We declare our services:<ul><li><code>api</code>, which is our Node.js app. Just like in our Dockerfile, it requires the&nbsp;<code>node:10.15.3-alpine</code>&nbsp;image. We also assign a name to this container&nbsp;<code>tqd-node</code>, and here we call the previously created Dockerfile using the&nbsp;<code>build&nbsp;.</code>&nbsp;command.</li><li>We need to expose the&nbsp;<code>3000</code>&nbsp;port so we write these statements as follows&nbsp;<code>3000:3000</code>. It means that we’re mapping&nbsp;<strong>from</strong>&nbsp;the port&nbsp;<code>3000</code>&nbsp;(inside our container)&nbsp;<strong>to</strong>&nbsp;the port&nbsp;<code>3000</code>&nbsp;(accessible from our machine). Then we’ll set some environment variables. The value&nbsp;<code>elasticsearch</code>&nbsp;is a variable which refers to the&nbsp;<code>elasticsearch</code>&nbsp;service inside our&nbsp;<code>docker-compose.yml</code>&nbsp;file.</li><li>We also want to mount a volume&nbsp;<code>/usr/src/app/quotes</code>. That way, once we restart our container we’ll maintain our data without losing it.</li><li>Once more, we tell Docker which command we need to execute once the container starts up, then we set a link to the&nbsp;<code>elasticsearch</code>&nbsp;service. We also tell Docker to start the&nbsp;<code>api</code>&nbsp;service after the&nbsp;<code>elasticsearch</code>&nbsp;service has booted (using the&nbsp;<code>depends_on</code>&nbsp;directive).</li><li>Last but not least, we tell Docker to connect the&nbsp;<code>api</code>&nbsp;service under the&nbsp;<code>esnet</code>&nbsp;network. That’s because every container has its own network. That way, we say that&nbsp;<code>api</code>&nbsp;and&nbsp;<code>elasticsearch</code>&nbsp;services shares the same network so they will be able to call each other with the same ports.</li><li><code>elasticsearch</code>, which is (as you may have guessed) our ES service. It’s configuration is pretty similar to the&nbsp;<code>api</code>&nbsp;service. We’ll just cut off its verbose logs setting the&nbsp;<code>logging</code>&nbsp;directive to&nbsp;<code>driver:&nbsp;none</code>&nbsp;.</li></ul></li><li>We also declare our volumes, where we store the ES data.</li><li>And we declare our network,&nbsp;<code>esnet</code>.</li></ul>



<h2 class="wp-block-heading">Bootstrapping the Node.js app</h2>



<p class="wp-block-paragraph">Now we need to create our Node.js application, so let’s get started setting up our&nbsp;<code>package.json</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">npm init -y</pre>



<p class="wp-block-paragraph">Now we need to install some dependencies:</p>



<pre class="wp-block-preformatted">npm i -s @elastic/elasticsearch body-parser cors dotenv express</pre>



<p class="wp-block-paragraph">Great! Our&nbsp;<code>package.json</code>&nbsp;file should look like this:</p>



<pre class="wp-block-preformatted">{
  "name": "nodejselastic",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@elastic/elasticsearch": "^7.3.0",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.1"
  }
}</pre>



<p class="wp-block-paragraph">Let’s implement our ElasticSearch connector in Node.js. First, we need to create a new&nbsp;<code>/src/elastic.js</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">const { Client } = require("@elastic/elasticsearch");
                   require("dotenv").config();

const elasticUrl = process.env.ELASTIC_URL || "http://localhost:9200";
const esclient   = new Client({ node: elasticUrl });
const index      = "quotes";
const type       = "quotes";</pre>



<p class="wp-block-paragraph">As you can see, here we set some constants that will be incredibly useful. First of all, we create a new connection to ElasticSearch using its official Node.js SDK, then we define an index (<code>"quotes"</code>) and an index type(<code>"quotes"</code> again, we’ll see later what they mean).</p>



<p class="wp-block-paragraph">Now we need to create an index on ElasticSearch. You can think of “indexes” as a SQL “database” equivalent. ElasticSearch is a NoSQL database, which means that it has no tables — it just stores JSON documents. An index is a logical namespace which maps to one or more primary shards and can have zero or more replica shards. You can read more about ElasticSearch indexes here.</p>



<p class="wp-block-paragraph">Let’s now define a function that will create our index:</p>



<pre class="wp-block-preformatted">async function createIndex(index) { 
  try {
    await esclient.indices.create({ index });
    console.log(`Created index ${index}`);
  } catch (err) {
    console.error(`An error occurred while creating the index ${index}:`);
    console.error(err);
  }
}</pre>



<p class="wp-block-paragraph">Now we need another function that creates the mapping for our quotes. The mapping defines the schema and types of our document:</p>



<pre class="wp-block-preformatted">async function setQuotesMapping () {
  try {
    const schema = {
      quote: {
        type: "text" 
      },
      author: {
        type: "text"
      }
    };

    await esclient.indices.putMapping({ 
      index, 
      type,
      include_type_name: true,
      body: { 
        properties: schema 
      } 
    })

    console.log("Quotes mapping created successfully");
  } catch (err) {
    console.error("An error occurred while setting the quotes mapping:");
    console.error(err);
  }
}</pre>



<p class="wp-block-paragraph">As you can see, we’re defining the schema for our documents, and we’re inserting it inside our&nbsp;<code>index</code>.</p>



<p class="wp-block-paragraph">Now let’s consider that ElasticSearch is a huge system and can take some seconds to boot up. We can’t connect to ES until it is ready, so we need a function that checks when the ES server is ready:</p>



<pre class="wp-block-preformatted">function checkConnection() {
  return new Promise(async (resolve) =&gt; {
    console.log("Checking connection to ElasticSearch...");
    let isConnected = false;
    while (!isConnected) {
      try {
        await esclient.cluster.health({});
        console.log("Successfully connected to ElasticSearch");
        isConnected = true;
      // eslint-disable-next-line no-empty
      } catch (_) {
      }
    }
    resolve(true);
  });
}</pre>



<p class="wp-block-paragraph">As you can see, we’re returning a promise. That’s because by using&nbsp;<code>async/await</code>&nbsp;we’re able to stop the entire Node.js process until this promise resolves, and it won’t do it until it connects to ES. That way, we force our Node.js to wait for ES before booting up.</p>



<p class="wp-block-paragraph">We’re done with ElasticSearch! Now let’s export our functions:</p>



<pre class="wp-block-preformatted">module.exports = {
  esclient,
  setQuotesMapping,
  checkConnection,
  createIndex,
  index,
  type
};</pre>



<p class="wp-block-paragraph">Great! Let’s see the entire&nbsp;<code>elastic.js</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">const { Client } = require("@elastic/elasticsearch");
                   require("dotenv").config();
const elasticUrl = process.env.ELASTIC_URL || "http://localhost:9200";
const esclient   = new Client({ node: elasticUrl });
const index      = "quotes";
const type       = "quotes";
/**
 * @function createIndex
 * @returns {void}
 * @description Creates an index in ElasticSearch.
 */
async function createIndex(index) {
  try {
    await esclient.indices.create({ index });
    console.log(`Created index ${index}`);
  } catch (err) {
    console.error(`An error occurred while creating the index ${index}:`);
    console.error(err);
  }
}
/**
 * @function setQuotesMapping,
 * @returns {void}
 * @description Sets the quotes mapping to the database.
 */
async function setQuotesMapping () {
  try {
    const schema = {
      quote: {
        type: "text" 
      },
      author: {
        type: "text"
      }
    };
  
    await esclient.indices.putMapping({ 
      index, 
      type,
      include_type_name: true,
      body: { 
        properties: schema 
      } 
    })
    
    console.log("Quotes mapping created successfully");
  
  } catch (err) {
    console.error("An error occurred while setting the quotes mapping:");
    console.error(err);
  }
}
/**
 * @function checkConnection
 * @returns {Promise&lt;Boolean&gt;}
 * @description Checks if the client is connected to ElasticSearch
 */
function checkConnection() {
  return new Promise(async (resolve) =&gt; {
    console.log("Checking connection to ElasticSearch...");
    let isConnected = false;
    while (!isConnected) {
      try {
        await esclient.cluster.health({});
        console.log("Successfully connected to ElasticSearch");
        isConnected = true;
      // eslint-disable-next-line no-empty
      } catch (_) {
      }
    }
    resolve(true);
  });
}
module.exports = {
  esclient,
  setQuotesMapping,
  checkConnection,
  createIndex,
  index,
  type
};</pre>



<h2 class="wp-block-heading">Populating ElasticSearch with quotes</h2>



<p class="wp-block-paragraph">Now we need to populate our ES instance with our quotes. This may sound easy, but believe me, it can be tricky.</p>



<p class="wp-block-paragraph">Let’s create a new file in&nbsp;<code>/src/data/index.js</code>:</p>



<pre class="wp-block-preformatted">const elastic = require("../elastic");
const quotes  = require("./quotes.json");

const esAction = {
  index: {
    _index: elastic.index,
    _type: elastic.type
  }
};</pre>



<p class="wp-block-paragraph">As you can see, we’re importing the&nbsp;<code>elastic</code>&nbsp;module we just created and our quotes from a JSON file stored in&nbsp;<code>/src/data/quotes.json</code>. We’re also creating an object called&nbsp;<code>esAction</code>, which will tell ES how to index a document once we insert it.</p>



<p class="wp-block-paragraph">Now we need a script to populate our database. We also need to create an array of Object with the following structure:</p>



<pre class="wp-block-preformatted">[
  {
    index: {
      _index: elastic.index,
      _type:  elastic.type
    }
  },
  {
    author: "quote author",
    quote:  "quote"
  },
  ...
]</pre>



<p class="wp-block-paragraph">As you can see, for each quote we’re gonna insert, we need to set its mapping to ElasticSearch. So that’s what we’ll do:</p>



<pre class="wp-block-preformatted">async function populateDatabase() {
  const docs = [];
  for (const quote of quotes) {
    docs.push(esAction);
    docs.push(quote);
  }
  return elastic.esclient.bulk({ body: docs });
}</pre>



<p class="wp-block-paragraph">Great! Now let’s create our main file in&nbsp;<code>/src/main.js</code>&nbsp;and see how we’ll structure everything we’ve written so far:</p>



<pre class="wp-block-preformatted">const elastic = require("./elastic");
const data    = require("./data");
                require("dotenv").config();

(async function main() {

  const isElasticReady = await elastic.checkConnection();
  if (isElasticReady) {
    const elasticIndex = await elastic.esclient.indices.exists({index: elastic.index});

    if (!elasticIndex.body) {
      await elastic.createIndex(elastic.index);
      await elastic.setQuotesMapping();
      await data.populateDatabase()
    }
  }

})();</pre>



<p class="wp-block-paragraph">Let’s analyze the code above. We create a self-executing main function which will check for the ES connection. The code execution won’t proceed until ES is connected. When ES is ready, we’ll check if the&nbsp;<code>quotes</code>&nbsp;index exists. If it doesn’t, we’ll create it, we’ll set its mapping and will populate the database. Obviously, we’ll do so only the first time we start up our server!</p>



<h2 class="wp-block-heading">Creating a RESTful API</h2>



<p class="wp-block-paragraph">Now we need to create our RESTful server. We’ll be using Express.js, which is the most popular Node.js framework out there for building servers.</p>



<p class="wp-block-paragraph">We’ll start with the&nbsp;<code>/src/server/index.js</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">const express      = require("express");
const cors         = require("cors");
const bodyParser   = require("body-parser");
const routes       = require("./routes");
                     require("dotenv").config();

const app  = express();
const port = process.env.NODE_PORT || 3000;

function start() {
  return  app.use(cors())
             .use(bodyParser.urlencoded({ extended: false }))
             .use(bodyParser.json())
             .use("/quotes",routes)
             .use((_req, res) =&gt; res.status(404).json({ success: false,error: "Route not found" }))
             .listen(port, () =&gt; console.log(`Server ready on port ${port}`));
}

module.exports = {
  start
};</pre>



<p class="wp-block-paragraph">As you can see, it is just a standard Express.js server, we won’t spend much time on that.</p>



<p class="wp-block-paragraph">Let’s see our&nbsp;<code>/src/server/routes/index.js</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">const express    = require("express");
const controller = require("../controllers");
const routes     = express.Router();

routes.route("/").get(controller.getQuotes);
routes.route("/new").post(controller.addQuote);

module.exports = routes;</pre>



<p class="wp-block-paragraph">We just create two endpoints:</p>



<ol class="wp-block-list"><li><code>GET&nbsp;/</code>, will return a list of quotes matching our query string parameters.</li><li><code>POST&nbsp;/new/</code>, will allow us to post a new quote storing it inside ElasticSearch.</li></ol>



<p class="wp-block-paragraph">So now let’s see our&nbsp;<code>/src/server/controllers/index.js</code>&nbsp;file:</p>



<pre class="wp-block-preformatted">const model = require("../models");

async function getQuotes(req, res) {
  const query  = req.query;
  if (!query.text) {
    res.status(422).json({
      error: true,
      data: "Missing required parameter: text"
    });
    return;
  }
  try {
    const result = await model.getQuotes(req.query);
    res.json({ success: true, data: result });
  } catch (err) {
    res.status(500).json({ success: false, error: "Unknown error."});
  }
}

async function addQuote(req, res) {
  const body = req.body;
  if (!body.quote || !body.author) {
    res.status(422).json({
      error: true,
      data: "Missing required parameter(s): 'body' or 'author'"
    });
    return;
  }
  try {
    const result = await model.insertNewQuote(body.quote, body.author);
    res.json({ 
      success: true, 
      data: {
        id:     result.body._id,
        author: body.author,
        quote:  body.quote
      } 
    });
  } catch (err) {
    res.status(500).json({ success: false, error: "Unknown error."});
  }
}
module.exports = {
  getQuotes,
  addQuote
};</pre>



<p class="wp-block-paragraph">Here we’re basically defining two functions:</p>



<ol class="wp-block-list"><li><code>getQuotes</code>, which requires at least one querystring parameter –&nbsp;<code>text</code></li><li><code>addQuote</code>, which require two parameters –&nbsp;<code>author</code>&nbsp;and&nbsp;<code>quote</code></li></ol>



<p class="wp-block-paragraph">The ElasticSearch interface is delegated to our&nbsp;<code>/src/server/models/index.js</code>. This structure helps us maintain a MVC-ish architecture.</p>



<p class="wp-block-paragraph">Let’s see our model:</p>



<pre class="wp-block-preformatted">const { esclient, index, type } = require("../../elastic");

async function getQuotes(req) {
  const query = {
    query: {
      match: {
        quote: {
          query: req.text,
          operator: "and",
          fuzziness: "auto"
        }
      }
    }
  }

  const { body: { hits } } = await esclient.search({
    from:  req.page  || 0,
    size:  req.limit || 100,
    index: index, 
    type:  type,
    body:  query
  });

  const results = hits.total.value;
  const values  = hits.hits.map((hit) =&gt; {
    return {
      id:     hit._id,
      quote:  hit._source.quote,
      author: hit._source.author,
      score:  hit._score
    }
  });

  return {
    results,
    values
  }
}</pre>



<p class="wp-block-paragraph">As you can see, we’re composing our ElasticSearch query by selecting every quote that includes a given word or phrase.</p>



<p class="wp-block-paragraph">Then, we spawn the query, setting both&nbsp;<code>page</code>&nbsp;and&nbsp;<code>limit</code>&nbsp;values we can pass them in a query string, for instance&nbsp;<code>http://localhost:3000/quotes?text=love&amp;page=1&amp;limit=100</code>. If these values are not passed via querystring, we’ll fall back to their default values.</p>



<p class="wp-block-paragraph">ElasticSearch returns an incredibly big amount of data, but we just need four things:</p>



<ol class="wp-block-list"><li>Quote ID</li><li>The quote itself</li><li>Quote author</li><li>Score</li></ol>



<p class="wp-block-paragraph">The score represents how close the quote is to our search term. Once we have these values, we return them with the total results number, which may be useful when paginating the results on the front end.</p>



<p class="wp-block-paragraph">Now we need to create the last function for our model&nbsp;<code>insertNewQuote</code>:</p>



<pre class="wp-block-preformatted">async function insertNewQuote(quote, author) {
  return esclient.index({
    index,
    type,
    body: {
      quote,
      author
    }
  })
}</pre>



<p class="wp-block-paragraph">This function is really simple, we just post the quote and the author to our index and return the query result back to the controller.</p>



<p class="wp-block-paragraph">Now the complete&nbsp;<code>/src/server/models/index.js</code>&nbsp;file should look like this:</p>



<pre class="wp-block-preformatted">const { esclient, index, type } = require("../../elastic");

async function getQuotes(req) {
  const query = {
    query: {
      match: {
        quote: {
          query: req.text,
          operator: "and",
          fuzziness: "auto"
        }
      }
    }
  }

  const { body: { hits } } = await esclient.search({
    from:  req.page  || 0,
    size:  req.limit || 100,
    index: index, 
    type:  type,
    body:  query
  });

  const results = hits.total.value;

  const values  = hits.hits.map((hit) =&gt; {
    return {
      id:     hit._id,
      quote:  hit._source.quote,
      author: hit._source.author,
      score:  hit._score
    }
  });

  return {
    results,
    values
  }
}

async function insertNewQuote(quote, author) {
  return esclient.index({
    index,
    type,
    body: {
      quote,
      author
    }
  })
}

module.exports = {
  getQuotes,
  insertNewQuote
}</pre>



<p class="wp-block-paragraph">And we’re done! We just need to setup our start script inside out&nbsp;<code>package.json</code>&nbsp;file and we’re ready to go:</p>



<pre class="wp-block-preformatted">"scripts": {
  "start": "pm2-runtime start ./src/main.js --name node_app",
  "stop": "pm2-runtime stop node_app "
}</pre>



<p class="wp-block-paragraph">We also need to update our&nbsp;<code>/src/main.js</code>&nbsp;script in order to start up our Express.js server once ElasticSearch has been connected:</p>



<pre class="wp-block-preformatted">const elastic = require("./elastic");
const server  = require("./server");
const data    = require("./data");
                require("dotenv").config();

(async function main() {
  const isElasticReady = await elastic.checkConnection();

  if (isElasticReady) {
    const elasticIndex = await elastic.esclient.indices.exists({index: elastic.index});

    if (!elasticIndex.body) {
      await elastic.createIndex(elastic.index);
      await elastic.setQuotesMapping();
      await data.populateDatabase()
    }

    server.start();
  }
})();</pre>



<h2 class="wp-block-heading">Launching the application</h2>



<p class="wp-block-paragraph">We’re now ready to start our application using&nbsp;<strong>docker-compose</strong>!</p>



<p class="wp-block-paragraph">Just run the following command:</p>



<pre class="wp-block-preformatted">docker-compose up</pre>



<p class="wp-block-paragraph">You’ll need to wait until Docker downloads both the ElasticSearch and Node.js images, then it will boot up your server and you’ll be ready to query against your REST endpoints!</p>



<p class="wp-block-paragraph">Let’s test with a couple of cURL calls:</p>



<pre class="wp-block-preformatted">curl localhost:3000/quotes?text=love&amp;limit=3

{
  "success": true,
  "data": {
    "results": 716,
    "values": [
      {
        "id": "JDE3kGwBuLHMiUvv1itT",
        "quote": "There is only one happiness in life, to love and be loved.",
        "author": "George Sand",
        "score": 6.7102118
      },
      {
        "id": "JjE3kGwBuLHMiUvv1itT",
        "quote": "Live through feeling and you will live through love. For feeling is the language of the soul, and feeling is truth.",
        "author": "Matt Zotti",
        "score": 6.2868223
      },
      {
        "id": "NTE3kGwBuLHMiUvv1iFO",
        "quote": "Genuine love should first be directed at oneself if we do not love ourselves, how can we love others?",
        "author": "Dalai Lama",
        "score": 5.236455
      }
    ]
  }
}</pre>



<p class="wp-block-paragraph">So as you can see, we decided to limit our results to&nbsp;<code>3</code>, but there are over 713 quotes!</p>



<p class="wp-block-paragraph">We can easily get the next three quotes by calling:</p>



<pre class="wp-block-preformatted">curl localhost:3000/quotes?text=love&amp;limit=3&amp;page=2

{
  "success": true,
  "data": {
    "results": 716,
    "values": [
      {
        "id": "SsyHkGwBrOFNsaVmePwE",
        "quote": "Forgiveness is choosing to love. It is the first skill of self-giving love.",
        "author": "Mohandas Gandhi",
        "score": 4.93597
      },
      {
        "id": "rDE3kGwBuLHMiUvv1idS",
        "quote": "Neither a lofty degree of intelligence nor imagination nor both together go to the making of genius. Love, love, love, that is the soul of genius.",
        "author": "Wolfgang Amadeus Mozart",
        "score": 4.7821507
      },
      {
        "id": "TjE3kGwBuLHMiUvv1h9K",
        "quote": "Speak low, if you speak love.",
        "author": "William Shakespeare",
        "score": 4.6697206
      }
    ]
  }
}</pre>



<p class="wp-block-paragraph">And what if you need to insert a new quote? Just call the&nbsp;<code>/quotes/new</code>&nbsp;endpoint!</p>



<pre class="wp-block-preformatted">curl --request POST \
     --url http://localhost:3000/quotes/new \
     --header 'content-type: application/json' \
     --data '{
        "author": "Michele Riva",
        "quote": "Using Docker and ElasticSearch is challenging, but totally worth it."
}'</pre>



<p class="wp-block-paragraph">and the response will be:</p>



<pre class="wp-block-preformatted">{
  "success": true,
  "data": {
    "id": "is2QkGwBrOFNsaVmFAi8",
    "author": "Michele Riva",
    "quote": "Using Docker and ElasticSearch is challenging, but totally worth it."
  }
}</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Docker makes it incredibly easy to manage our dependencies and their deployment. From that point, we could host our application on Heroku, AWS ECS, Google Cloud Container or any other Docker-based service with ease, without struggling to setup our server with their super-complex configurations.</p>



<p class="wp-block-paragraph">Next steps?</p>



<ul class="wp-block-list"><li>Learn how to use Kubernetes in order to scale your container and orchestrate more ElasticSearch Instances!</li><li>Create a new endpoint that will allow you to update an existing quote. Mistakes can happen!</li><li>And what about deleting a quote? How would you implement that endpoint?</li><li>It would be great to save your quotes with tags (for instances, quotes about love, health, art)… try to update your <code>quotes</code> index!</li></ul>



<p class="wp-block-paragraph">Software development is fun. With Docker, Node, and ElasticSearch it’s even better!</p>



<h2 class="wp-block-heading">Plug: LogRocket, a DVR for web apps</h2>



<figure class="wp-block-image"><a href="https://logrocket.com/signup/" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&amp;ssl=1" alt="LogRocket Dashboard Free Trial Banner" class="wp-image-46"/></a></figure>



<p class="wp-block-paragraph">LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.</p>



<p class="wp-block-paragraph">In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.bestdevops.com/full-text-search-with-node-js-and-elasticsearch-on-docker/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
