function-score-query.asciidoc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. [[query-dsl-function-score-query]]
  2. === Function Score Query
  3. The `function_score` allows you to modify the score of documents that are
  4. retrieved by a query. This can be useful if, for example, a score
  5. function is computationally expensive and it is sufficient to compute
  6. the score on a filtered set of documents.
  7. `function_score` provides the same functionality that
  8. `custom_boost_factor`, `custom_score` and
  9. `custom_filters_score` provided
  10. but furthermore adds futher scoring functionality such as
  11. distance and recency scoring (see description below).
  12. ==== Using function score
  13. To use `function_score`, the user has to define a query and one or
  14. several functions, that compute a new score for each document returned
  15. by the query.
  16. `function_score` can be used with only one function like this:
  17. [source,js]
  18. --------------------------------------------------
  19. "function_score": {
  20. "(query|filter)": {},
  21. "boost": "boost for the whole query",
  22. "FUNCTION": {},
  23. "boost_mode":"(multiply|replace|...)"
  24. }
  25. --------------------------------------------------
  26. Furthermore, several functions can be combined. In this case one can
  27. optionally choose to apply the function only if a document matches a
  28. given filter:
  29. [source,js]
  30. --------------------------------------------------
  31. "function_score": {
  32. "(query|filter)": {},
  33. "boost": "boost for the whole query",
  34. "functions": [
  35. {
  36. "filter": {},
  37. "FUNCTION": {}
  38. },
  39. {
  40. "FUNCTION": {}
  41. }
  42. ],
  43. "max_boost": number,
  44. "score_mode": "(multiply|max|...)",
  45. "boost_mode": "(multiply|replace|...)"
  46. }
  47. --------------------------------------------------
  48. If no filter is given with a function this is equivalent to specifying
  49. `"match_all": {}`
  50. First, each document is scored by the defined functions. The parameter
  51. `score_mode` specifies how the computed scores are combined:
  52. [horizontal]
  53. `multiply`:: scores are multiplied (default)
  54. `sum`:: scores are summed
  55. `avg`:: scores are averaged
  56. `first`:: the first function that has a matching filter
  57. is applied
  58. `max`:: maximum score is used
  59. `min`:: minimum score is used
  60. The new score can be restricted to not exceed a certain limit by setting
  61. the `max_boost` parameter. The default for `max_boost` is FLT_MAX.
  62. Finally, the newly computed score is combined with the score of the
  63. query. The parameter `boost_mode` defines how:
  64. [horizontal]
  65. `multiply`:: query score and function score is multiplied (default)
  66. `replace`:: only function score is used, the query score is ignored
  67. `sum`:: query score and function score are added
  68. `avg`:: average
  69. `max`:: max of query score and function score
  70. `min`:: min of query score and function score
  71. ==== Score functions
  72. The `function_score` query provides several types of score functions.
  73. ===== Script score
  74. The `script_score` function allows you to wrap another query and customize
  75. the scoring of it optionally with a computation derived from other numeric
  76. field values in the doc using a script expression. Here is a
  77. simple sample:
  78. [source,js]
  79. --------------------------------------------------
  80. "script_score" : {
  81. "script" : "_score * doc['my_numeric_field'].value"
  82. }
  83. --------------------------------------------------
  84. On top of the different scripting field values and expression, the
  85. `_score` script parameter can be used to retrieve the score based on the
  86. wrapped query.
  87. Scripts are cached for faster execution. If the script has parameters
  88. that it needs to take into account, it is preferable to reuse the same
  89. script, and provide parameters to it:
  90. [source,js]
  91. --------------------------------------------------
  92. "script_score": {
  93. "lang": "lang",
  94. "params": {
  95. "param1": value1,
  96. "param2": value2
  97. },
  98. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  99. }
  100. --------------------------------------------------
  101. Note that unlike the `custom_score` query, the
  102. score of the query is multiplied with the result of the script scoring. If
  103. you wish to inhibit this, set `"boost_mode": "replace"`
  104. ===== Boost factor
  105. The `boost_factor` score allows you to multiply the score by the provided
  106. `boost_factor`. This can sometimes be desired since boost value set on
  107. specific queries gets normalized, while for this score function it does
  108. not.
  109. [source,js]
  110. --------------------------------------------------
  111. "boost_factor" : number
  112. --------------------------------------------------
  113. ===== Random
  114. The `random_score` generates scores via a pseudo random number algorithm
  115. that is initialized with a `seed`.
  116. [source,js]
  117. --------------------------------------------------
  118. "random_score": {
  119. "seed" : number
  120. }
  121. --------------------------------------------------
  122. ===== Field Value factor
  123. added[1.2.0]
  124. The `field_value_factor` function allows you to use a field from a document to
  125. influence the score. It's similar to using the `script_score` function, however,
  126. it avoids the overhead of scripting. If used on a multi-valued field, only the
  127. first value of the field is used in calculations.
  128. As an example, imagine you have a document indexed with a numeric `popularity`
  129. field and wish to influence the score of a document with this field, an example
  130. doing so would look like:
  131. [source,js]
  132. --------------------------------------------------
  133. "field_value_factor": {
  134. "field": "popularity",
  135. "factor": 1.2,
  136. "modifier": "sqrt"
  137. }
  138. --------------------------------------------------
  139. Which will translate into the following forumla for scoring:
  140. `sqrt(1.2 * doc['popularity'].value)`
  141. There are a number of options for the `field_value_factor` function:
  142. [cols="<,<",options="header",]
  143. |=======================================================================
  144. | Parameter |Description
  145. |`field` |Field to be extracted from the document.
  146. |`factor` |Optional factor to multiply the field value with, defaults to 1.
  147. |`modifier` |Modifier to apply to the field value, can be one of: `none`, `log`,
  148. `log1p`, `log2p`, `ln`, `ln1p`, `ln2p`, `square`, `sqrt`, or `reciprocal`.
  149. Defaults to `none`.
  150. |=======================================================================
  151. Keep in mind that taking the log() of 0, or the square root of a negative number
  152. is an illegal operation, and an exception will be thrown. Be sure to limit the
  153. values of the field with a range filter to avoid this, or use `log1p` and
  154. `ln1p`.
  155. ===== Decay functions
  156. Decay functions score a document with a function that decays depending
  157. on the distance of a numeric field value of the document from a user
  158. given origin. This is similar to a range query, but with smooth edges
  159. instead of boxes.
  160. To use distance scoring on a query that has numerical fields, the user
  161. has to define an `origin` and a `scale` for each field. The `origin`
  162. is needed to define the ``central point'' from which the distance
  163. is calculated, and the `scale` to define the rate of decay. The
  164. decay function is specified as
  165. [source,js]
  166. --------------------------------------------------
  167. "DECAY_FUNCTION": {
  168. "FIELD_NAME": {
  169. "origin": "11, 12",
  170. "scale": "2km",
  171. "offset": "0km",
  172. "decay": 0.33
  173. }
  174. }
  175. --------------------------------------------------
  176. where `DECAY_FUNCTION` can be "linear", "exp" and "gauss" (see below). The specified field must be a numeric field. In the above example, the field is a <<mapping-geo-point-type>> and origin can be provided in geo format. `scale` and `offset` must be given with a unit in this case. If your field is a date field, you can set `scale` and `offset` as days, weeks, and so on. Example:
  177. [source,js]
  178. --------------------------------------------------
  179. "DECAY_FUNCTION": {
  180. "FIELD_NAME": {
  181. "origin": "2013-09-17",
  182. "scale": "10d",
  183. "offset": "5d",
  184. "decay" : 0.5
  185. }
  186. }
  187. --------------------------------------------------
  188. The format of the origin depends on the <<mapping-date-format>> defined in your mapping. If you do not define the origin, the current time is used.
  189. The `offset` and `decay` parameters are optional.
  190. [horizontal]
  191. `offset`::
  192. If an `offset` is defined, the decay function will only compute the
  193. decay function for documents with a distance greater that the defined
  194. `offset`. The default is 0.
  195. `decay`::
  196. The `decay` parameter defines how documents are scored at the distance
  197. given at `scale`. If no `decay` is defined, documents at the distance
  198. `scale` will be scored 0.5.
  199. In the first example, your documents might represents hotels and contain a geo
  200. location field. You want to compute a decay function depending on how
  201. far the hotel is from a given location. You might not immediately see
  202. what scale to choose for the gauss function, but you can say something
  203. like: "At a distance of 2km from the desired location, the score should
  204. be reduced by one third."
  205. The parameter "scale" will then be adjusted automatically to assure that
  206. the score function computes a score of 0.5 for hotels that are 2km away
  207. from the desired location.
  208. In the second example, documents with a field value between 2013-09-12 and 2013-09-22 would get a weight of 1.0 and documents which are 15 days from that date a weight of 0.5.
  209. The `DECAY_FUNCTION` determines the shape of the decay:
  210. [horizontal]
  211. `gauss`::
  212. Normal decay, computed as:
  213. +
  214. image:images/Gaussian.png[]
  215. where image:images/sigma.png[] is computed to assure that the score takes the value `decay` at distance `scale` from `origin`+-`offset`
  216. image:images/sigma_calc.png[]
  217. [horizontal]
  218. `exp`::
  219. Exponential decay, computed as:
  220. +
  221. image:images/Exponential.png[]
  222. where again the parameter image:images/lambda.png[] is computed to assure that the score takes the value `decay` at distance `scale` from `origin`+-`offset`
  223. image:images/lambda_calc.png[]
  224. [horizontal]
  225. `linear`::
  226. Linear decay, computed as:
  227. +
  228. image:images/Linear.png[].
  229. where again the parameter `s` is computed to assure that the score takes the value `decay` at distance `scale` from `origin`+-`offset`
  230. image:images/s_calc.png[]
  231. In contrast to the normal and exponential decay, this function actually
  232. sets the score to 0 if the field value exceeds twice the user given
  233. scale value.
  234. ===== Multiple values:
  235. If a field used for computing the decay contains multiple values, per default the value closest to the origin is chosen for determining the distance.
  236. This can be changed by setting `multi_value_mode`.
  237. [horizontal]
  238. `min`:: Distance is the minimum distance
  239. `max`:: Distance is the maximum distance
  240. `avg`:: Distance is the average distance
  241. `sum`:: Distance is the sum of all distances
  242. Example:
  243. [source,js]
  244. --------------------------------------------------
  245. "DECAY_FUNCTION": {
  246. "FIELD_NAME": {
  247. "origin": ...,
  248. "scale": ...
  249. },
  250. "multi_value_mode": "avg"
  251. }
  252. --------------------------------------------------
  253. ==== Detailed example
  254. Suppose you are searching for a hotel in a certain town. Your budget is
  255. limited. Also, you would like the hotel to be close to the town center,
  256. so the farther the hotel is from the desired location the less likely
  257. you are to check in.
  258. You would like the query results that match your criterion (for
  259. example, "hotel, Nancy, non-smoker") to be scored with respect to
  260. distance to the town center and also the price.
  261. Intuitively, you would like to define the town center as the origin and
  262. maybe you are willing to walk 2km to the town center from the hotel. +
  263. In this case your *origin* for the location field is the town center
  264. and the *scale* is ~2km.
  265. If your budget is low, you would probably prefer something cheap above
  266. something expensive. For the price field, the *origin* would be 0 Euros
  267. and the *scale* depends on how much you are willing to pay, for example 20 Euros.
  268. In this example, the fields might be called "price" for the price of the
  269. hotel and "location" for the coordinates of this hotel.
  270. The function for `price` in this case would be
  271. [source,js]
  272. --------------------------------------------------
  273. "DECAY_FUNCTION": {
  274. "price": {
  275. "origin": "0",
  276. "scale": "20"
  277. }
  278. }
  279. --------------------------------------------------
  280. and for `location`:
  281. [source,js]
  282. --------------------------------------------------
  283. "DECAY_FUNCTION": {
  284. "location": {
  285. "origin": "11, 12",
  286. "scale": "2km"
  287. }
  288. }
  289. --------------------------------------------------
  290. where `DECAY_FUNCTION` can be "linear", "exp" and "gauss".
  291. Suppose you want to multiply these two functions on the original score,
  292. the request would look like this:
  293. [source,js]
  294. --------------------------------------------------
  295. curl 'localhost:9200/hotels/_search/' -d '{
  296. "query": {
  297. "function_score": {
  298. "functions": [
  299. {
  300. "DECAY_FUNCTION": {
  301. "price": {
  302. "origin": "0",
  303. "scale": "20"
  304. }
  305. }
  306. },
  307. {
  308. "DECAY_FUNCTION": {
  309. "location": {
  310. "origin": "11, 12",
  311. "scale": "2km"
  312. }
  313. }
  314. }
  315. ],
  316. "query": {
  317. "match": {
  318. "properties": "balcony"
  319. }
  320. },
  321. "score_mode": "multiply"
  322. }
  323. }
  324. }'
  325. --------------------------------------------------
  326. Next, we show how the computed score looks like for each of the three
  327. possible decay functions.
  328. ===== Normal decay, keyword `gauss`
  329. When choosing `gauss` as the decay function in the above example, the
  330. contour and surface plot of the multiplier looks like this:
  331. image::https://f.cloud.github.com/assets/4320215/768157/cd0e18a6-e898-11e2-9b3c-f0145078bd6f.png[width="700px"]
  332. image::https://f.cloud.github.com/assets/4320215/768160/ec43c928-e898-11e2-8e0d-f3c4519dbd89.png[width="700px"]
  333. Suppose your original search results matches three hotels :
  334. * "Backback Nap"
  335. * "Drink n Drive"
  336. * "BnB Bellevue".
  337. "Drink n Drive" is pretty far from your defined location (nearly 2 km)
  338. and is not too cheap (about 13 Euros) so it gets a low factor a factor
  339. of 0.56. "BnB Bellevue" and "Backback Nap" are both pretty close to the
  340. defined location but "BnB Bellevue" is cheaper, so it gets a multiplier
  341. of 0.86 whereas "Backpack Nap" gets a value of 0.66.
  342. ===== Exponential decay, keyword `exp`
  343. When choosing `exp` as the decay function in the above example, the
  344. contour and surface plot of the multiplier looks like this:
  345. image::https://f.cloud.github.com/assets/4320215/768161/082975c0-e899-11e2-86f7-174c3a729d64.png[width="700px"]
  346. image::https://f.cloud.github.com/assets/4320215/768162/0b606884-e899-11e2-907b-aefc77eefef6.png[width="700px"]
  347. ===== Linear' decay, keyword `linear`
  348. When choosing `linear` as the decay function in the above example, the
  349. contour and surface plot of the multiplier looks like this:
  350. image::https://f.cloud.github.com/assets/4320215/768164/1775b0ca-e899-11e2-9f4a-776b406305c6.png[width="700px"]
  351. image::https://f.cloud.github.com/assets/4320215/768165/19d8b1aa-e899-11e2-91bc-6b0553e8d722.png[width="700px"]
  352. ==== Supported fields for decay functions
  353. Only single valued numeric fields, including time and geo locations,
  354. are supported.
  355. ==== What if a field is missing?
  356. If the numeric field is missing in the document, the function will
  357. return 1.
  358. ==== Relation to `custom_boost`, `custom_score` and `custom_filters_score`
  359. The `custom_boost_factor` query
  360. [source,js]
  361. --------------------------------------------------
  362. "custom_boost_factor": {
  363. "boost_factor": 5.2,
  364. "query": {...}
  365. }
  366. --------------------------------------------------
  367. becomes
  368. [source,js]
  369. --------------------------------------------------
  370. "function_score": {
  371. "boost_factor": 5.2,
  372. "query": {...}
  373. }
  374. --------------------------------------------------
  375. The `custom_score` query
  376. [source,js]
  377. --------------------------------------------------
  378. "custom_score": {
  379. "params": {
  380. "param1": 2,
  381. "param2": 3.1
  382. },
  383. "query": {...},
  384. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  385. }
  386. --------------------------------------------------
  387. becomes
  388. [source,js]
  389. --------------------------------------------------
  390. "function_score": {
  391. "boost_mode": "replace",
  392. "query": {...},
  393. "script_score": {
  394. "params": {
  395. "param1": 2,
  396. "param2": 3.1
  397. },
  398. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  399. }
  400. }
  401. --------------------------------------------------
  402. and the `custom_filters_score`
  403. [source,js]
  404. --------------------------------------------------
  405. "custom_filters_score": {
  406. "filters": [
  407. {
  408. "boost": "3",
  409. "filter": {...}
  410. },
  411. {
  412. "filter": {...},
  413. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  414. }
  415. ],
  416. "params": {
  417. "param1": 2,
  418. "param2": 3.1
  419. },
  420. "query": {...},
  421. "score_mode": "first"
  422. }
  423. --------------------------------------------------
  424. becomes:
  425. [source,js]
  426. --------------------------------------------------
  427. "function_score": {
  428. "functions": [
  429. {
  430. "boost_factor": "3",
  431. "filter": {...}
  432. },
  433. {
  434. "filter": {...},
  435. "script_score": {
  436. "params": {
  437. "param1": 2,
  438. "param2": 3.1
  439. },
  440. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  441. }
  442. }
  443. ],
  444. "query": {...},
  445. "score_mode": "first"
  446. }
  447. --------------------------------------------------