Building an e-Commerce website with Node – Part 35 – Installing ElasticSearch in Node.js

Elasticsearch is an open source search engine that will give your web aplication search capabilities. In order to install it on a Linux machine you must install Java first. There are tutorials on the Internet on how to install Elasticsearch so I won’t go into details here. If you are on a Mac then you can install Xcode (which comes with Ruby) and Homebrew.

You also need Mongoosastic which is a library that uses elasticsearch to replicate the data from MongoDB to elasticsearch. You can easily install Mongo0sastic via terminal.

This way you can search any productic by typing Product.search. How convenient!

Open product.js which is under models folder and type the following code.

var mongoosastic = require('mongoosastic');

This requires the mongoosastic library.

And

ProductSchema.plugin(mongoosastic, {
  hosts: [
    'localhost:9200'
  ]
});

The 'localhost:9200' is the default when setting up elasticsearch.

Next, in the main.js file under the routes folder we have to add the following code.

Product.createMapping(function(err, mapping) {
  if (err) {
    console.log("error creating mapping");
    console.log(err);
  } else {
    console.log("Mapping created");
    console.log(mapping);
  }
});

This code creates a connection between product database and elastic search, so they can communicate. By using createMapping you basically create a map of the product database so elasticsearch can use it.

Next, we want to synchronize the whole data to the elasticsearch. For that we have to add the following code to our main.js file.

var stream = Product.synchronize();
var count = 0;

stream.on('data', function() {
  count++;
});

stream.on('close', function() {
  console.log("Indexed " + count + " documents");
});

stream.on('error', function(err) {
  console.log(err);
});

First paragraph of code syncronizes the product database to the elesticsearch.
The second paragraph of code counts the documents.
The third will display how many documents were indexed.
The last part will display an error if there is one.

Now, in order to test everything we have done we need to open two terminal windows, one for the Node.js server and one for the Elasticsearch server.

Elasticsearch

As you can see, mapping was created and the last message “Indexed 60 documents” shows that elasticsearch does what is supposed to do. Why 60? Because I have two categories, books and gadgets, and Faker makes 30 products for each category.

Leave a Reply