Aggregates of attributes with Sum

I have a doc structure like:

{
"product_number" : 4687897,
"name" : "widget",
"attributes" : [ {
"name" : "size",
"weight" : 3,
"value" : "large"
}, {
"name" : "color",
"weight" : 1,
"value" : "blue"
} ]
},
{
"product_number" : 1354564,
"name" : "thingy",
"attributes" : [ {
"name" : "shape",
"weight" : 2,
"value" : "round"
}, {
"name" : "color",
"weight" : 1,
"value" : "green"
} ]
}

If I query using aggregates, I am able to group bu the attributes.name. However, when I try to get the sum of the weight to create an attribute score it gives undesired results:

curl localhost:9200/prod/_search?pretty -d '{"aggs":{"attribute_groups":{"terms":{"field":"attributes.name"},"aggs":{"weight_sum":{"sum":{"field":"attributes.weight"}}}}}}'

Actual results:

"aggregations" : {
"attribute_groups" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "color",
"doc_count" : 2,
"weight_sum" : {
"value" : 7.0
}
}, {
"key" : "shape",
"doc_count" : 1,
"weight_sum" : {
"value" : 3.0
}
}, {
"key" : "size",
"doc_count" : 1,
"weight_sum" : {
"value" : 4.0
}
} ]
}
}

Desired results:

"aggregations" : {
"attribute_groups" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "color",
"doc_count" : 2,
"weight_sum" : {
"value" : 2.0
}
}, {
"key" : "shape",
"doc_count" : 1,
"weight_sum" : {
"value" : 2.0
}
}, {
"key" : "size",
"doc_count" : 1,
"weight_sum" : {
"value" : 3.0
}
} ]
}
}

The idea is to have the weight be an additional tool for determining attribute relevance when building out faceted navigation

Figured this one out myself. The way to accomplish a sum on values associated with term is to nested mapping.

curl -XPUT 'localhost:9200/prod?pretty' -d'
{
  "mappings": {
    "external": {
      "properties": {
        "attributes": {
          "type": "nested" 
        }
      }
    }
  }
}'````

This allows the the array of objects to be associated. That way a sum of the weight value corresponds to the particular name upon which the grouping occurs.

Because the index is nested, the query for the nested values must change to something like this:

curl localhost:9200/prod/_search?pretty -d '
{
"aggs" : {
"attributes" : {
"nested" : {
"path" : "attributes"
},
"aggs" : {
"facets" : {
"terms":{ "field" : "attributes.name" },
"aggs": {
"facet_sum": {
"sum": {
"field": "attributes.weight"
}
}
}
}
}
}
}
}'````