function-score-query.asciidoc 16 KB

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