script-fields.asciidoc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. [discrete]
  2. [[script-fields]]
  3. === Script fields
  4. You can use the `script_fields` parameter to retrieve a <<modules-scripting,script
  5. evaluation>> (based on different fields) for each hit. For example:
  6. [source,console]
  7. --------------------------------------------------
  8. GET /_search
  9. {
  10. "query": {
  11. "match_all": {}
  12. },
  13. "script_fields": {
  14. "test1": {
  15. "script": {
  16. "lang": "painless",
  17. "source": "doc['price'].value * 2"
  18. }
  19. },
  20. "test2": {
  21. "script": {
  22. "lang": "painless",
  23. "source": "doc['price'].value * params.factor",
  24. "params": {
  25. "factor": 2.0
  26. }
  27. }
  28. }
  29. }
  30. }
  31. --------------------------------------------------
  32. // TEST[setup:sales]
  33. Script fields can work on fields that are not stored (`price` in
  34. the above case), and allow to return custom values to be returned (the
  35. evaluated value of the script).
  36. Script fields can also access the actual `_source` document and
  37. extract specific elements to be returned from it by using `params['_source']`.
  38. Here is an example:
  39. [source,console]
  40. --------------------------------------------------
  41. GET /_search
  42. {
  43. "query" : {
  44. "match_all": {}
  45. },
  46. "script_fields" : {
  47. "test1" : {
  48. "script" : "params['_source']['message']"
  49. }
  50. }
  51. }
  52. --------------------------------------------------
  53. // TEST[setup:my_index]
  54. Note the `_source` keyword here to navigate the json-like model.
  55. It's important to understand the difference between
  56. `doc['my_field'].value` and `params['_source']['my_field']`. The first,
  57. using the doc keyword, will cause the terms for that field to be loaded to
  58. memory (cached), which will result in faster execution, but more memory
  59. consumption. Also, the `doc[...]` notation only allows for simple valued
  60. fields (you can't return a json object from it) and makes sense only for
  61. non-analyzed or single term based fields. However, using `doc` is
  62. still the recommended way to access values from the document, if at all
  63. possible, because `_source` must be loaded and parsed every time it's used.
  64. Using `_source` is very slow.