Elasticsearch sub aggregation not working with max

I have nested data of shape: albums have tracks, tracks have versions.

album: {
   tracks: [
       {
         id: 1,
         mainTrackID: 1, // mainTrackID = id means main track
         versions: [
            {
               id: 2,
               mainTrackID: 1 // mainTrackID != id means it's a version
            }
         ]
     }
   ]
}

I want to aggregate the results of my query by albums, tracks, versions. Album with the highest track/version score should be on the top. Then within each album I want to group by mainTrackID with tracks/versions sorted by doc score desc.

I have this query that works album_track_max_score is set to sum but not max .

 "aggs": {
    "by_albumID": {
      "terms": {
        "field": "album.albumID",
        "size": 5,
            "order": [
                { "album_track_max_score": "desc" }
            ]
      },
      "aggs": {
        "by_mainTrackID": {
          "terms": {
            "field": "mainTrackID",
            "size": 10,
                "order": [
                    { "track_score": "desc" }
                ]
          },
          "aggs": {
            "by_top_hits": {
              "top_hits": {
                "_source": {
                  "include": [
                    "trackID",
                        "mainTrackID",
                        "album.albumDisplayTitle",
                        "trackDisplayTitle",
                        "releaseDate"
                  ]
                },
                "size": 10,
                "sort": [
                    { "_score": {"order": "desc"}}
                ]
              }
            },
            "track_score": {
            "max": {
                "script": "_score"
                }
            }
          }
        },
        "album_track_max_score": {
        "max": {
            "script": "_score"
            }
        }
      }
    }
  }

When album_track_max_score is set to max the by_top_hits agg only returns 1 track. When I set it to sum everything works perfectly (it returns all versions grouped by mainTrackID) except the top album isn't the 1 with the highest score but one with the highest combined score of all tracks which does not fulfill the requirement.

I'm not sure how an aggregation in parent bucket is causing things to change in the child? I've tried using track_score in the track/version agg but it doesn't seem to do anything. I have tried many other permutations but it seems I'm missing some key concept here.

Any guidance is much appreciated.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.