Last Updated: February 25, 2016
·
968
· tsturzl

Setting up an ElasticSearch End Point in your Express Project

Setting up ElasticSearch in your app can be a real pain. You gotta throw together some query builder, grab the results, push all the source documents to an array, figure out which fields need to be filtered and which need to be queried. By the end of it you have a boat made out of duct tape that barely stays a float.

With Express-Search you can just add water(not really... seriously don't...). With Express-Search you provide ElasticSearch and some basic configurations and you're smooth sailing. With features such as full-text search, phrase matching for quoted text, tag search via hash tags, and mention search via the mention tag(@). It allows you to provide a concise, single input search with rich features.

Setup

Set up is super simple. You just have to:

  • Provide connection settings for ElasticSearch.
  • Set Index and Type to search.
  • Configure pagination(default page size).
  • Configure Fields to search
    • Fields for general search
    • Fields for tag serach
    • Fields for mentions
  • Fields to return
  • Configure default sorting(optional)
    • Field to sort by
    • Sort order(ascending/descending)

Setup connection settings:

var expressSearch=require('express-search');
var express=require('express');

var app=express();

var config={
    'hosts':['localhost:9200']
    //'log':'trace' //handy for debugging
}

var search=expressSearch(configs);

Now you can use the expressSearch object to create multiple routes:

var mySearch={
   index: "myIndex",
   type: "someType",
    //fields for tag search
   tags: ['tags','twitter.tags'], 
   mentions: ['authors','editors'], //fields for mention search
   fields: ['title','description'], //fields for general search
   //fields to return in results
   projection: ['title','description','authors','editors','tags'], 
   pageSize: 10, //default page size
   sort: 'desc',
   sortBy: 'createDate'
};

app.use('/api/search/',search.setup(mySearch));

Now to use it:

curl http://localhost/api/search?q=music&page=10&sortBy=published_date&sort=desc

You can use the expressSearch object to setup as many search endpoints are you desire.