How to add parameters to a scripted similarity?

I'm trying to make a parametrized scripted similarity function but I can't get it to work.
I have created the script and have it stored.

However, when I try to implement it in the similarity score, I keep getting errors because of the symbol [params].

^ I know my script looks very similar to BM25, but I need to parametrized certain values during the query.

{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "... f = doc.freq/(doc.freq + params['k1'] * (1 - param ...",
          "                             ^---- HERE"
        ],
        "script" : "double boost = 2.2 * doc.freq; double tf = doc.freq/(doc.freq + params['k1'] * (1 - params['b'] + params['b'] * field('dl_avgdl'))); double idf = Math.log(1 + ((params['docs_count'] - term.docfreq + 0.5)/(term.docFreq + 0.5))); return query.boost * tf * idf * norm;",
        "lang" : "painless",
        "position" : {
          "offset" : 64,
          "start" : 39,
          "end" : 89
        }
      }
    ],
    "type" : "script_exception",
    "reason" : "compile error",
    "script_stack" : [
      "... f = doc.freq/(doc.freq + params['k1'] * (1 - param ...",
      "                             ^---- HERE"
    ],
    "script" : "double boost = 2.2 * doc.freq; double tf = doc.freq/(doc.freq + params['k1'] * (1 - params['b'] + params['b'] * field('dl_avgdl'))); double idf = Math.log(1 + ((params['docs_count'] - term.docfreq + 0.5)/(term.docFreq + 0.5))); return query.boost * tf * idf * norm;",
    "lang" : "painless",
    "position" : {
      "offset" : 64,
      "start" : 39,
      "end" : 89
    },
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "cannot resolve symbol [params]"
    }
  },
  "status" : 400
}

Is this possible to do with Elasticsearch 8.1?

Hi @fsanzestevez, unfortunately params is not available for similarity scripts. So the script will need to embed the constants.

See the similarity context docs for all the variables available to similarity scripts.

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