# Can I do a sum on the fields that have 'keyword' type

**URL:** <https://discuss.elastic.co/t/can-i-do-a-sum-on-the-fields-that-have-keyword-type/333076>\
**Category:** Elasticsearch\
**Created:** [May 10, 2023, 10:51am UTC](https://discuss.elastic.co/t/can-i-do-a-sum-on-the-fields-that-have-keyword-type/333076 "2023-05-10T10:51:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![searchwithme](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/searchwithme/32/137075_2.png) [@searchwithme](https://discuss.elastic.co/u/searchwithme)\
**Post date:** [May 10, 2023, 10:51am UTC](https://discuss.elastic.co/t/can-i-do-a-sum-on-the-fields-that-have-keyword-type/333076/1 "2023-05-10T10:51:29Z")

</div>

I have a field that is keyword type. The index looks like this:

{  
"key": 1  
},  
{  
"key": 2  
},  
{  
"key": 3  
},  
{  
"key":"abc"  
},  
{  
"key":"zyx"  
}

Some values are numeric and some are strings. Is there a way to sum all numeric keywords such that the value comes to 1+2+3 = 6

Is some form type casting possible?

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [May 10, 2023, 11:06am UTC](https://discuss.elastic.co/t/can-i-do-a-sum-on-the-fields-that-have-keyword-type/333076/2 "2023-05-10T11:06:31Z")

</div>

The only way I see to do this would be with a runtime field but this will be slow most likely...  
The runtime field could emit 0 when not a number and the number when it can be transformed as a number.  
Then you can aggregate with a sum agg on that field I think.

Have a look at [Sum aggregation | Elasticsearch Guide [8.7] | Elastic](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html#_script_14)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [June 7, 2023, 11:06am UTC](https://discuss.elastic.co/t/can-i-do-a-sum-on-the-fields-that-have-keyword-type/333076/3 "2023-06-07T11:06:52Z")

</div>

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