带分组的弹性搜索困难查询

Elastic Search Difficult Query with Grouping

我是 Elastic Search (1.7) 的新手。 我有客户版本的ES索引。

每个客户端都有一个唯一的 ID (client_id)。

一个客户端有很多版本可以在索引中。

客户端的每个版本都有一个唯一的客户端 ID (version_id)。

索引数据示例:

{
  “client_id”: "1",
  "version_id": "1",
  “versionCreationDate”: "2015-11-06T10:02:22.597Z",
  “clientName”: “FirstName LastName”
}
…,
{
  “client_id”: "1",
  "version_id": "n",
  “versionCreationDate”: …
  “clientName”: “FirstName LastName”
},
{
  “client_id”: "2",
  "version_id": "1",
  “versionCreationDate”: …
  “clientName”: “FirstName LastName”
},
…
{
  “client_id”: "2",
  "version_id": "n",
  “versionCreationDate”: …
  “clientName”: “FirstName LastName”
},
…
{
  “client_id”: "N",
  "version_id": "1",
  “versionCreationDate”: …
  “clientName”: “FirstName LastName”
},
…
{
  “client_id”: "N",
  "version_id": "n",
  “versionCreationDate”: …
    “clientName”: “FirstName LastName”
}

我需要通过查询的输入参数查找客户端的版本:

<clientName>,<VersionCreationDateMax>。

客户端的版本应该与 <clientName> 匹配(fuzziness=auto)。并且任何版本都必须具有此客户端的 versionCreationDate 最大值,但 <= <VersionCreationDateMax>。因此每个客户端的唯一版本应该在搜索结果中(最新,但不超过 <VersionCreationDateMax>)

请帮我找到 filter/query 来做到这一点

您可以通过以下查询实现此目的:

  • 一个 range 过滤器指定最大值 versionCreationDate
  • 然后在 client_id 字段上进行 terms 聚合
  • 最后,对于每个客户端桶,一个 top_hits 子聚合在 versionCreationDate 字段上按 desc 顺序排序并且只返回一个文档(即 size: 1

这里是查询:

{
  "query": {
    "filtered": {
      "filter": {
        "range": {
          "versionCreationDate": {
            "lt": "2015-12-02T00:00:00.000Z"
          }
        }
      }
    }
  },
  "aggs": {
    "clients": {
      "terms": {
        "field": "client_id"
      },
      "aggs": {
        "latest": {
          "top_hits": {
            "sort": [
              {
                "versionCreationDate": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}