Search code examples
node.jselasticsearchelasticsearch-pluginmongoose-schemamongoose-populate

Conditional update with Elastic Search Client with mongoose static


I have a mongoose schema and when the save or update is called on this, in turns it updates the elastic search source as well. I have one issue when the status value is draft it should not update the elastic search. How it can be achieved by making the modification in following schema?

var TestShcema = new mongoose.Schema({
        custom_id:{
            type:String,
            required: true,
            index: {unique: true},
            es_indexed: true,
            es_index:"analyzed",
            es_index_analyzer:"autocomplete_analyzer"
        },
        title:{
            type:String,
            index: {unique: false},
            es_indexed: true,
            es_index:"analyzed",
            es_index_analyzer:"autocomplete_analyzer"
        },
        status:{
            type:String,
            index: {unique: false},
            es_indexed: true,
            es_index:"analyzed",
            es_index_analyzer:"autocomplete_analyzer"
        }
    });
    //Hook with Elastic Search
    var esClient = new elasticsearch.Client({host: config.elasticsearch.host});

    TestShcema.plugin(mongoosastic, {
        esClient: esClient
    });

    var Test = mongoose.model('Test', TestShcema);

    module.exports = Test;

Solution

  • you can use Filtered Indexing

    copy paste from npmjs

    You can specify a filter function to index a model to Elasticsearch based on some specific conditions.

    Filtering function must return True for conditions that will ignore indexing to Elasticsearch.

    var MovieSchema = new Schema({
      title: {type: String},
      genre: {type: String, enum: ['horror', 'action', 'adventure', 'other']}
    });
    
    MovieSchema.plugin(mongoosastic, {
      filter: function(doc) {
        return doc.genre === 'action';
      }
    });
    

    Instances of Movie model having 'action' as their genre will not be indexed to Elasticsearch.

    https://www.npmjs.com/package/mongoosastic#filtered-indexing

    you can do something like this

    TestShcema.plugin(mongoosastic, {
      filter: function(doc) {
        return doc.status === 'draft';
      }
    });