1
0

function-score-query.asciidoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 with additional capabilities such as distance and recency scoring (see description below).
  11. ==== Using function score
  12. To use `function_score`, the user has to define a query and one or
  13. several functions, that compute a new score for each document returned
  14. by the query.
  15. `function_score` can be used with only one function like this:
  16. [source,js]
  17. --------------------------------------------------
  18. "function_score": {
  19. "(query|filter)": {},
  20. "boost": "boost for the whole query",
  21. "FUNCTION": {},
  22. "boost_mode":"(multiply|replace|...)"
  23. }
  24. --------------------------------------------------
  25. Furthermore, several functions can be combined. In this case one can
  26. optionally choose to apply the function only if a document matches a
  27. given filter:
  28. [source,js]
  29. --------------------------------------------------
  30. "function_score": {
  31. "(query|filter)": {},
  32. "boost": "boost for the whole query",
  33. "functions": [
  34. {
  35. "filter": {},
  36. "FUNCTION": {},
  37. "weight": number
  38. },
  39. {
  40. "FUNCTION": {}
  41. },
  42. {
  43. "filter": {},
  44. "weight": number
  45. }
  46. ],
  47. "max_boost": number,
  48. "score_mode": "(multiply|max|...)",
  49. "boost_mode": "(multiply|replace|...)"
  50. }
  51. --------------------------------------------------
  52. If no filter is given with a function this is equivalent to specifying
  53. `"match_all": {}`
  54. First, each document is scored by the defined functions. The parameter
  55. `score_mode` specifies how the computed scores are combined:
  56. [horizontal]
  57. `multiply`:: scores are multiplied (default)
  58. `sum`:: scores are summed
  59. `avg`:: scores are averaged
  60. `first`:: the first function that has a matching filter
  61. is applied
  62. `max`:: maximum score is used
  63. `min`:: minimum score is used
  64. 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` (coming[1.4.0]). The `weight` can be defined per function in the `functions` array (example above) and is multiplied with the score computed by the respective function.
  65. If weight is given without any other function declaration, `weight` acts as a function that simply returns the `weight`.
  66. The new score can be restricted to not exceed a certain limit by setting
  67. the `max_boost` parameter. The default for `max_boost` is FLT_MAX.
  68. Finally, the newly computed score is combined with the score of the
  69. query. The parameter `boost_mode` defines how:
  70. [horizontal]
  71. `multiply`:: query score and function score is multiplied (default)
  72. `replace`:: only function score is used, the query score is ignored
  73. `sum`:: query score and function score are added
  74. `avg`:: average
  75. `max`:: max of query score and function score
  76. `min`:: min of query score and function score
  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. coming[1.4.0]
  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. ===== Boost factor
  121. deprecated[1.4.0]
  122. Same as `weight`. Use `weight` instead.
  123. ===== Random
  124. The `random_score` generates scores using a hash of the `_uid` field,
  125. with a `seed` for variation. If `seed` is not specified, the current
  126. time is used.
  127. NOTE: Using this feature will load field data for `_uid`, which can
  128. be a memory intensive operation since the values are unique.
  129. [source,js]
  130. --------------------------------------------------
  131. "random_score": {
  132. "seed" : number
  133. }
  134. --------------------------------------------------
  135. ===== Field Value factor
  136. added[1.2.0]
  137. The `field_value_factor` function allows you to use a field from a document to
  138. influence the score. It's similar to using the `script_score` function, however,
  139. it avoids the overhead of scripting. If used on a multi-valued field, only the
  140. first value of the field is used in calculations.
  141. As an example, imagine you have a document indexed with a numeric `popularity`
  142. field and wish to influence the score of a document with this field, an example
  143. doing so would look like:
  144. [source,js]
  145. --------------------------------------------------
  146. "field_value_factor": {
  147. "field": "popularity",
  148. "factor": 1.2,
  149. "modifier": "sqrt"
  150. }
  151. --------------------------------------------------
  152. Which will translate into the following forumla for scoring:
  153. `sqrt(1.2 * doc['popularity'].value)`
  154. There are a number of options for the `field_value_factor` function:
  155. [cols="<,<",options="header",]
  156. |=======================================================================
  157. | Parameter |Description
  158. |`field` |Field to be extracted from the document.
  159. |`factor` |Optional factor to multiply the field value with, defaults to 1.
  160. |`modifier` |Modifier to apply to the field value, can be one of: `none`, `log`,
  161. `log1p`, `log2p`, `ln`, `ln1p`, `ln2p`, `square`, `sqrt`, or `reciprocal`.
  162. Defaults to `none`.
  163. |=======================================================================
  164. Keep in mind that taking the log() of 0, or the square root of a negative number
  165. is an illegal operation, and an exception will be thrown. Be sure to limit the
  166. values of the field with a range filter to avoid this, or use `log1p` and
  167. `ln1p`.
  168. ===== Decay functions
  169. Decay functions score a document with a function that decays depending
  170. on the distance of a numeric field value of the document from a user
  171. given origin. This is similar to a range query, but with smooth edges
  172. instead of boxes.
  173. To use distance scoring on a query that has numerical fields, the user
  174. has to define an `origin` and a `scale` for each field. The `origin`
  175. is needed to define the ``central point'' from which the distance
  176. is calculated, and the `scale` to define the rate of decay. The
  177. decay function is specified as
  178. [source,js]
  179. --------------------------------------------------
  180. "DECAY_FUNCTION": {
  181. "FIELD_NAME": {
  182. "origin": "11, 12",
  183. "scale": "2km",
  184. "offset": "0km",
  185. "decay": 0.33
  186. }
  187. }
  188. --------------------------------------------------
  189. 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:
  190. [source,js]
  191. --------------------------------------------------
  192. "DECAY_FUNCTION": {
  193. "FIELD_NAME": {
  194. "origin": "2013-09-17",
  195. "scale": "10d",
  196. "offset": "5d",
  197. "decay" : 0.5
  198. }
  199. }
  200. --------------------------------------------------
  201. 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.
  202. The `offset` and `decay` parameters are optional.
  203. [horizontal]
  204. `offset`::
  205. If an `offset` is defined, the decay function will only compute the
  206. decay function for documents with a distance greater that the defined
  207. `offset`. The default is 0.
  208. `decay`::
  209. The `decay` parameter defines how documents are scored at the distance
  210. given at `scale`. If no `decay` is defined, documents at the distance
  211. `scale` will be scored 0.5.
  212. In the first example, your documents might represents hotels and contain a geo
  213. location field. You want to compute a decay function depending on how
  214. far the hotel is from a given location. You might not immediately see
  215. what scale to choose for the gauss function, but you can say something
  216. like: "At a distance of 2km from the desired location, the score should
  217. be reduced by one third."
  218. The parameter "scale" will then be adjusted automatically to assure that
  219. the score function computes a score of 0.5 for hotels that are 2km away
  220. from the desired location.
  221. 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.
  222. The `DECAY_FUNCTION` determines the shape of the decay:
  223. [horizontal]
  224. `gauss`::
  225. Normal decay, computed as:
  226. +
  227. image:images/Gaussian.png[]
  228. where image:images/sigma.png[] is computed to assure that the score takes the value `decay` at distance `scale` from `origin`+-`offset`
  229. image:images/sigma_calc.png[]
  230. [horizontal]
  231. `exp`::
  232. Exponential decay, computed as:
  233. +
  234. image:images/Exponential.png[]
  235. 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`
  236. image:images/lambda_calc.png[]
  237. [horizontal]
  238. `linear`::
  239. Linear decay, computed as:
  240. +
  241. image:images/Linear.png[].
  242. where again the parameter `s` is computed to assure that the score takes the value `decay` at distance `scale` from `origin`+-`offset`
  243. image:images/s_calc.png[]
  244. In contrast to the normal and exponential decay, this function actually
  245. sets the score to 0 if the field value exceeds twice the user given
  246. scale value.
  247. ===== Multiple values:
  248. 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.
  249. This can be changed by setting `multi_value_mode`.
  250. [horizontal]
  251. `min`:: Distance is the minimum distance
  252. `max`:: Distance is the maximum distance
  253. `avg`:: Distance is the average distance
  254. `sum`:: Distance is the sum of all distances
  255. Example:
  256. [source,js]
  257. --------------------------------------------------
  258. "DECAY_FUNCTION": {
  259. "FIELD_NAME": {
  260. "origin": ...,
  261. "scale": ...
  262. },
  263. "multi_value_mode": "avg"
  264. }
  265. --------------------------------------------------
  266. ==== Detailed example
  267. Suppose you are searching for a hotel in a certain town. Your budget is
  268. limited. Also, you would like the hotel to be close to the town center,
  269. so the farther the hotel is from the desired location the less likely
  270. you are to check in.
  271. You would like the query results that match your criterion (for
  272. example, "hotel, Nancy, non-smoker") to be scored with respect to
  273. distance to the town center and also the price.
  274. Intuitively, you would like to define the town center as the origin and
  275. maybe you are willing to walk 2km to the town center from the hotel. +
  276. In this case your *origin* for the location field is the town center
  277. and the *scale* is ~2km.
  278. If your budget is low, you would probably prefer something cheap above
  279. something expensive. For the price field, the *origin* would be 0 Euros
  280. and the *scale* depends on how much you are willing to pay, for example 20 Euros.
  281. In this example, the fields might be called "price" for the price of the
  282. hotel and "location" for the coordinates of this hotel.
  283. The function for `price` in this case would be
  284. [source,js]
  285. --------------------------------------------------
  286. "DECAY_FUNCTION": {
  287. "price": {
  288. "origin": "0",
  289. "scale": "20"
  290. }
  291. }
  292. --------------------------------------------------
  293. and for `location`:
  294. [source,js]
  295. --------------------------------------------------
  296. "DECAY_FUNCTION": {
  297. "location": {
  298. "origin": "11, 12",
  299. "scale": "2km"
  300. }
  301. }
  302. --------------------------------------------------
  303. where `DECAY_FUNCTION` can be "linear", "exp" and "gauss".
  304. Suppose you want to multiply these two functions on the original score,
  305. the request would look like this:
  306. [source,js]
  307. --------------------------------------------------
  308. curl 'localhost:9200/hotels/_search/' -d '{
  309. "query": {
  310. "function_score": {
  311. "functions": [
  312. {
  313. "DECAY_FUNCTION": {
  314. "price": {
  315. "origin": "0",
  316. "scale": "20"
  317. }
  318. }
  319. },
  320. {
  321. "DECAY_FUNCTION": {
  322. "location": {
  323. "origin": "11, 12",
  324. "scale": "2km"
  325. }
  326. }
  327. }
  328. ],
  329. "query": {
  330. "match": {
  331. "properties": "balcony"
  332. }
  333. },
  334. "score_mode": "multiply"
  335. }
  336. }
  337. }'
  338. --------------------------------------------------
  339. Next, we show how the computed score looks like for each of the three
  340. possible decay functions.
  341. ===== Normal decay, keyword `gauss`
  342. When choosing `gauss` as the decay function in the above example, the
  343. contour and surface plot of the multiplier looks like this:
  344. image::https://f.cloud.github.com/assets/4320215/768157/cd0e18a6-e898-11e2-9b3c-f0145078bd6f.png[width="700px"]
  345. image::https://f.cloud.github.com/assets/4320215/768160/ec43c928-e898-11e2-8e0d-f3c4519dbd89.png[width="700px"]
  346. Suppose your original search results matches three hotels :
  347. * "Backback Nap"
  348. * "Drink n Drive"
  349. * "BnB Bellevue".
  350. "Drink n Drive" is pretty far from your defined location (nearly 2 km)
  351. and is not too cheap (about 13 Euros) so it gets a low factor a factor
  352. of 0.56. "BnB Bellevue" and "Backback Nap" are both pretty close to the
  353. defined location but "BnB Bellevue" is cheaper, so it gets a multiplier
  354. of 0.86 whereas "Backpack Nap" gets a value of 0.66.
  355. ===== Exponential decay, keyword `exp`
  356. When choosing `exp` as the decay function in the above example, the
  357. contour and surface plot of the multiplier looks like this:
  358. image::https://f.cloud.github.com/assets/4320215/768161/082975c0-e899-11e2-86f7-174c3a729d64.png[width="700px"]
  359. image::https://f.cloud.github.com/assets/4320215/768162/0b606884-e899-11e2-907b-aefc77eefef6.png[width="700px"]
  360. ===== Linear' decay, keyword `linear`
  361. When choosing `linear` as the decay function in the above example, the
  362. contour and surface plot of the multiplier looks like this:
  363. image::https://f.cloud.github.com/assets/4320215/768164/1775b0ca-e899-11e2-9f4a-776b406305c6.png[width="700px"]
  364. image::https://f.cloud.github.com/assets/4320215/768165/19d8b1aa-e899-11e2-91bc-6b0553e8d722.png[width="700px"]
  365. ==== Supported fields for decay functions
  366. Only single valued numeric fields, including time and geo locations,
  367. are supported.
  368. ==== What if a field is missing?
  369. If the numeric field is missing in the document, the function will
  370. return 1.
  371. ==== Relation to `custom_boost`, `custom_score` and `custom_filters_score`
  372. The `custom_boost_factor` query
  373. [source,js]
  374. --------------------------------------------------
  375. "custom_boost_factor": {
  376. "boost_factor": 5.2,
  377. "query": {...}
  378. }
  379. --------------------------------------------------
  380. becomes
  381. [source,js]
  382. --------------------------------------------------
  383. "function_score": {
  384. "weight": 5.2,
  385. "query": {...}
  386. }
  387. --------------------------------------------------
  388. The `custom_score` query
  389. [source,js]
  390. --------------------------------------------------
  391. "custom_score": {
  392. "params": {
  393. "param1": 2,
  394. "param2": 3.1
  395. },
  396. "query": {...},
  397. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  398. }
  399. --------------------------------------------------
  400. becomes
  401. [source,js]
  402. --------------------------------------------------
  403. "function_score": {
  404. "boost_mode": "replace",
  405. "query": {...},
  406. "script_score": {
  407. "params": {
  408. "param1": 2,
  409. "param2": 3.1
  410. },
  411. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  412. }
  413. }
  414. --------------------------------------------------
  415. and the `custom_filters_score`
  416. [source,js]
  417. --------------------------------------------------
  418. "custom_filters_score": {
  419. "filters": [
  420. {
  421. "boost": "3",
  422. "filter": {...}
  423. },
  424. {
  425. "filter": {...},
  426. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  427. }
  428. ],
  429. "params": {
  430. "param1": 2,
  431. "param2": 3.1
  432. },
  433. "query": {...},
  434. "score_mode": "first"
  435. }
  436. --------------------------------------------------
  437. becomes:
  438. [source,js]
  439. --------------------------------------------------
  440. "function_score": {
  441. "functions": [
  442. {
  443. "weight": "3",
  444. "filter": {...}
  445. },
  446. {
  447. "filter": {...},
  448. "script_score": {
  449. "params": {
  450. "param1": 2,
  451. "param2": 3.1
  452. },
  453. "script": "_score * doc['my_numeric_field'].value / pow(param1, param2)"
  454. }
  455. }
  456. ],
  457. "query": {...},
  458. "score_mode": "first"
  459. }
  460. --------------------------------------------------