使用运行时字段

编辑

使用 runtime_mappings 参数在搜索期间从现有字段提取并创建运行时字段(或列)。

以下搜索从 release_date 创建一个 release_day_of_week 运行时字段,并在响应中返回它。

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'
  """
}

API 返回

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