Node + MongoDB + Elasticsearch

mongodb
npm install -S mongoosastic
var BlogSchema = new mongooseSchema({
title: { type: String, es_indexed: true },
blog_text: { type: String, es_indexed: true },
author_name: { type: String, es_indexed: true },
sequence_num: Number,
category: { type: String, es_indexed: true },
created_at: { type: Date, default: Date.now },
modified_at: { type: Date, default: Date.now },
is_verified: { type: Boolean, es_indexed: true }
});
BlogSchema .plugin(mongoosastic);
var Blog = mongoose.model(‘Blog’, BlogSchema , ‘blogs’);
var stream = Blog.synchronize();
stream.on(‘error’, function (err) {
console.log(“Error while synchronizing” + err);
});
blog.save(function(err){
if (err) throw err;
/* Document indexation on going */
blog.on(‘es-indexed’, function(err, res){
if (err) throw err;
/* Document is indexed */
});
});
blog.remove(function(err) {
if (err) throw err;
/* Document unindexing in the background */
blog.on(‘es-removed’, function(err, res) {
if (err) throw err;
/* Document is unindexed */
});
});
Blog.createMapping({
“settings”: {
“analysis”: {
“analyzer”: {
“my_analyzer”: {
“type”: “custom”,
“tokenizer”: “classic”,
“char_filter”: [ “my_pattern” ],
“filter”: [“lowercase”]
}
},
“char_filter”: {
“my_pattern”: {
“type”: “pattern_replace”,
“pattern”: “\\.”,
“replacement”: “ “
}
}
}
},
“mappings”: {
“blog”: {
“dynamic_templates”: [{
“strings”: {
“match_mapping_type”: “string”,
“mapping”: {
“type”: “text”,
“fields”: {
“keyword”: {
“type”: “keyword”
}
}
}
}
}],
“properties”: {
“title”: {
“type”: “text”,
“analyzer”: “my_analyzer”
},
“category”: {
“type”: “keyword”
}
}
}
}
}, (err, mapping) => {
if (err) {
console.log(‘error creating mapping (you can safely ignore
this)’);
console.log(err);
} else {
console.log(‘mapping created!’);
console.log(mapping);
}
});
var collections = [‘blogs’];
var types = [‘blog’];
var fields = [“blog_text³”, “title”]
var filter = {
“is_verified”: true
};
var sort = “_score”;
Blog.search({
bool: {
must: [{
multi_match: {
query: searchString,
type: “phrase”,
fields: fields,
},
}],
should: [{
multi_match: {
query: searchString,
fields: fields,
operator: “and”,
boost: 10,
minimum_should_match: “100%”
},
}],
filter: [{
term: filter
}]
}
}, {
index: collections,
type: types,
from: from,
size: 10,
track_scores: true,
sort: sort
},
function (err, results) {
if (err) {
console.log(“Error in searchController: “, err);
} else {
res.json({result: results.hits.hits})
}
});

--

--

Delivering the difference through world-class software solutions and products.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store