一、對象類型
使用json、json數組作爲字段值,動態映射會默認使用對象類型(type object)。
1.1字段值爲json對象
POST users/users/1
{
"name":"王月",
"description":{
"date":"2015-12-22",
"title":"go to School"
}
}
相當於插入一條:
{
"name":"王月",
"description.date":"2015-12-22",
"description.title":"go to School"
}
1.2字段值爲json數組
POST users/users/1
{
"name":"王月",
"user_id":1,
"description":[
{
"date":"2015-12-22",
"title":"go to School"
},
{
"date":"2016-10-22",
"title":"go Shopping"
}
]
}
相當於插入一條:
{
"name":"王月",
"user_id":1,
"description.date":["2015-12-22","2016-10-22"],
"description.title":["go to School","go Shopping"]
}
但是當我們搜索:“2015年” 且“包含shopping”的記錄時,這條記錄仍然可以被搜索出來。就是因爲存儲對象數組時使用object會丟失層級關係,解決方式就是需要Nested格式解決。
{
"query":{
"bool":{
"must":[
{
"term":{
"description.title":{
"value":"school"
}
}
},
{
"range":{
"description.date":{
"from":"2015-01-01",
"to":"2015-12-31"
}
}
}
]
}
}
}
查看此時的mapping結構:(其實是description字段裏面增加了兩個key).
二、Nested
創建索引mapping:設置type爲nested。然後再寫入剛剛的數據,再查詢“2015年” 且“包含shopping”的記錄,無結果返回,正確。
{
"mappings":{
"users":{
"properties":{
"description":{
"type":"nested",
"properties":{
"date":{
"type":"date"
},
"title":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
},
"name":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
}
}
}
這時候當你再執行插入語句時:相當於插入了三條記錄,一條根文檔和兩條嵌套文檔。
{
"name":"王月"
}
{
"description.date":"2015-12-22",
"description.title":"go to School"
}
{
"description.date":"2016-10-22",
"description.title":"go Shopping"
}
需要說明的一點,爲了保證性能,一個文檔和其嵌套文檔都集中在同一個Segment中。而父子關係的文檔因爲是子文檔和父文檔相互獨立查詢起來更耗時,但是對於更新更加友好。子文檔和父文檔的更新相互不影響。