How to execute a stored script in a search query

hey there,
I created a stored script that should add a new field to all the docs into an index.

POST _scripts/set_new_field
{
  "script": {
    "lang": "painless",
    "source": """
     if (ctx._source.speaker == "TEDX") { 
       ctx._source.conference = true;
     } else 
     {
       ctx._source.conference = false;
     } 
"""
  }

}

I am not able right to execute it on a specific index named speech
What should be the request to be executed?
i.e.

GET speech/_search
{
   "query": {
      "match_all": {}
   }
   "script": {
   ... 
   }
}

I checked the official documentation but I cannot find the correct address

Here is a full example of how to save and then use a script within a search.

GET my-index-000001/_search
{
  "query": {
    "script_score": {
      "query": {
        "match": {
            "message": "some message"
        }
      },
      "script": {
        "id": "calculate-score",
        "params": {
          "my_modifier": 2
        }
      }
    }
  }
}

I already saw that script and documentation but I cannot get out with it.
if I try:

GET hamlet/_search
{
  "query": {
    "script_score": {
      "query": {
        "match": {
            "city": "Paris"
        }
      },
      "script": {
        "id": "set_new_field"
      }
    }
  }
}

I get this error:

"caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "cannot resolve symbol [ctx._source.speaker]"
      }

furthermore, I don't understand why I should use script_score

Is your end goal to add a new field permanently to your index based on the script?

If so I would just use the Update by Query API.

POST speech/_update_by_query
{
  "script": {
    "lang": "painless",
    "source": """
     if (ctx._source.speaker == "TEDX") { 
       ctx._source.conference = true;
     } else 
     {
       ctx._source.conference = false;
     } 
    """
  },
  "query": {
    "match_all": {}
  }
}

Result

    "hits" : [
      {
        "_source" : {
          "conference" : false,
          "speaker" : "Elastic"
        }
      },
      {
        "_source" : {
          "conference" : true,
          "speaker" : "TEDX"
        }
      }
    ]

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