Use runtime fields

edit

Use the runtime_mappings parameter to extract and create runtime fields, or columns, from existing ones during a search.

The following search creates a release_day_of_week runtime field from release_date and returns it in the response.

resp = client.sql.query(
    format="txt",
    runtime_mappings={
        "release_day_of_week": {
            "type": "keyword",
            "script": "\n        emit(doc['release_date'].value.dayOfWeekEnum.toString())\n      "
        }
    },
    query="\n    SELECT * FROM library WHERE page_count > 300 AND author = 'Frank Herbert'\n  ",
)
print(resp)
response = client.sql.query(
  format: 'txt',
  body: {
    runtime_mappings: {
      release_day_of_week: {
        type: 'keyword',
        script: "\n        emit(doc['release_date'].value.dayOfWeekEnum.toString())\n      "
      }
    },
    query: "\n    SELECT * FROM library WHERE page_count > 300 AND author = 'Frank Herbert'\n  "
  }
)
puts response
const response = await client.sql.query({
  format: "txt",
  runtime_mappings: {
    release_day_of_week: {
      type: "keyword",
      script:
        "\n        emit(doc['release_date'].value.dayOfWeekEnum.toString())\n      ",
    },
  },
  query:
    "\n    SELECT * FROM library WHERE page_count > 300 AND author = 'Frank Herbert'\n  ",
});
console.log(response);
POST _sql?format=txt
{
  "runtime_mappings": {
    "release_day_of_week": {
      "type": "keyword",
      "script": """
        emit(doc['release_date'].value.dayOfWeekEnum.toString())
      """
    }
  },
  "query": """
    SELECT * FROM library WHERE page_count > 300 AND author = 'Frank Herbert'
  """
}

The API returns:

    author     |     name      |  page_count   |      release_date      |release_day_of_week
---------------+---------------+---------------+------------------------+-------------------
Frank Herbert  |Dune           |604            |1965-06-01T00:00:00.000Z|TUESDAY