function-score-query.asciidoc 22 KB

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