function-score-query.asciidoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. [[query-dsl-function-score-query]]
  2. === Function Score Query
  3. added[0.90.4]
  4. The `function_score` allows you to modify the score of documents that are
  5. retrieved by a query. This can be useful if, for example, a score
  6. function is computationally expensive and it is sufficient to compute
  7. the score on a filtered set of documents.
  8. `function_score` provides the same functionality that
  9. <<query-dsl-custom-boost-factor-query>>,
  10. <<query-dsl-custom-score-query>> and
  11. <<query-dsl-custom-filters-score-query>> provided
  12. but furthermore adds futher scoring functionality such as
  13. distance and recency scoring (see description below).
  14. ==== Using function score
  15. To use `function_score`, the user has to define a query and one or
  16. several functions, that compute a new score for each document returned
  17. by the query.
  18. `function_score` can be used with only one function like this:
  19. [source,js]
  20. --------------------------------------------------
  21. "function_score": {
  22. "(query|filter)": {},
  23. "boost": "boost for the whole query",
  24. "FUNCTION": {},
  25. "boost_mode":"(multiply|replace|...)"
  26. }
  27. --------------------------------------------------
  28. Furthermore, several functions can be combined. In this case one can
  29. optionally choose to apply the function only if a document matches a
  30. given filter:
  31. [source,js]
  32. --------------------------------------------------
  33. "function_score": {
  34. "(query|filter)": {},
  35. "boost": "boost for the whole query",
  36. "functions": [
  37. {
  38. "filter": {},
  39. "FUNCTION": {}
  40. },
  41. {
  42. "FUNCTION": {}
  43. }
  44. ],
  45. "max_boost": number,
  46. "score_mode": "(multiply|max|...)",
  47. "boost_mode": "(multiply|replace|...)"
  48. }
  49. --------------------------------------------------
  50. If no filter is given with a function this is equivalent to specifying
  51. `"match_all": {}`
  52. First, each document is scored by the defined functons. 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. 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 <<query-dsl-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. ===== Boost factor
  107. The `boost_factor` score allows you to multiply the score by the provided
  108. `boost_factor`. 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. "boost_factor" : number
  114. --------------------------------------------------
  115. ===== Random
  116. The `random_score` generates scores via a pseudo random number algorithm
  117. that is initialized with a `seed`.
  118. [source,js]
  119. --------------------------------------------------
  120. "random_score": {
  121. "seed" : number
  122. }
  123. --------------------------------------------------
  124. ===== Decay functions
  125. Decay functions score a document with a function that decays depending
  126. on the distance of a numeric field value of the document from a user
  127. given origin. This is similar to a range query, but with smooth edges
  128. instead of boxes.
  129. To use distance scoring on a query that has numerical fields, the user
  130. has to define an `origin` and a `scale` for each field. The `origin`
  131. is needed to define the ``central point'' from which the distance
  132. is calculated, and the `scale` to define the rate of decay. The
  133. decay function is specified as
  134. [source,js]
  135. --------------------------------------------------
  136. "DECAY_FUNCTION": {
  137. "FIELD_NAME": {
  138. "origin": "11, 12",
  139. "scale": "2km",
  140. "offset": "0km",
  141. "decay": 0.33
  142. }
  143. }
  144. --------------------------------------------------
  145. 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:
  146. [source,js]
  147. --------------------------------------------------
  148. "DECAY_FUNCTION": {
  149. "FIELD_NAME": {
  150. "origin": "2013-09-17",
  151. "scale": "10d",
  152. "offset": "5d",
  153. "decay" : 0.5
  154. }
  155. }
  156. --------------------------------------------------
  157. 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.
  158. The `offset` and `decay` parameters are optional.
  159. [horizontal]
  160. `offset`::
  161. If an `offset` is defined, the decay function will only compute a the
  162. decay function for documents with a distance greater that the defined
  163. `offset`. The default is 0.
  164. `decay`::
  165. The `decay` parameter defines how documents are scored at the distance
  166. given at `scale`. If no `decay` is defined, documents at the distance
  167. `scale` will be scored 0.5.
  168. In the first example, your documents might represents hotels and contain a geo
  169. location field. You want to compute a decay function depending on how
  170. far the hotel is from a given location. You might not immediately see
  171. what scale to choose for the gauss function, but you can say something
  172. like: "At a distance of 2km from the desired location, the score should
  173. be reduced by one third."
  174. The parameter "scale" will then be adjusted automatically to assure that
  175. the score function computes a score of 0.5 for hotels that are 2km away
  176. from the desired location.
  177. 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.
  178. The `DECAY_FUNCTION` determines the shape of the decay:
  179. [horizontal]
  180. `gauss`::
  181. Normal decay, computed as:
  182. +
  183. image:images/Gaussian.png[]
  184. `exp`::
  185. Exponential decay, computed as:
  186. +
  187. image:images/Exponential.png[]
  188. `linear`::
  189. Linear decay, computed as:
  190. +
  191. image:images/Linear.png[].
  192. +
  193. In contrast to the normal and exponential decay, this function actually
  194. sets the score to 0 if the field value exceeds twice the user given
  195. scale value.
  196. ==== Detailed example
  197. Suppose you are searching for a hotel in a certain town. Your budget is
  198. limited. Also, you would like the hotel to be close to the town center,
  199. so the farther the hotel is from the desired location the less likely
  200. you are to check in.
  201. You would like the query results that match your criterion (for
  202. example, "hotel, Nancy, non-smoker") to be scored with respect to
  203. distance to the town center and also the price.
  204. Intuitively, you would like to define the town center as the origin and
  205. maybe you are willing to walk 2km to the town center from the hotel. +
  206. In this case your *origin* for the location field is the town center
  207. and the *scale* is ~2km.
  208. If your budget is low, you would probably prefer something cheap above
  209. something expensive. For the price field, the *origin* would be 0 Euros
  210. and the *scale* depends on how much you are willing to pay, for example 20 Euros.
  211. In this example, the fields might be called "price" for the price of the
  212. hotel and "location" for the coordinates of this hotel.
  213. The function for `price` in this case would be
  214. [source,js]
  215. --------------------------------------------------
  216. "DECAY_FUNCTION": {
  217. "price": {
  218. "origin": "0",
  219. "scale": "20"
  220. }
  221. }
  222. --------------------------------------------------
  223. and for `location`:
  224. [source,js]
  225. --------------------------------------------------
  226. "DECAY_FUNCTION": {
  227. "location": {
  228. "origin": "11, 12",
  229. "scale": "2km"
  230. }
  231. }
  232. --------------------------------------------------
  233. where `DECAY_FUNCTION` can be "linear", "exp" and "gauss".
  234. Suppose you want to multiply these two functions on the original score,
  235. the request would look like this:
  236. [source,js]
  237. --------------------------------------------------
  238. curl 'localhost:9200/hotels/_search/' -d '{
  239. "query": {
  240. "function_score": {
  241. "functions": [
  242. {
  243. "DECAY_FUNCTION": {
  244. "price": {
  245. "origin": "0",
  246. "scale": "20"
  247. }
  248. }
  249. },
  250. {
  251. "DECAY_FUNCTION": {
  252. "location": {
  253. "origin": "11, 12",
  254. "scale": "2km"
  255. }
  256. }
  257. }
  258. ],
  259. "query": {
  260. "match": {
  261. "properties": "balcony"
  262. }
  263. },
  264. "score_mode": "multiply"
  265. }
  266. }
  267. }'
  268. --------------------------------------------------
  269. Next, we show how the computed score looks like for each of the three
  270. possible decay functions.
  271. ===== Normal decay, keyword `gauss`
  272. When choosing `gauss` as the decay function in the above example, the
  273. contour and surface plot of the multiplier looks like this:
  274. image::https://f.cloud.github.com/assets/4320215/768157/cd0e18a6-e898-11e2-9b3c-f0145078bd6f.png[width="700px"]
  275. image::https://f.cloud.github.com/assets/4320215/768160/ec43c928-e898-11e2-8e0d-f3c4519dbd89.png[width="700px"]
  276. Suppose your original search results matches three hotels :
  277. * "Backback Nap"
  278. * "Drink n Drive"
  279. * "BnB Bellevue".
  280. "Drink n Drive" is pretty far from your defined location (nearly 2 km)
  281. and is not too cheap (about 13 Euros) so it gets a low factor a factor
  282. of 0.56. "BnB Bellevue" and "Backback Nap" are both pretty close to the
  283. defined location but "BnB Bellevue" is cheaper, so it gets a multiplier
  284. of 0.86 whereas "Backpack Nap" gets a value of 0.66.
  285. ===== Exponential decay, keyword `exp`
  286. When choosing `exp` as the decay function in the above example, the
  287. contour and surface plot of the multiplier looks like this:
  288. image::https://f.cloud.github.com/assets/4320215/768161/082975c0-e899-11e2-86f7-174c3a729d64.png[width="700px"]
  289. image::https://f.cloud.github.com/assets/4320215/768162/0b606884-e899-11e2-907b-aefc77eefef6.png[width="700px"]
  290. ===== Linear' decay, keyword `linear`
  291. When choosing `linear` as the decay function in the above example, the
  292. contour and surface plot of the multiplier looks like this:
  293. image::https://f.cloud.github.com/assets/4320215/768164/1775b0ca-e899-11e2-9f4a-776b406305c6.png[width="700px"]
  294. image::https://f.cloud.github.com/assets/4320215/768165/19d8b1aa-e899-11e2-91bc-6b0553e8d722.png[width="700px"]
  295. ==== Supported fields for decay functions
  296. Only single valued numeric fields, including time and geo locations,
  297. are supported.
  298. ==== What is a field is missing?
  299. If the numeric field is missing in the document, the function will
  300. return 1.
  301. ==== Relation to `custom_boost`, `custom_score` and `custom_filters_score`
  302. The <<query-dsl-custom-boost-factor-query>>
  303. [source,js]
  304. --------------------------------------------------
  305. "custom_boost_factor": {
  306. "boost_factor": 5.2,
  307. "query": {...}
  308. }
  309. --------------------------------------------------
  310. becomes
  311. [source,js]
  312. --------------------------------------------------
  313. "function_score": {
  314. "boost_factor": 5.2,
  315. "query": {...}
  316. }
  317. --------------------------------------------------
  318. The <<query-dsl-custom-score-query>>
  319. [source,js]
  320. --------------------------------------------------
  321. "custom_score": {
  322. "params": {
  323. "param1": 2,
  324. "param2": 3.1
  325. },
  326. "query": {...},
  327. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  328. }
  329. --------------------------------------------------
  330. becomes
  331. [source,js]
  332. --------------------------------------------------
  333. "function_score": {
  334. "boost_mode": "replace",
  335. "query": {...},
  336. "script_score": {
  337. "params": {
  338. "param1": 2,
  339. "param2": 3.1
  340. },
  341. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  342. }
  343. }
  344. --------------------------------------------------
  345. and the <<query-dsl-custom-filters-score-query>>
  346. [source,js]
  347. --------------------------------------------------
  348. "custom_filters_score": {
  349. "filters": [
  350. {
  351. "boost_factor": "3",
  352. "filter": {...}
  353. },
  354. {
  355. "filter": {…},
  356. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  357. }
  358. ],
  359. "params": {
  360. "param1": 2,
  361. "param2": 3.1
  362. },
  363. "query": {...},
  364. "score_mode": "first"
  365. }
  366. --------------------------------------------------
  367. becomes:
  368. [source,js]
  369. --------------------------------------------------
  370. "function_score": {
  371. "functions": [
  372. {
  373. "boost_factor": "3",
  374. "filter": {...}
  375. },
  376. {
  377. "filter": {...},
  378. "script_score": {
  379. "params": {
  380. "param1": 2,
  381. "param2": 3.1
  382. },
  383. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  384. }
  385. }
  386. ],
  387. "query": {...},
  388. "score_mode": "first"
  389. }
  390. --------------------------------------------------