Script field could not run in the visualize

I create a script field as follwing

if (params._source.containsKey('datav1') && params._source.datav1.containsKey('messageHistory')) {
    def firstElement = params._source.datav1.messageHistory[0];
    if (firstElement.containsKey('service')) {
        return firstElement['service'];
    }
    
}
return 'NULL';

The data structure looks like this

{
     "_source": {
         "datav1": {
            "deviceVersion": "egale",
            "notificationType": "pub",
            "messageHistory": [
          {
          "service": "test",
          "created": "2024-09-20T07:00:35.943Z",
        },
      ],
     }
}

it run well in the preview, but when I used it in the visualize, I got this error

Error
    at Fetch._callee3$ (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/core/core.entry.js:6:59535)
    at tryCatch (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/plugin/opendistroQueryWorkbenchKibana/opendistroQueryWorkbenchKibana.plugin.js:1:32004)
    at Generator.invoke [as _invoke] (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/plugin/opendistroQueryWorkbenchKibana/opendistroQueryWorkbenchKibana.plugin.js:1:35968)
    at forEach.prototype.<computed> [as next] (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/plugin/opendistroQueryWorkbenchKibana/opendistroQueryWorkbenchKibana.plugin.js:1:33129)
    at fetch_asyncGeneratorStep (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/core/core.entry.js:6:52652)
    at _next (https://kibana-prod.aaecosystem.com/_plugin/kibana/36163/bundles/core/core.entry.js:6:52968)

OK, although there is no obvious prompt for this error.I think it should be because the amount of data is too large, leading to the query timeout, because when I set the query time to one hour, I can get the data, but when the query time is too large, this error will occur