native.asciidoc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. }
  33. public static class MyNativeScript extends AbstractDoubleSearchScript {
  34. @Override
  35. public double runAsDouble() {
  36. double a = (double) source().get("a");
  37. double b = (double) source().get("b");
  38. return a * b;
  39. }
  40. }
  41. }
  42. --------------------------------------------------
  43. You can execute the script by specifying its `lang` as `native`, and the name
  44. of the script as the `id`:
  45. [source,js]
  46. --------------------------------------------------
  47. curl -XPOST localhost:9200/_search -d '{
  48. "query": {
  49. "function_score": {
  50. "query": {
  51. "match": {
  52. "body": "foo"
  53. }
  54. },
  55. "functions": [
  56. {
  57. "script_score": {
  58. "script": {
  59. "id": "my_script",
  60. "lang" : "native"
  61. }
  62. }
  63. }
  64. ]
  65. }
  66. }
  67. }'
  68. --------------------------------------------------