如何根据 Elasticsearch 中的特定字段获取非空值的计数

how to get count of not-null value based on specific field in Elasticsearch

我有弹性搜索索引,我需要其中一个字段 ("actual_start") 不为空的记录总数,我该怎么做?

我已经写了这个查询,我想将非空实际起始值的计数附加到我的查询结果中:

 $params = [
            'index' => "appointment_request",
            'body' => [
                'from' => $request['from'],
                'size' => $request['size'],
                "query" => [
                    "bool"=>[
                        "must" => [

                            [
                                "term" => [
                                    "doctor_id" => [
                                        "value" => $request['doctor_id']
                                    ]
                                ]
                            ],
                            [
                                "match" => [
                                    "book_date" => $request['book_date']

                                ]
                            ],
                      
                        ]

                    ],
                ]
            ]
        ];

看看Exists Query

试试这个:

GET <your-index>/_count
{
  "query": {
    "exists": {
      "field": "actual_start"
    }
  }
}

然后您可以读取 count 值,该值将为您提供 actual_start 为 not-null.

的记录总数

您还可以将 _count 替换为 _searchhits 下的 total 值将为您提供总计数(如果您还想要 hits) .

如果你想做相反的事情(所有 actual_start 为空的记录):

GET <your-index>/_count
{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "actual_start"
          }
        }
      ]
    }
  }
}

更新

如果我对你的理解正确,你想将你当前的查询附加到 exists 查询。

示例:

GET <your-index>/_search
{
  "query": {
    "bool": {
      "must": [
        {
          <put-your-query-here>
        },
        {
          "exists": {
            "field": "actual_start"
          }
        }
      ]
    }
  }
}