使用 HttpClient 执行查询计数 api 搜索 Elasticsearch

Using HttpClient to perform query count api search Elasticsearch

我想使用 httpclient 以便在 elasticsearch 中执行 GET /count return 根据查询搜索有多少命中。但是,在调试和悬停在 jsonData:

上时,我一直试图获取 jsonData 中的值,其中包含以下内容
{{
  "count": 91,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  }
}}

我知道这可以通过 NEST 使用计数 api 来完成。但我想用 httpclient 来做。所以我尝试了以下方法,但是当我设置 count = contents.Count() 时,它 returns 72 而不是 91.

       var countQuery = "{ \"query\": { \"bool\": { \"should\": [ { \"match\": { \"fields.User\": \"jukl\" } } ], \"filter\": [ {" +
            " \"range\": { \"@timestamp\": { \"gte\": \"2021-07-01T00:00:00.000-05:00\", \"lt\": \"2021-07-31T23:59:59.999-05:00\" } } } ]," +
            " \"minimum_should_match\": 1 } } }";


      

如何分配 count 来保存值 91?

elastic for .NET 文档本身声明使用 HttpClient 进行消费不是一个好习惯。 正确的做法是使用依赖注入,如下例所示:

public static void AddElasticsearch(this IServiceCollection services, IConfiguration configuration)
{
    var settings = new ConnectionSettings(new Uri(configuration["ElasticsearchSettings:uri"]));

    var defaultIndex = configuration["ElasticsearchSettings:defaultIndex"];

    if (!string.IsNullOrEmpty(defaultIndex))
        settings = settings.DefaultIndex(defaultIndex);

    var basicAuthUser = configuration["ElasticsearchSettings:username"];
    var basicAuthPassword = configuration["ElasticsearchSettings:password"];

    if (!string.IsNullOrEmpty(basicAuthUser) && !string.IsNullOrEmpty(basicAuthPassword))
        settings = settings.BasicAuthentication(basicAuthUser, basicAuthPassword);

    var client = new ElasticClient(settings);

    services.AddSingleton<IElasticClient>(client);
}

之后,使用下面的代码获取记录总数:

var search = new SearchDescriptor<T>(IndexName).MatchAll();
var response = await _elasticClient.SearchAsync<T>(search);
if (response.IsValid)
{
    return response.Total;
}

参考:https://github.com/hgmauri/elasticsearch-with-nest