主要知識點
- 理解es中的type數據類型
一、type的理解
type是一個index中用來區分類似的數據的,但是可能有不同的fields,而且有不同的屬性來控制索引建立、分詞器。field的value值在底層的lucene中建立索引的時候,全部是opaque bytes類型,不區分類型的。lucene是沒有type的概念的,在document中,實際上將type作為一個document的field來存儲,即_type,es通過_type來進行type的過濾和篩選。一個index中的多個type,實際上是放在一起存儲的,因此一個index下,不能有多個type重名但是類型或其他設置不同,因為那樣是無法處理的。
二、示例
假設有如下一個index
PUT /goods
{
"ecommerce": {
"mappings": {
"elactronic_goods": {
"properties": {
"name": {
"type": "string",
},
"price": {
"type": "double"
},
"service_period": {
"type": "string"
}
}
},
"fresh_goods": {
"properties": {
"name": {
"type": "string",
},
"price": {
"type": "double"
},
"eat_period": {
"type": "string"
}
}
}
}
}
}
有如下兩條數據
{
"name": "geli kongtiao",
"price": 1999.0,
"service_period": "one year"
}
{
"name": "aozhou dalongxia",
"price": 199.0,
"eat_period": "one week"
}
在底層的存儲是這樣子的:
{
"ecommerce": {
"mappings": {
"_type": {
"type": "string",
"index": "not_analyzed"
},
"name": {
"type": "string"
}
"price": {
"type": "double"
}
"service_period": {
"type": "string"
}
"eat_period": {
"type": "string"
}
}
}
}
{
"_type": "elactronic_goods",
"name": "geli kongtiao",
"price": 1999.0,
"service_period": "one year",
"eat_period": ""
}
{
"_type": "fresh_goods",
"name": "aozhou dalongxia",
"price": 199.0,
"service_period": "",
"eat_period": "one week"
}
可以看出,在es內部,會把所有field合並,對於一個type中沒有的field就用空值替代。
所以,在一個index下不同type的同名field的類型必須一致,不然就會沖突。
最佳實踐,將類似結構的type放在一個index下,這些type應該有多個field是相同的
因此,如果將兩個type的field完全不同,放在一個index下,那么就每條數據都至少有一半的field在底層的lucene中是空值,會有嚴重的性能問題。