native.asciidoc 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. [[modules-scripting-native]]
  2. === Native (Java) Scripts
  3. Sometimes `painless` and <<modules-scripting-expression, expression>> aren't enough. For those times you can
  4. implement a native script.
  5. The best way to implement a native script is to write a plugin and install it.
  6. The plugin {plugins}/plugin-authors.html[documentation] has more information on
  7. how to write a plugin so that Elasticsearch will properly load it.
  8. To register the actual script you'll need to implement `NativeScriptFactory`
  9. to construct the script. The actual script will extend either
  10. `AbstractExecutableScript` or `AbstractSearchScript`. The second one is likely
  11. the most useful and has several helpful subclasses you can extend like
  12. `AbstractLongSearchScript` and `AbstractDoubleSearchScript`.
  13. Finally, your plugin should register the native script by implementing the
  14. `ScriptPlugin` interface.
  15. If you squashed the whole thing into one class it'd look like:
  16. [source,java]
  17. --------------------------------------------------
  18. public class MyNativeScriptPlugin extends Plugin implements ScriptPlugin {
  19. @Override
  20. public List<NativeScriptFactory> getNativeScripts() {
  21. return Collections.singletonList(new MyNativeScriptFactory());
  22. }
  23. public static class MyNativeScriptFactory implements NativeScriptFactory {
  24. @Override
  25. public ExecutableScript newScript(@Nullable Map<String, Object> params) {
  26. return new MyNativeScript();
  27. }
  28. @Override
  29. public boolean needsScores() {
  30. return false;
  31. }
  32. @Override
  33. public String getName() {
  34. return "my_script";
  35. }
  36. }
  37. public static class MyNativeScript extends AbstractDoubleSearchScript {
  38. @Override
  39. public double runAsDouble() {
  40. double a = (double) source().get("a");
  41. double b = (double) source().get("b");
  42. return a * b;
  43. }
  44. }
  45. }
  46. --------------------------------------------------
  47. You can execute the script by specifying its `lang` as `native`, and the name
  48. of the script as the `id`:
  49. [source,js]
  50. --------------------------------------------------
  51. POST /_search
  52. {
  53. "query": {
  54. "function_score": {
  55. "query": {
  56. "match": {
  57. "body": "foo"
  58. }
  59. },
  60. "functions": [
  61. {
  62. "script_score": {
  63. "script": {
  64. "inline": "my_script",
  65. "lang" : "native"
  66. }
  67. }
  68. }
  69. ]
  70. }
  71. }
  72. }
  73. --------------------------------------------------
  74. // CONSOLE
  75. // TEST[skip:we don't have a native plugin installed to test this]