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