native.asciidoc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. curl -XPOST localhost:9200/_search -d '{
  52. "query": {
  53. "function_score": {
  54. "query": {
  55. "match": {
  56. "body": "foo"
  57. }
  58. },
  59. "functions": [
  60. {
  61. "script_score": {
  62. "script": {
  63. "inline": "my_script",
  64. "lang" : "native"
  65. }
  66. }
  67. }
  68. ]
  69. }
  70. }
  71. }'
  72. --------------------------------------------------