Painless script for custom scoring based on number of occurrences of a term

Hi team!

I see this - SELECT count(date) FROM my-index in the documentation - Functions - OpenSearch documentation

can you give me an example of how to write it in a painless script to give custom score based on count of a particular term in a field?

eg/ if recipe has “healthy” 4 times, it should be score 1.5. If it has “healthy” 6 times, the score should be 2.5

I am trying something like this:

"source": "int termfreq = doc['recipe'].count('healthy'); if (termfreq == 4) { return 1.5; } else if (termfreq == 6) { return 2.5; } else { return 1; }"

but its complaining at the .count area

If changing the score is what you want, I’d look for a scripted similarity rather than a custom function: Similarity module | Elasticsearch Guide [7.10] | Elastic

The term frequency in the document should be doc.freq

In case you want more goodies around similarities, check this blog post: Search Relevance - Solr & Elasticsearch Similarities -