Created script field successfully but error occurred in discover

@Echo_yu, scripted field is created on index pattern level which is part of Kibana, and not Elasticsearch.

If you want to see aggregation with scripted field in dev tools, you'd have to manually duplicate your script inside that aggregation. There is a documented example using a script for a sum aggregation which may help. To avoid duplication, you could also store the script and reference in both locations by name. - How to use a script field inside Aggregate?

But this scripted field should be available for aggregations in Kibana's visualize. So you should be able to create a visualisation on that field. Internally Kibana will use your script inside the aggregation in request to Elasticsearch.

Hope this is helpful