script-fields.asciidoc 2.2 KB

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