简体   繁体   中英

How to delete multiple id documents in elasticsearch index

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: 'ABC',
    log: 'trace',
    apiVersion: '7.1'
});
client.delete({
        index: 'allevents',
        type: '_doc',
        id:"2"
    }).then(function(resp) {
        console.log("Successful query!");
        console.log(JSON.stringify(resp, null, 4));
    }, function(err) {
        console.trace(err.message);
    });

When I delete a single document by passing single id value.its working fine.

But I want to delete multiple documents in a single query . How will we do?

I tried

 client.delete({
    index: 'allevents',
    type: '_doc',
    id: ["2","3"]
})

This function returning error.

I suggest to leverage the bulk method / API , like this:

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: 'ABC',
    log: 'trace',
    apiVersion: '7.1'
});

var idsToDelete = ["2", "3"];
var bulk = idsToDelete.map(id => {
  return {
     'delete': {
        '_index': 'allevents',
        '_type': '_doc',
        '_id': id
     }
  };
});

client.bulk({
      body: bulk
    }).then(function(resp) {
        console.log("Successful query!");
        console.log(JSON.stringify(resp, null, 4));
    }, function(err) {
        console.trace(err.message);
    });

Another way of doing it is to leverage the deleteByQuery method / API :

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: 'ABC',
    log: 'trace',
    apiVersion: '7.1'
});

var idsToDelete = ["2", "3"];

client.deleteByQuery({
      index: 'allevents',
      type: '_doc',
      body: {
        query: {
          terms: {
            _id: idsToDelete
          }
        }
      }
    }).then(function(resp) {
        console.log("Successful query!");
        console.log(JSON.stringify(resp, null, 4));
    }, function(err) {
        console.trace(err.message);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM