1、首先弄明白四個概念
elasticsearch | 關系型數據庫 |
index | 數據庫 |
type | 表 |
document | 行 |
field | 字段 |
如果剛一開始理解比較困難,那你就在心中默念100遍,10遍也可以。。。
如果你做過面向對象開發,我覺得elasticsearch的這四個概念還是很好理解的。
需要重點說明的是document就是一個json格式的字符串,里面包括N個字段。我們可以想象將面向對象語言里面的一個對象序列化成json字符串。
關系型數據庫需要先建庫,再建表。elasticsearch不需要,在你新增的時候會根據你指定的index,type,document,field自動創建。當然先創建索引也是可以的。
接下來的測試我會這么定義我們的index,type
index:news
type:new
field:title,content。就兩個吧,如下:
{ "title":"", "content":"" }
我使用的客戶端是kibana。
2、新增document
PUT news/new/6 { "title":"title test", "conent":"content test" }
結果:
{ "_index": "news", "_type": "new", "_id": "6", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 2, "failed": 0 }, "created": true }
解釋下:
PUT news/new/6
這條命令的原型是這樣的:
PUT index/type/id
PUT命令是http請求的一種方式,如果了解過restful api,對這個命令應該不陌生。除了我們大家熟悉的get,post,還有put,delete,head等。
news就是我們需要創建的索引,可以理解為數據庫
new就是我們需要創建的type,可以理解為表
6就是文檔的id,可以理解為一條記錄的id
仔細看返回結果,先別看_shards,其它幾個字段大家看了之后應該會立馬明白。
_version,是elasticsearch里面用來控制版本沖突的,知道下就行,如果修改或者刪除,_version的值都會+1。
3、修改document
修改又分為全量修改和部分修改
全量修改用PUT,部分修改用POST
全量修改:
PUT news/new/6 { "title":"title test" }
用查詢命令(下面有)查看結果:
{ "_index": "news", "_type": "new", "_id": "6", "_version": 2, "found": true, "_source": { "title": "title test" } }
納尼?我的content字段呢?問題就出在這里,如果用全量修改(PUT),就等於是刪除之后再新建。
如果有人說我只想修改title字段怎么辦?看下面。
部分修改
POST /news/new/6/_update { "doc":{ "title":"abcdefg" } }
用查詢命令(下面有)查看結果:
{ "_index": "news", "_type": "new", "_id": "6", "_version": 4, "found": true, "_source": { "title": "abcdefg", "content": "content test" } }
我在執行POST命令前,把數據恢復了,所以在執行POST命令且只修改title字段后,content還是保留的。且_version變成了4,而不是3。
4、查詢document
GET /news/new/6
結果:
{ "_index": "news", "_type": "new", "_id": "6", "_version": 4, "found": true, "_source": { "title": "abcdefg", "content": "content test" } }
5、刪除document
DELETE /news/new/6
結果:
{ "found": true, "_index": "news", "_type": "new", "_id": "6", "_version": 5, "result": "deleted", "_shards": { "total": 2, "successful": 2, "failed": 0 } }
很簡單。簡單的增刪改查介紹完畢。
劇透一下,接下來會講中文分詞+全文搜索