elasticsearch如何爲類型添加字段並賦初值
elasticsearch如何爲指定索引中類型添加字段並賦初值,就像數據庫中添加字段爲老的數據賦初始值一樣。
用update_by_query結合script可以辦到,例如:
POST my_index/_update_by_query
{
"script": {
"lang": "painless",
"inline": "if (ctx._source.status_code == null) {ctx._source.status_code= '02'}"
}
}
在ES裏爲已有索引增加一個新字段以後,老的數據並不會自動就擁有了這個新字段,也就不可能給他一個所謂的默認值。ES裏的數據都是文檔型的,修改一個文檔只能是對原文檔做更新,也就是隻能藉助於重新索引的手段。
NULL在ES裏的含義和RDBMS非常不同。
NULL的意思是索引的時候,某個字段沒有被賦值,例如文檔有"city","title"和"status_code"三個字段。
索引的時候漏掉status_code字段:
PUT my_index/my_type/1
{
"city": "NJ",
"title": "Document 1"
}
或者顯式給status_code一個空值:
PUT my_index/my_type/2
{
"city": "BJ",
"title": "Document 2",
"status_code": null
}
示例裏的兩條文檔的status_code這個字段都是被忽略,不做索引的,因此也就無法做所謂的空值搜索。
因此,爲了支持做“status_code = NULL”這樣的搜索,就可以配置一個可選的null_value選項:
"properties": {
"status_code": {
"type": "keyword",
"null_value": "NULL"
}
}
null_value的值可以任意指定,但是必須和status_code的字段類型一致。 比如配置的keyword類型,null_value就必須是字符型。 如果是long類型,null_value就必須是個數字。 類型不一致會報錯。
POST my_index/_update_by_query
{
"script":{
"lang":"painless",
"inline":"if (ctx._source.status == null) {ctx._source.status= '02'}"
}
}
它自動爲我的索引的mapping創建了status這個字段,並且賦值成功。
字段描述如下:
"status" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},