script-score-query.asciidoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. [[query-dsl-script-score-query]]
  2. === Script Score Query
  3. experimental[]
  4. The `script_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. To use `script_score`, you have to define a query and a script -
  9. a function to be used to compute a new score for each document returned
  10. by the query. For more information on scripting see
  11. <<modules-scripting, scripting documentation>>.
  12. Here is an example of using `script_score` to assign each matched document
  13. a score equal to the number of likes divided by 10:
  14. [source,js]
  15. --------------------------------------------------
  16. GET /_search
  17. {
  18. "query" : {
  19. "script_score" : {
  20. "query" : {
  21. "match": { "message": "elasticsearch" }
  22. },
  23. "script" : {
  24. "source" : "doc['likes'].value / 10 "
  25. }
  26. }
  27. }
  28. }
  29. --------------------------------------------------
  30. // CONSOLE
  31. // TEST[setup:twitter]
  32. NOTE: The values returned from `script_score` cannot be negative. In general,
  33. Lucene requires the scores produced by queries to be non-negative in order to
  34. support certain search optimizations.
  35. ==== Accessing the score of a document within a script
  36. Within a script, you can
  37. {ref}/modules-scripting-fields.html#scripting-score[access]
  38. the `_score` variable which represents the current relevance score of a
  39. document.
  40. ==== Predefined functions within a Painless script
  41. You can use any of the available
  42. <<painless-api-reference, painless functions>> in the painless script.
  43. Besides these functions, there are a number of predefined functions
  44. that can help you with scoring. We suggest you to use them instead of
  45. rewriting equivalent functions of your own, as these functions try
  46. to be the most efficient by using the internal mechanisms.
  47. ===== saturation
  48. `saturation(value,k) = value/(k + value)`
  49. [source,js]
  50. --------------------------------------------------
  51. "script" : {
  52. "source" : "saturation(doc['likes'].value, 1)"
  53. }
  54. --------------------------------------------------
  55. // NOTCONSOLE
  56. ===== sigmoid
  57. `sigmoid(value, k, a) = value^a/ (k^a + value^a)`
  58. [source,js]
  59. --------------------------------------------------
  60. "script" : {
  61. "source" : "sigmoid(doc['likes'].value, 2, 1)"
  62. }
  63. --------------------------------------------------
  64. // NOTCONSOLE
  65. [[vector-functions]]
  66. ===== Functions for vector fields
  67. These functions are used for
  68. for <<dense-vector,`dense_vector`>> and
  69. <<sparse-vector,`sparse_vector`>> fields.
  70. For dense_vector fields, `cosineSimilarity` calculates the measure of
  71. cosine similarity between a given query vector and document vectors.
  72. [source,js]
  73. --------------------------------------------------
  74. {
  75. "query": {
  76. "script_score": {
  77. "query": {
  78. "match_all": {}
  79. },
  80. "script": {
  81. "source": "cosineSimilarity(params.query_vector, doc['my_dense_vector']) + 1.0" <1>,
  82. "params": {
  83. "query_vector": [4, 3.4, -0.2] <2>
  84. }
  85. }
  86. }
  87. }
  88. }
  89. --------------------------------------------------
  90. // NOTCONSOLE
  91. <1> The script adds 1.0 to the cosine similarity to prevent the score from being negative.
  92. <2> To take advantage of the script optimizations, provide a query vector as a script parameter.
  93. Similarly, for sparse_vector fields, `cosineSimilaritySparse` calculates cosine similarity
  94. between a given query vector and document vectors.
  95. [source,js]
  96. --------------------------------------------------
  97. {
  98. "query": {
  99. "script_score": {
  100. "query": {
  101. "match_all": {}
  102. },
  103. "script": {
  104. "source": "cosineSimilaritySparse(params.query_vector, doc['my_sparse_vector']) + 1.0",
  105. "params": {
  106. "query_vector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
  107. }
  108. }
  109. }
  110. }
  111. }
  112. --------------------------------------------------
  113. // NOTCONSOLE
  114. For dense_vector fields, `dotProduct` calculates the measure of
  115. dot product between a given query vector and document vectors.
  116. [source,js]
  117. --------------------------------------------------
  118. {
  119. "query": {
  120. "script_score": {
  121. "query": {
  122. "match_all": {}
  123. },
  124. "script": {
  125. "source": """
  126. double value = dotProduct(params.query_vector, doc['my_vector']);
  127. return sigmoid(1, Math.E, -value); <1>
  128. """,
  129. "params": {
  130. "query_vector": [4, 3.4, -0.2]
  131. }
  132. }
  133. }
  134. }
  135. }
  136. --------------------------------------------------
  137. // NOTCONSOLE
  138. <1> Using the standard sigmoid function prevents scores from being negative.
  139. Similarly, for sparse_vector fields, `dotProductSparse` calculates dot product
  140. between a given query vector and document vectors.
  141. [source,js]
  142. --------------------------------------------------
  143. {
  144. "query": {
  145. "script_score": {
  146. "query": {
  147. "match_all": {}
  148. },
  149. "script": {
  150. "source": """
  151. double value = dotProductSparse(params.query_vector, doc['my_sparse_vector']);
  152. return sigmoid(1, Math.E, -value);
  153. """,
  154. "params": {
  155. "query_vector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
  156. }
  157. }
  158. }
  159. }
  160. }
  161. --------------------------------------------------
  162. // NOTCONSOLE
  163. NOTE: If a document doesn't have a value for a vector field on which
  164. a vector function is executed, 0 is returned as a result
  165. for this document.
  166. NOTE: If a document's dense vector field has a number of dimensions
  167. different from the query's vector, 0 is used for missing dimensions
  168. in the calculations of vector functions.
  169. [[random-score-function]]
  170. ===== Random score function
  171. `random_score` function generates scores that are uniformly distributed
  172. from 0 up to but not including 1.
  173. `randomScore` function has the following syntax:
  174. `randomScore(<seed>, <fieldName>)`.
  175. It has a required parameter - `seed` as an integer value,
  176. and an optional parameter - `fieldName` as a string value.
  177. [source,js]
  178. --------------------------------------------------
  179. "script" : {
  180. "source" : "randomScore(100, '_seq_no')"
  181. }
  182. --------------------------------------------------
  183. // NOTCONSOLE
  184. If the `fieldName` parameter is omitted, the internal Lucene
  185. document ids will be used as a source of randomness. This is very efficient,
  186. but unfortunately not reproducible since documents might be renumbered
  187. by merges.
  188. [source,js]
  189. --------------------------------------------------
  190. "script" : {
  191. "source" : "randomScore(100)"
  192. }
  193. --------------------------------------------------
  194. // NOTCONSOLE
  195. Note that documents that are within the same shard and have the
  196. same value for field will get the same score, so it is usually desirable
  197. to use a field that has unique values for all documents across a shard.
  198. A good default choice might be to use the `_seq_no`
  199. field, whose only drawback is that scores will change if the document is
  200. updated since update operations also update the value of the `_seq_no` field.
  201. [[decay-functions]]
  202. ===== Decay functions for numeric fields
  203. You can read more about decay functions
  204. {ref}/query-dsl-function-score-query.html#function-decay[here].
  205. * `double decayNumericLinear(double origin, double scale, double offset, double decay, double docValue)`
  206. * `double decayNumericExp(double origin, double scale, double offset, double decay, double docValue)`
  207. * `double decayNumericGauss(double origin, double scale, double offset, double decay, double docValue)`
  208. [source,js]
  209. --------------------------------------------------
  210. "script" : {
  211. "source" : "decayNumericLinear(params.origin, params.scale, params.offset, params.decay, doc['dval'].value)",
  212. "params": { <1>
  213. "origin": 20,
  214. "scale": 10,
  215. "decay" : 0.5,
  216. "offset" : 0
  217. }
  218. }
  219. --------------------------------------------------
  220. // NOTCONSOLE
  221. <1> Using `params` allows to compile the script only once, even if params change.
  222. ===== Decay functions for geo fields
  223. * `double decayGeoLinear(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)`
  224. * `double decayGeoExp(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)`
  225. * `double decayGeoGauss(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)`
  226. [source,js]
  227. --------------------------------------------------
  228. "script" : {
  229. "source" : "decayGeoExp(params.origin, params.scale, params.offset, params.decay, doc['location'].value)",
  230. "params": {
  231. "origin": "40, -70.12",
  232. "scale": "200km",
  233. "offset": "0km",
  234. "decay" : 0.2
  235. }
  236. }
  237. --------------------------------------------------
  238. // NOTCONSOLE
  239. ===== Decay functions for date fields
  240. * `double decayDateLinear(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)`
  241. * `double decayDateExp(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)`
  242. * `double decayDateGauss(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)`
  243. [source,js]
  244. --------------------------------------------------
  245. "script" : {
  246. "source" : "decayDateGauss(params.origin, params.scale, params.offset, params.decay, doc['date'].value)",
  247. "params": {
  248. "origin": "2008-01-01T01:00:00Z",
  249. "scale": "1h",
  250. "offset" : "0",
  251. "decay" : 0.5
  252. }
  253. }
  254. --------------------------------------------------
  255. // NOTCONSOLE
  256. NOTE: Decay functions on dates are limited to dates in the default format
  257. and default time zone. Also calculations with `now` are not supported.
  258. ==== Faster alternatives
  259. Script Score Query calculates the score for every hit (matching document).
  260. There are faster alternative query types that can efficiently skip
  261. non-competitive hits:
  262. * If you want to boost documents on some static fields, use
  263. <<query-dsl-rank-feature-query, Rank Feature Query>>.
  264. ==== Transition from Function Score Query
  265. We are deprecating <<query-dsl-function-score-query, Function Score>>, and
  266. Script Score Query will be a substitute for it.
  267. Here we describe how Function Score Query's functions can be
  268. equivalently implemented in Script Score Query:
  269. ===== `script_score`
  270. What you used in `script_score` of the Function Score query, you
  271. can copy into the Script Score query. No changes here.
  272. ===== `weight`
  273. `weight` function can be implemented in the Script Score query through
  274. the following script:
  275. [source,js]
  276. --------------------------------------------------
  277. "script" : {
  278. "source" : "params.weight * _score",
  279. "params": {
  280. "weight": 2
  281. }
  282. }
  283. --------------------------------------------------
  284. // NOTCONSOLE
  285. ===== `random_score`
  286. Use `randomScore` function
  287. as described in <<random-score-function, random score function>>.
  288. ===== `field_value_factor`
  289. `field_value_factor` function can be easily implemented through script:
  290. [source,js]
  291. --------------------------------------------------
  292. "script" : {
  293. "source" : "Math.log10(doc['field'].value * params.factor)",
  294. params" : {
  295. "factor" : 5
  296. }
  297. }
  298. --------------------------------------------------
  299. // NOTCONSOLE
  300. For checking if a document has a missing value, you can use
  301. `doc['field'].size() == 0`. For example, this script will use
  302. a value `1` if a document doesn't have a field `field`:
  303. [source,js]
  304. --------------------------------------------------
  305. "script" : {
  306. "source" : "Math.log10((doc['field'].size() == 0 ? 1 : doc['field'].value()) * params.factor)",
  307. params" : {
  308. "factor" : 5
  309. }
  310. }
  311. --------------------------------------------------
  312. // NOTCONSOLE
  313. This table lists how `field_value_factor` modifiers can be implemented
  314. through a script:
  315. [cols="<,<",options="header",]
  316. |=======================================================================
  317. | Modifier | Implementation in Script Score
  318. | `none` | -
  319. | `log` | `Math.log10(doc['f'].value)`
  320. | `log1p` | `Math.log10(doc['f'].value + 1)`
  321. | `log2p` | `Math.log10(doc['f'].value + 2)`
  322. | `ln` | `Math.log(doc['f'].value)`
  323. | `ln1p` | `Math.log(doc['f'].value + 1)`
  324. | `ln2p` | `Math.log(doc['f'].value + 2)`
  325. | `square` | `Math.pow(doc['f'].value, 2)`
  326. | `sqrt` | `Math.sqrt(doc['f'].value)`
  327. | `reciprocal` | `1.0 / doc['f'].value`
  328. |=======================================================================
  329. ===== `decay functions`
  330. Script Score query has equivalent <<decay-functions, decay functions>>
  331. that can be used in script.