AI Hints
Home›Elasticsearch Tutorial›Custom Scoring and Typos
Elasticsearch · Lesson 64 of 120

function_score

Popularity counts.

⏱ 2 min read▶ Video at 1:00:35🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Two headlamps match a search equally well. One has eight hundred happy reviews, the other has three. Customers want the popular one first. Function score mixes numbers like that into the score.

  • Equal text match
  • 800 reviews vs 3
  • Popular first

Boost by review count

Function score wraps a normal query. Field value factor uses the reviews field. Log one p softens it, so eight hundred reviews isn't eight hundred times better. Run it. The most reviewed headlamps now rank first.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._source
{
  "query": { "function_score": {
    "query": { "match": { "name": "headlamp" } },
    "field_value_factor": {
      "field": "reviews", "modifier": "log1p", "factor": 1 },
    "boost_mode": "multiply" } },
  "_source": ["name", "reviews"]
}
Output
{
  "hits": {
    "hits": [
      {
        "_source": {
          "name": "Rechargeable 600 Headlamp",
          "reviews": 544
        }
      },
      {
        "_source": {
          "name": "Bright 400 Headlamp",
          "reviews": 38
        }
      },
      {"_source": {"name": "Mini 200 Headlamp", "reviews": 8}}
    ]
  }
}
Also uses _load
catalog

function_score options

Field value factor uses a number field. Modifiers like log one p and square root stop big numbers from taking over. Boost mode says how to combine with the text score. And script score allows any formula.

keyvalue
field_value_factoruse a numeric field
modifierlog1p, sqrt
boost_modemultiply, sum, replace
script_scoreany formula

Summary

Function score mixes signals like reviews or ratings into relevance. Soften big numbers with log one p. Next, preferring newer or nearer things.

Key takeaways
  • function_score
  • field_value_factor
  • log1p
Next up: Decay Functions — newer is better