Elasticsearch获取最新文档,按多个字段分组

德科夫

在Elasticsearch上查询每种类型的最新文档类似,我在ES中有一组记录。为了便于说明,我们还说这是新闻,每个新闻都有映射:

"news": {
    "properties": {
        "source": { "type": "string", "index": "not_analyzed" },
        "headline": { "type": "object" },
        "timestamp": { "type": "date", "format": "date_hour_minute_second_millis" },
        "user": { "type": "string", "index": "not_analyzed" }
        "newspaper": { "type": "string", "index": "not_analyzed"}
    }
}

我可以通过以下方式获取每位用户的最新“新闻文章”:

"size": 0,
"aggs": {
    "sources" : {
        "terms" : {
            "field" : "user"
        },
        "aggs": {
            "latest": {
              "top_hits": {
                "size": 1,
                "sort": {
                  "timestamp": "desc"
                }
              }
            }
        }
    }
}

但是,我试图实现的是让每个用户,每份报纸获得最新的文章而我做得还不够。

例如

  • 约翰·纽约时报,Title1
  • 约翰(BBC),标题2
  • 简·纽约时报,Title3
  • 等等。

您可以像这样terms为该newspaper字段添加另一个子聚合

"size": 0,
"aggs": {
    "sources" : {
        "terms" : {
            "field" : "user"
        },
        "aggs": {
            "newspaper": {
               "terms": {
                  "field": "newspaper"
               },
               "aggs": {
                  "latest": {
                     "top_hits": {
                       "size": 1,
                       "sort": {
                          "timestamp": "desc"
                       }
                     }
                  }
               }
            }
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章