将基于脚本的字段添加到elasticSearch索引Map

b4wnujal  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(176)

我正在跟踪以下文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime-indexed.html
我有一个字段,我不想在运行时编写脚本,而是在索引时编写脚本,根据上面的内容,我可以简单地将该字段及其脚本像往常一样放在Map对象中。
下面是我尝试创建的索引的简化版本

{
  "settings": {
    "analysis": {
      "analyzer": {
        "case_insensitive_analyzer": {
          "type": "custom",
          "filter": ["lowercase"],
          "tokenizer": "keyword"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "text"
      },
      "events": {
        "properties": {
          "fields": {
            "type": "text"
          },
          "id": {
            "type": "text"
          },
          "event": {
            "type": "text"
          },
          "time": {
            "type": "date"
          },
          "user": {
            "type": "text"
          },
          "state": {
            "type": "integer"
          }
        }
      },
      "eventLast": {
        "type": "date",
        "on_script_error": "fail",
        "script": {
          "source": "def events = doc['events']; emit(events[events.length-1].time.value"
        }
      }
    }
  }
}

我得到这个400错误:

{
    "error": {
        "root_cause": [
            {
                "type": "mapper_parsing_exception",
                "reason": "unknown parameter [script] on mapper [eventLast] of type [date]"
            }
        ],
        "type": "mapper_parsing_exception",
        "reason": "Failed to parse mapping [_doc]: unknown parameter [script] on mapper [eventLast] of type [date]",
        "caused_by": {
            "type": "mapper_parsing_exception",
            "reason": "unknown parameter [script] on mapper [eventLast] of type [date]"
        }
    },
    "status": 400
}

实际上,我正在尝试创建一个脚本化索引字段,该字段是根据文档的events数组中的最后一个事件时间计算出来的。
谢谢

yxyvkwin

yxyvkwin1#

Tldr;

正如错误所述,您不能在此处定义脚本。在elasticsearch中有一个specific way to create runtime fields
您需要将定义放在runtime对象中json的根目录下。

溶液

{
  "settings": {
    "analysis": {
      "analyzer": {
        "case_insensitive_analyzer": {
          "type": "custom",
          "filter": ["lowercase"],
          "tokenizer": "keyword"
        }
      }
    }
  },
  "runtime": {
    "eventLast": {
      "type": "date",
      "on_script_error": "fail",
      "script": {
        "source": "def events = doc['events']; emit(events[events.length-1].time.value"
      }
    }
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "text"
      },
      "events": {
        "properties": {
          "fields": {
            "type": "text"
          },
          "id": {
            "type": "text"
          },
          "event": {
            "type": "text"
          },
          "time": {
            "type": "date"
          },
          "user": {
            "type": "text"
          },
          "state": {
            "type": "integer"
          }
        }
      }
    }
  }
}

相关问题