進入Kibana的DevTools執行下面操作:
#添加一條document
PUT /test_index/test_type/1
{
"test_content":"test test"
}
#查詢
GET /test_index/test_type/1
#返回
{
"_index": "test_index",
"_type": "test_type",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"test_content": "test test"
}
}
1、 _index元數據解析
- 代表這個document存放在哪個index中
- 類似的數據放在一個索引,非類似的數據放不同索引。例如:product index(包含了所有的商品),sales index(包含了所有的商品銷售數據),inventory index(包含了所有庫存相關的數據)。如果你把比如product,sales,human resource(employee),全都放在一個大的index里面,比如說company index,不合適的。
- index中包含了很多類似的document:類似是什么意思,其實指的就是說,這些document的fields很大一部分是相同的,你說你放了3個document,每個document的fields都完全不一樣,這就不是類似了,就不太適合放到一個index里面去了。
-
索引名稱必須是小寫的,不能用下劃線開頭,不能包含逗號:product,website,blog
為什么類似的數據放在一個索引,非類似的數據放不同索引
2、 _type元數據解析
- 代表document屬于index中的哪個類別(type)
- 一個索引通常會劃分為多個type,邏輯上對index中有些許不同的幾類數據進行分類:因為一批相同的數據,可能有很多相同的fields,但是還是可能會有一些輕微的不同,可能會有少數fields是不一樣的,舉個例子,就比如說,商品,可能劃分為電子商品,生鮮商品,日化商品,等等。
- type名稱可以是大寫或者小寫,但是同時不能用下劃線開頭,不能包含逗號
3、 _id元數據解析
- 代表document的唯一標識,id與index和type一起,可以唯一標識和定位一個document
- 我們可以手動指定document的id(put /index/type/id),也可以不指定,由es自動為我們創建一個id
4、document id的手動指定與自動生成兩種方式解析
1. 手動指定document id
(1)根據應用情況來說,是否滿足手動指定document id的前提:
- 一般來說,是從某些其他的系統中,導入一些數據到es時,會采取這種方式,就是使用系統中已有數據的唯一標識,作為es中document的id。
舉個例子,比如說,我們現在在開發一個電商網站,做搜索功能,或者是OA系統,做員工檢索功能。這個時候,數據首先會在網站系統或者IT系統內部的數據庫中,會先有一份,此時就肯定會有一個數據庫的primary key(自增長,UUID,或者是業務編號)。如果將數據導入到es中,此時就比較適合采用數據在數據庫中已有的primary key。
- 如果說,我們是在做一個系統,這個系統主要的數據存儲就是es一種,也就是說,數據產生出來以后,可能就沒有id,直接就放es一個存儲,那么這個時候,可能就不太適合說手動指定document id的形式了,因為你也不知道id應該是什么,此時可以采取下面要講解的讓es自動生成id的方式。
#語法:
put /index/type/id
#手動生成id
PUT /test_index/test_type/2
{
"test_content": "my test"
}
2. 自動生成document id
#語法:
post /index/type
#自動生成id
POST /test_index/test_type
{
"test_content": "my test"
}
#返回
{
"_index": "test_index",
"_type": "test_type",
"_id": "AWKVr3MWWhuqAs-7Mpj5",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
自動生成的id,長度為20個字符,URL安全,base64編碼,GUID,分布式系統并行生成時不可能會發生沖突
GUID:GUID算法,可保證在分布式的環境下,不同節點同一時間創建的 _id 一定是不沖突的。
GUID不沖突解釋
4、_source元數據以及定制返回結果解析
- _source元數據
#添加數據
put /test_index/test_type/1
{
"test_field1": "test field1",
"test_field2": "test field2"
}
#獲取
get /test_index/test_type/1
#返回
{
"_index": "test_index",
"_type": "test_type",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"test_field1": "test field1",
"test_field2": "test field2"
}
}
_source元數據:就是說,我們在創建一個document的時候,使用的那個放在request body中的json串(所有的field),默認情況下,在get的時候,會原封不動的給我們返回回來。
- 定制返回結果
定制返回的結果,指定_source中,返回哪些field
#語法:
GET /test_index/test_type/1?_source=test_field2
#返回
{
"_index": "test_index",
"_type": "test_type",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"test_field2": "test field2"
}
}
#也可返回多個field使用都好分割
GET /test_index/test_type/1?_source=test_field2,test_field1