function-score-query.asciidoc 17 KB

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