ElasticSearch NEST Delete all document

2019-09-16 18:14发布

问题:

I am using ElastciSearch 2.3.0

I am trying to delete documents from the ElasticSearch using .net and NEST for specific index.

I only want to delete all documents and not the _mapping

DeleteByQueryRequest r = new DeleteByQueryRequest(new IndexName() { Name = indexName });
r.QueryOnQueryString = "*";                            
var response = client.DeleteByQuery(r);

I am try to do this by using above code but it is not working.

Please suggest on what's wrong with the above code or how this can be done.

Thanks for your help in advance.

回答1:

Don't use delete by query it was made a plugin since elastic 2.0 for a good reason. You can get out of memory exceptions easy. You should delete the whole index and recreate the mappings

static void Main(string[] args)
        {
            ElasticClient db = new ElasticClient(new Uri("http://localhost.fiddler:9200"));

            db.IndexMany(Enumerable.Range(0, 100).Select(i => new Data { Id = i, Name = "Name" + i }), "test_index");

            var mappings = db.GetMapping<Data>();

            var delete = db.DeleteIndex(new DeleteIndexRequest("test_index"));

            var indexMapping = mappings.IndexTypeMappings["test_index"].ToDictionary(k => k.Key, v => (ITypeMapping)v.Value);

            db.CreateIndex(new CreateIndexRequest("test_index")
            {
                Mappings = new Mappings(indexMapping)
            });

            Console.ReadLine();
        }

        class Data 
        {
            public int Id { get; set; }

            public string Name { get; set; }
        }

Raw copy of index

var res = db.LowLevel.IndicesGetMapping<JObject>("test_index"); 
var delete = db.DeleteIndex(new DeleteIndexRequest("test_index"));
var mappings = res.Body["test_index"].ToString(); 
var create = db.LowLevel.IndicesCreate<JObject>("test_index", mappings);

If you really need to install the plug-in sudo bin/plugin install delete-by-query



回答2:

It worked. Thanks a lot.

var res = db.LowLevel.IndicesGetMapping<JObject>("test_index"); 
var delete = db.DeleteIndex(new DeleteIndexRequest("test_index")); 
var mappings = res.Body["test_index"].ToString(); 
var create = db.LowLevel.IndicesCreate<JObject>("test_index", mappings);