@seedalpha/es-index-mongoose

Elastic search index for mongoose models

Usage no npm install needed!

<script type="module">
  import seedalphaEsIndexMongoose from 'https://cdn.skypack.dev/@seedalpha/es-index-mongoose';
</script>

README

es-index-mongoose

wercker status

Index mongoose models with ElasticSearch

Changelog

3.1.0:

  • allow custom mappings

3.0.0:

  • return whole resulting object from ES rather than just _source from there

2.3.2:

  • reduce number of connections for reindex

2.3.1:

  • fix unindex to only affect certain type

2.3.0:

  • parse stream from db to lower the connection stress to es

2.2.0:

  • add options with size and from to support search pagination

2.1.0:

  • add onIndex(doc, done) method to augment records before they are indexed by elastic-index

2.0.2:

  • use private registry

Prerequisites

$ npm set registry http://npm.sandbox.elasticseed.net
$ npm set always-auth true
$ npm login

Installation

$ npm install es-index-mongoose --save

Usage

# index.js

var esIndex   = require('es-index-mongoose');
var mongoose  = require('mongoose');

var user = new Schema({ 
  name: String, 
  company: { 
    type: mongoose.schema.types.ObjectId, 
    ref: 'Company' 
  } 
});

user.plugin(esIndex,  {
  url: 'http://localhost:9200',
  index: 'demo',
  type: 'users',
  mapping: {
    _id: { type: "string", index: "not_analyzed" },
    ...
  },
  onIndex: function(doc, done) {
    mongoose.model('Company').findById(doc.company, function(err, company) {
      if (err || !company) {
        console.log('Fail!');
        return done();
      }
      doc.company = company;
      done();
    });
  }
});

var User = mongoose.model('User', user);

User.create({ name: 'John' }, function(error, result) {

  var query = { filter: { term: { name: 'John' } } };

  User.search(query, function(results) {
    console.log(results); // [{...}]
  });
  // or
  // curl http://localhost:9200/demo/users/_search?name=John
  // { _id: "...", name: "John" }
});

User.unindex(function() { /* dropped user type from es index */ });

User.index(function(){ /* force reindex users collection from mongo to es, update mapping */});

User.findOne({ name: 'Denis' }, function(error, user) {
  if (error || !user) return console.log(error);
  user.index(function() {
    /* force reindexed user denis from mongo to es */
  });
});

Development (OS X)

$ git clone git@github.com:seedalpha/es-index-mongoose.git
$ cd es-index-mongoose
$ npm install
$ brew install mongodb
$ ES_URL=http://localhost:9200 npm test

Debug

$ DEBUG=es-index-mongoose npm test

Contributors

Vladimir Popov vlad@seedalpha.net
Denis Tsoi denis@seedalpha.net

License

©2014 Seedalpha