script-fields.asciidoc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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,js]
  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. // CONSOLE
  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,js]
  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. // CONSOLE
  54. // TEST[setup:twitter]
  55. Note the `_source` keyword here to navigate the json-like model.
  56. It's important to understand the difference between
  57. `doc['my_field'].value` and `params['_source']['my_field']`. The first,
  58. using the doc keyword, will cause the terms for that field to be loaded to
  59. memory (cached), which will result in faster execution, but more memory
  60. consumption. Also, the `doc[...]` notation only allows for simple valued
  61. fields (you can't return a json object from it) and makes sense only for
  62. non-analyzed or single term based fields. However, using `doc` is
  63. still the recommended way to access values from the document, if at all
  64. possible, because `_source` must be loaded and parsed every time it's used.
  65. Using `_source` is very slow.