'How to get sum of diferent fields / array values in elasticsearch?

Using Elasticsearch 7.9.0
My document looks like this

{
  "student": {
    "marks": [
      {
        "sub": 80
      },
      {
        "sub": 90
      },
      {
        "sub": 100
      }
    ]
  }
}

I need one more field total_marks in the response of GET API
Something like this

{
  "hits": [
    {
      "_index": "abc",
      "_type": "_doc",
      "_id": "blabla",
      "_score": null,
      "_source": {
        "student": {
          "marks": [
            {
              "sub": 80
            },
            {
              "sub": 90
            },
            {
              "sub": 100
            }
          ]
        }
      },
      "total_marks": 270
    }
  ]
}

I tried using script_fields My query is

GET sample/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "total_marks": {
      "script": {
         "source": """double sum = 0.0;
                    for( item in params._source.student.marks)
                    { sum = sum + item.sub }
                    return sum;"""
      }
    }
  }
}

I got response as

{
  "hits": [
    {
      "_index": "abc",
      "_type": "_doc",
      "_id": "blabla",
      "_score": null,
      "_source": {
        "student": {
          "marks": [
            {
              "sub": 80
            },
            {
              "sub": 90
            },
            {
              "sub": 100
            }
          ]
        }
      },
      "fields": {
        "total_marks": [
          270
        ]
      }
    }
  ]
}

Is thare any way to get as expected?
Any better/optimal solution would be helps a lot.
Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source