Script query

Script query

Runtime fields provide a very similar feature that is more flexible. You write a script to create field values and they are available everywhere, such as fields, all queries, and aggregations.

Filters documents based on a provided script. The script query is typically used in a filter context.

Using scripts can result in slower search speeds. See Scripts, caching, and search speed.

Example request

  1. GET /_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": {
  6. "script": {
  7. "script": """
  8. double amount = doc['amount'].value;
  9. if (doc['type'].value == 'expense') {
  10. amount *= -1;
  11. }
  12. return amount < 10;
  13. """
  14. }
  15. }
  16. }
  17. }
  18. }

You can achieve the same results in a search query by using runtime fields. Use the fields parameter on the _search API to fetch values as part of the same query:

  1. GET /_search
  2. {
  3. "runtime_mappings": {
  4. "amount.signed": {
  5. "type": "double",
  6. "script": """
  7. double amount = doc['amount'].value;
  8. if (doc['type'].value == 'expense') {
  9. amount *= -1;
  10. }
  11. emit(amount);
  12. """
  13. }
  14. },
  15. "query": {
  16. "bool": {
  17. "filter": {
  18. "range": {
  19. "amount.signed": { "lt": 10 }
  20. }
  21. }
  22. }
  23. },
  24. "fields": [{"field": "amount.signed"}]
  25. }

Top-level parameters for script

script

(Required, script object) Contains a script to run as a query. This script must return a boolean value, true or false.

Notes

Custom Parameters

Like filters, scripts are cached for faster execution. If you frequently change the arguments of a script, we recommend you store them in the script’s params parameter. For example:

  1. GET /_search
  2. {
  3. "query": {
  4. "bool": {
  5. "filter": {
  6. "script": {
  7. "script": {
  8. "source": "doc['num1'].value > params.param1",
  9. "lang": "painless",
  10. "params": {
  11. "param1": 5
  12. }
  13. }
  14. }
  15. }
  16. }
  17. }
  18. }

Allow expensive queries

Script queries will not be executed if search.allow_expensive_queries is set to false.