function-score-query.asciidoc 16 KB

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