Elasticsearch Elasticsearch Painless Script Examples

By Opster Team

Updated: Nov 14, 2023

| 2 min read

Introduction

Painless is a simple, secure, and performant scripting language designed specifically for Elasticsearch and OpenSearch. It is the default scripting language for Elasticsearch and can safely be used for inline and stored scripts. In this article, we will explore some practical examples of using Painless scripts in Elasticsearch.

1. Scripted Fields in Kibana

Scripted fields in Kibana allow you to compute a new field on the fly from the data in your Elasticsearch indices. This can be useful for creating custom visualizations or aggregations based on calculated values. Here’s an example of a Painless script that calculates the duration between two date fields:

doc['end_date'].value - doc['start_date'].value

This script subtracts the `start_date` field from the `end_date` field and returns the duration in milliseconds.

2. Custom Scoring in Elasticsearch Queries

Painless scripts can be used to modify the relevance score of documents returned by Elasticsearch queries. This can be useful for boosting or demoting certain documents based on specific criteria. Here’s an example of a Painless script that boosts the score of documents with a specific tag:

json
{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "filter": {
            "term": {
              "tags": "important"
            }
          },
          "script_score": {
            "script": {
              "source": "return _score * 2;"
            }
          }
        }
      ]
    }
  }
}

This script doubles the score of documents with the “important” tag, making them more likely to appear at the top of the search results.

3. Update By Query with Painless Script

You can use Painless scripts to update documents in Elasticsearch based on a query. This can be useful for applying changes to a subset of documents without having to reindex the entire dataset. Here’s an example of a Painless script that updates the `price` field of all documents with a specific `category`:

json
POST /products/_update_by_query
{
  "script": {
    "source": "ctx._source.price *= 1.1",
    "lang": "painless"
  },
  "query": {
    "term": {
      "category": "electronics"
    }
  }
}

This script increases the `price` field by 10% for all documents with the “electronics” category.

4. Ingest Node Script Processor

Painless scripts can be used in Elasticsearch ingest pipelines to modify documents before they are indexed. This can be useful for cleaning, enriching, or transforming data as it is ingested into Elasticsearch. Here’s an example of a Painless script that concatenates two fields into a new field:

json
PUT _ingest/pipeline/concatenate-fields
{
  "description": "Concatenate first_name and last_name fields",
  "processors": [
    {
      "script": {
        "source": "ctx.full_name = ctx.first_name + ' ' + ctx.last_name;"
      }
    }
  ]
}

This script creates a new `full_name` field by concatenating the `first_name` and `last_name` fields.

5. Bucket Script Aggregation

Painless scripts can be used in Elasticsearch aggregations to perform calculations on the results of other aggregations. This can be useful for computing ratios, differences, or other derived metrics. Here’s an example of a Painless script that calculates the average revenue per user:

json
{
  "size": 0,
  "aggs": {
    "total_revenue": {
      "sum": {
        "field": "revenue"
      }
    },
    "unique_users": {
      "cardinality": {
        "field": "user_id"
      }
    },
    "average_revenue_per_user": {
      "bucket_script": {
        "buckets_path": {
          "total_revenue": "total_revenue",
          "unique_users": "unique_users"
        },
        "script": "params.total_revenue / params.unique_users"
      }
    }
  }
}

This script calculates the average revenue per user by dividing the total revenue by the number of unique users.

Conclusion 

In conclusion, Painless scripts offer a powerful and flexible way to customize Elasticsearch and OpenSearch behavior. By understanding how to use Painless scripts effectively, you can unlock new possibilities for data analysis, visualization, and manipulation.