当我试图自己写它时,我想,“什么?你怎么写的?”

关于聚合查询

在 Elsticseaech,对于您通常的搜索查询,聚合您可以为(下面的示例)编写查询。

返回使用qiita搜索到的文章的搜索结果以及标签聚合时的查询示例
# 获取 /articles/_search
{
  "_source": [
    "id",
    "body"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "multi_match": {
            "fields": [
              "title",
              "title.ngram",
              "body",
              "body.ngram"
            ],
            "query": "qiita",
            "type": "phrase",
            "operator": "and"
          }
        }
      ]
    }
  },
  "sort": [
    "_score"
  ],
  "aggs": {
    "tags": {
      "terms": {
        "field": "tag"
      }
    }
  }
}
在查询中以 aggs 开头的以下部分中,使用键 `tags`,将从索引中的命中内容中检查标签字段。
  "aggs": {
    "tags": {
      "terms": {
        "field": "tag"
      }
    }
  }

然后,连同搜索结果,它返回 48 篇带有教程标签的文章,如下所示。

{
  "aggs": {
    "tags": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 10,
      "buckets": [
        {
          "key": "チュートリアル",
          "doc_count": 48
        },
        {
          "key": "aws",
          "doc_count": 1
        },
        #(中略)
        {
          "key": "infrastructure",
          "doc_count": 1
        }
      ]
    }
  }
}

我想知道○○天内创建的文章数

所以,就像标签一样,如果你想按日期聚合,你会怎么写呢?
在本例中,我们需要 7 天、30 天和 365 天内创建的文章数。
此外,索引包含日期类型的 created_at。

使用日期范围聚合

**日期范围聚合通过如下使用**,可以以一种很好的方式聚合时间。

{
  "aggs": {
    "date": {
      "date_range": {
        "field": "created_at",
        "format": "yyyy-MM-dd'T'HH:mm:ssZ",
        "ranges": [
          {
            "from": "now-168h"
          },
          {
            "from": "now-720h"
          },
          {
            "from": "now-8760h"
          }
        ]
      }
    }
  }
}

重点是from部分,可以now-時間的形式收集○○之前的文章数。
它将以下列格式返回。

{
  "aggregations": {
    "date": {
      "buckets": [
        {
          "key": "2021-08-12T03:25:33+0000-*",
          "from": 1628738733198,
          "from_as_string": "2021-08-12T03:25:33+0000",
          "doc_count": 55
        },
        {
          "key": "2022-07-13T03:25:33+0000-*",
          "from": 1657682733198,
          "from_as_string": "2022-07-13T03:25:33+0000",
          "doc_count": 2
        },
        {
          "key": "2022-08-05T03:25:33+0000-*",
          "from": 1659669933198,
          "from_as_string": "2022-08-05T03:25:33+0000",
          "doc_count": 0
        }
      ]
    }
  }
}

由于这次指定了 h,因此可以将(指定したい日付範囲)*24 放入每个中。

你也可以这样写:

{
  "aggs": {
    "date": {
      "date_range": {
        "field": "created_at",
        "format": "yyyy-MM-dd'T'HH:mm:ssZ",
        "ranges": [
          {
            "from": "now-1w"
          },
          {
            "from": "now-30d"
          },
          {
            "from": "now-365d"
          }
        ]
      }
    }
  }
}

原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308623376.html

相关文章: