New

The executive guide to generative AI

Read more
IMPORTANT: This documentation is no longer updated. Refer to Elastic's version policy and the latest documentation.

Using Python in Elasticsearch

edit

Once the plugin has been installed, Python can be used at a scripting language by setting the lang parameter to python.

Scripting is available in many APIs, but we will use an example with the function_score for demonstration purposes:

Inline scripts

edit

Enabling inline scripting on an unprotected Elasticsearch cluster is dangerous. See File scripts for a safer option.

If you have enabled inline scripts, you can use Python as follows:

PUT test/doc/1
{
  "num": 1.0
}

PUT test/doc/2
{
  "num": 2.0
}

GET test/_search
{
  "query": {
    "function_score": {
      "script_score": {
        "script": {
          "inline": "doc[\"num\"].value * factor",
          "lang": "python",
          "params": {
            "factor": 2
          }
        }
      }
    }
  }
}

Stored scripts

edit

Enabling stored scripts on an unprotected Elasticsearch cluster is dangerous. See File scripts for a safer option.

If you have enabled stored scripts, you can use Python as follows:

PUT test/doc/1
{
  "num": 1.0
}

PUT test/doc/2
{
  "num": 2.0
}

POST _scripts/python/my_script  
{
  "script": "doc[\"num\"].value * factor"
}

GET test/_search
{
  "query": {
    "function_score": {
      "script_score": {
        "script": {
          "stored": "my_script", 
          "lang": "python",
          "params": {
            "factor": 2
          }
        }
      }
    }
  }
}

We store the script under the id my_script.

The function score query retrieves the script with id my_script.

File scripts

edit

You can save your scripts to a file in the config/scripts/ directory on every node. The .py file suffix identifies the script as containing Python:

First, save this file as config/scripts/my_script.py on every node in the cluster:

doc["num"].value * factor

then use the script as follows:

PUT test/doc/1
{
  "num": 1.0
}

PUT test/doc/2
{
  "num": 2.0
}

GET test/_search
{
  "query": {
    "function_score": {
      "script_score": {
        "script": {
          "file": "my_script", 
          "lang": "python",
          "params": {
            "factor": 2
          }
        }
      }
    }
  }
}

The function score query retrieves the script with filename my_script.py.

Was this helpful?
Feedback