使用HttpClient调用Elasticsearch Count API获取查询匹配结果总数
问题根源
你调用的contents.Count()是C#字符串的LINQ扩展方法,统计的是ES返回的JSON字符串的字符总数,和接口返回的count字段完全无关,你拿到的72就是当前JSON字符串的字符数,不是统计的文档总数。
解决方案
你需要先把返回的JSON字符串反序列化,再提取count字段值,以下是两种常用实现方式:
方式1:使用.NET内置System.Text.Json解析
强类型解析(推荐,性能更高)
首先定义和返回结构匹配的实体类:
using System.Text.Json.Serialization; public class EsCountResponse { [JsonPropertyName("count")] public long Count { get; set; } [JsonPropertyName("_shards")] public ShardsInfo Shards { get; set; } } public class ShardsInfo { [JsonPropertyName("total")] public int Total { get; set; } [JsonPropertyName("successful")] public int Successful { get; set; } [JsonPropertyName("skipped")] public int Skipped { get; set; } [JsonPropertyName("failed")] public int Failed { get; set; } }
再反序列化提取字段:
using System.Text.Json; // contents为ES接口返回的JSON字符串 var esResponse = JsonSerializer.Deserialize<EsCountResponse>(contents); long count = esResponse.Count; // 此处即可拿到正确的91
动态解析(无需定义实体类)
using System.Text.Json.Nodes; var jsonNode = JsonNode.Parse(contents); long count = jsonNode["count"].GetValue<long>();
方式2:使用Newtonsoft.Json(Json.NET)解析
动态解析
using Newtonsoft.Json; dynamic jsonObj = JsonConvert.DeserializeObject(contents); long count = jsonObj.count;
注意事项
你贴出的JSON示例外层多了两层大括号,属于调试复制时的冗余内容,正常ES返回的结构只有一层大括号,无需额外处理。另外请确认你的HttpClient请求配置正确:请求方法为POST、地址为ES节点地址/索引名/_count、请求头携带Content-Type: application/json、请求体为你编写的countQuery。
内容的提问来源于stack exchange,提问作者MarkCo
相关产品推荐
相关产品推荐

