function-score-query.asciidoc 19 KB

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