native.asciidoc 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. [[modules-scripting-native]]
  2. === Native (Java) Scripts
  3. Sometimes `groovy` 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`, `AbstractDoubleSearchScript`, and
  13. `AbstractFloatSearchScript`. Finally, your plugin should register the native
  14. script by declaring the `onModule(ScriptModule)` method.
  15. If you squashed the whole thing into one class it'd look like:
  16. [source,java]
  17. --------------------------------------------------
  18. public class MyNativeScriptPlugin extends Plugin {
  19. @Override
  20. public String name() {
  21. return "my-native-script";
  22. }
  23. @Override
  24. public String description() {
  25. return "my native script that does something great";
  26. }
  27. public void onModule(ScriptModule scriptModule) {
  28. scriptModule.registerScript("my_script", MyNativeScriptFactory.class);
  29. }
  30. public static class MyNativeScriptFactory implements NativeScriptFactory {
  31. @Override
  32. public ExecutableScript newScript(@Nullable Map<String, Object> params) {
  33. return new MyNativeScript();
  34. }
  35. @Override
  36. public boolean needsScores() {
  37. return false;
  38. }
  39. }
  40. public static class MyNativeScript extends AbstractFloatSearchScript {
  41. @Override
  42. public float runAsFloat() {
  43. float a = (float) source().get("a");
  44. float b = (float) source().get("b");
  45. return a * b;
  46. }
  47. }
  48. }
  49. --------------------------------------------------
  50. You can execute the script by specifying its `lang` as `native`, and the name
  51. of the script as the `id`:
  52. [source,js]
  53. --------------------------------------------------
  54. curl -XPOST localhost:9200/_search -d '{
  55. "query": {
  56. "function_score": {
  57. "query": {
  58. "match": {
  59. "body": "foo"
  60. }
  61. },
  62. "functions": [
  63. {
  64. "script_score": {
  65. "script": {
  66. "id": "my_script",
  67. "lang" : "native"
  68. }
  69. }
  70. }
  71. ]
  72. }
  73. }
  74. }'
  75. --------------------------------------------------