script-fields.asciidoc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. [[search-request-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['my_field_name'].value * 2"
  17. }
  18. },
  19. "test2" : {
  20. "script" : {
  21. "lang": "painless",
  22. "source": "doc['my_field_name'].value * params.factor",
  23. "params" : {
  24. "factor" : 2.0
  25. }
  26. }
  27. }
  28. }
  29. }
  30. --------------------------------------------------
  31. // CONSOLE
  32. Script fields can work on fields that are not stored (`my_field_name` 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,js]
  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. // CONSOLE
  53. // TEST[setup:twitter]
  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.