script-fields.asciidoc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. {
  8. "query" : {
  9. ...
  10. },
  11. "script_fields" : {
  12. "test1" : {
  13. "script" : "doc['my_field_name'].value * 2"
  14. },
  15. "test2" : {
  16. "script" : "doc['my_field_name'].value * factor",
  17. "params" : {
  18. "factor" : 2.0
  19. }
  20. }
  21. }
  22. }
  23. --------------------------------------------------
  24. Script fields can work on fields that are not stored (`my_field_name` in
  25. the above case), and allow to return custom values to be returned (the
  26. evaluated value of the script).
  27. Script fields can also access the actual `_source` document indexed and
  28. extract specific elements to be returned from it (can be an "object"
  29. type). Here is an example:
  30. [source,js]
  31. --------------------------------------------------
  32. {
  33. "query" : {
  34. ...
  35. },
  36. "script_fields" : {
  37. "test1" : {
  38. "script" : "_source.obj1.obj2"
  39. }
  40. }
  41. }
  42. --------------------------------------------------
  43. Note the `_source` keyword here to navigate the json-like model.
  44. It's important to understand the difference between
  45. `doc['my_field'].value` and `_source.my_field`. The first, using the doc
  46. keyword, will cause the terms for that field to be loaded to memory
  47. (cached), which will result in faster execution, but more memory
  48. consumption. Also, the `doc[...]` notation only allows for simple valued
  49. fields (can't return a json object from it) and make sense only on
  50. non-analyzed or single term based fields.
  51. The `_source` on the other hand causes the source to be loaded, parsed,
  52. and then only the relevant part of the json is returned.