0.1.1 • Published 11 years ago
mongoose-elasticsearch v0.1.1
MongooseElasticSearch
Binds a mongoose model to an elasticsearch.
I wanted a promise based library based on the official elasticsearch node client. There are other great alternatives such as mongooseElasticsearch, mongoosastic but they didn't fit my needs as I needed more flexiblity around setting the schema to use parent associations and complex analyzers.
Changes!!!
syntax change when defining plugins
AnimalSchema.plugin mongooseElasticsearch.plugin(), {type: 'animal', mapping: elasticMapping}Features
- Optional automatic saving to elasticsearch
 - Optional automatic deletion from elasticsearch
 - Bulk indexing of a model to ES
 - Use a preconfigured elasticsearch client
 - Manually define elasticsearch mapping
 - Optional custom object to save (which can be a promise to populate fields)
 
Usage
Setup model
./animal.coffee
  mongoose = require("mongoose")
  MongooseElasticSearch = require("mongoose-elasticsearch")
  
  # Generic setup
  elasticsearch = require("elasticsearch") 
  # can put the elasticClient creation in an initializer
  elasticClient = new elasticsearch.Client
    host: "localhost:9200"
    maxSockets: 2
    sniffOnStart: true
    sniffInterval: 60000
    defer: () -> Q.defer()
  # Can put the mongooseElasticsearch creation in an initializer
  mongooseElasticsearch = new MongooseElasticSearch
    index: 'animals'
    client: elasticClient
  # Exact elasticsearch mapping required for the object
  elasticmapping =
    properties:
      name:
        type: "string"
      description:
        type: "string"
        analyzer: "english"
      createdAt:
        type: "date"
  # Define mongoose schema
  AnimalSchema = new mongoose.Schema
    name:
      type: String
    description:
      type: String
    createdAt:
      type: Date
  # Add the plugin giving the type and 
  AnimalSchema.plugin mongooseElasticsearch.plugin(),
    type: 'animal' 
    mapping: elasticMapping
  model = mongoose.model "Animal", AnimalSchemaUse model
./test.coffee
  Animal = require("./animal")
  animal = new Animal(name: 'Cheater', description: "Freakin fast cat", createdAt: new Date())
  animal.save().then (animal) ->
    # Standard elasticsearch query
    query = 
      matchAll: {}
    Animal.search(query).then (res) ->
      console.log 'res', res### Maintenance and migrations
./tasks.coffee
  elastic