您可以查看Elasticsearch Pipelines。它们在索引(以及您的案例分析)发生之前应用。
具体来说,您可以添加一个 Elasticsearch Pipeline,如果它们满足您列出的条件,则删除必填字段。比如:
PUT _ingest/pipeline/remove_invalid_value
{
"description": "my pipeline that removes empty string and null strings",
"processors": [
{
"remove": {
"field": "field1",
"ignore_missing": true,
"if": "ctx.field1 == \"null\" || ctx.field1 == \"\""
}
},
{
"remove": {
"field": "field2",
"ignore_missing": true,
"if": "ctx.field2 == \"null\" || ctx.field2 == \"\""
}
},
{
"remove": {
"field": "field3",
"ignore_missing": true,
"if": "ctx.field3 == \"null\" || ctx.field3 == \"\""
}
}
]
}
然后,您可以在index request 中指定管道,或者将其作为default_pipeline 或final_pipeline 放在index settings 中。您也可以在索引模板中指定此设置。
(脚本)循环方法
如果您不想编写一长串删除操作,可以尝试使用脚本处理器,如下所示:
PUT _ingest/pipeline/remove_invalid_fields
{
"description": "remove fields",
"processors": [
{
"script": {
"source": """
for (x in params.to_delete_on_condition) {
if (ctx[x] == "null" || ctx[x] == "") {
ctx.remove(x);
}
}
""",
"params": {
"to_delete_on_condition": [
"field1",
"field2",
"field3"
]
}
}
}
]
}
它遍历列表并在条件匹配时删除该字段。
访问脚本中的嵌套字段并不像许多答案中所报告的那样微不足道,但它应该是可行的。这个想法是nested.field 应该作为ctx['nested']['field'] 访问。