根据 ObjectField 的属性进行聚合,然后对嵌套字段进行排序

Aggregation on the basis of an attribute of an ObjectField then sort Nested Fields

假设我有这样的文件-

{
    "_id": 1,
    "threat": {
        "application_number": 1234,
    }
    "score_algorithms": [
        {
            "score": 21,
        },
        {
            "score": 93,
        }    
    ],
    "max_similarity": 93,
}

{
    "_id": 2,
    "threat": {
        "application_number": 1348,
    }
    "score_algorithms": [
        {
            "score": 45,
        },
        {
            "score": 67,
        }    
    ],
    "max_similarity": 67,
}

{
    "_id": 3,
    "threat": {
        "application_number": 1234,
    }
    "score_algorithms": [
        {
            "score": 98,
        },
        {
            "score": 51,
        }    
    ],
    "max_similarity": 98,
}

现在这里的议程是-

对于要求 1. 和 2. 即对文档进行分组和排序,您可以在聚合定义中使用 order 参数。

要检索聚合中的 score_algorithms 字段,请使用 top_hits 子聚合。

您将只能检索 top_hits 聚合的 size 参数之前的文档。如果单个 application_number 有大量文档,它可能会很慢。

{
    "size": 0,
    "aggs" : {
        "applications" : {
            "terms" : {
                "field" : "threat.application_number",
                "order": [{"stats.max": "desc"}]
            },
            "aggs" : {
                "stats" : { "stats" : { "field" : "max_similarity" } },
                "applications_fields": {
                    "top_hits": {
                        "sort": [
                            {
                                "max_similarity": {
                                    "order": "desc"
                                }
                            }
                        ],
                        "_source": {
                            "includes": [ "score_algorithms", "max_similarity" ]
                        },
                        "size" : 100
                    }
                }
            }
        }

    }
}