.NET Core使用ElasticSearch 四:批量操作,批量更新添加等
电脑版发表于:2021/7/14 17:20
ElasticSearch批量更新
原生API
POST users/_bulk {"update":{"_id":"1"}} {"doc":{"message":"测试一下...."}} {"update":{"_id":"2"}} {"doc":{"message":"测试一下...."}}
执行效果如下:
有些时候如果代码执行有问题,我们可以先用原生的语句执行试试,让原生的语句能够成功执行后在去分析代码调用的问题,因为代码调用其实不过就是使用代码去执行这些原生语句而已
.net core调用执行:
格式一定要对,如果是这种的,这个user的格式就有问题
像这样就可以了,id在update上面提供了,doc哪里就不需要提供了,否则反而会报错
封装的代码:
/// <summary> /// 批量更新文档 /// </summary> /// <param name="indexName">索引名称</param> /// <param name="listDocment">数据集合,注意需要提供更新的id</param> /// <returns></returns> public static async Task<bool> BatchUpdateDocumentByBulkAsync(this IElasticSearchServer elasticSearchServer, string indexName, List<object> listDocment) { bool flag = false; try { List<string> list = new List<string>(); foreach (var objectDocment in listDocment) { string json = JsonConvert.SerializeObject(objectDocment); JToken docment = null; var objectDocmentOne = JToken.Parse(json); docment = objectDocmentOne; if (json.IndexOf("[") == 0) { json = JsonConvert.SerializeObject(objectDocmentOne[0]); docment = objectDocmentOne[0]; } string _id = docment["id"].ToString(); int idInt = json.IndexOf("\"id"); //去掉doc下面的json,因为id在update上面提供了,doc哪里就不需要提供了,否则反而会报错 if (idInt > 0) { string idJson = json.Substring(idInt, json.IndexOf(_id) + _id.Length); json = json.Replace(idJson, ""); } list.Add("{\"update\":{\"_id\":\"" + _id + "\"}}"); list.Add("{\"doc\":" + json + "}"); } var stringRespones = await elasticSearchServer.ElasticJsonClient.BulkAsync<StringResponse>(indexName.ToLower(), PostData.MultiJson(list)); var resObj = JObject.Parse(stringRespones.Body); if (!(bool)resObj["errors"]) { return true; } } catch (Exception ex) { } return flag; }
action调用代码:
/// <summary> /// 批量更新文档 /// </summary> /// <returns></returns> public async Task<bool> BatchUpdateDocumentByBulk() { List<object> contens = new List<object>() { new { id=1, user = "嘻嘻_批量更新", post_date = "2021-10-11T15:00:12", message = "批量更新_id_1" }, new { id=2, user = "xxx_批量更新", post_date = "2021-10-11T15:00:12", message = "批量更新_id_2" } }; bool result = await _elasticSearchServer.BatchUpdateDocumentByBulkAsync("users", contens); return result; }
ElasticSearch批量添加
原生API
##批量添加 POST users/_bulk {"index":{"_index":"users","_id":3}} {"message":"批量添加...."} {"index":{"_index":"users","_id":4}} {"message":"批量添加...."}
代码就留一下,自己写了,大同小异
贴一下代码:https://download.tnblog.net/resource/index/6769f2d356784dcd9689882012ad2754