1. 程式人生 > >Elasticsearch CRUD基本操作

Elasticsearch CRUD基本操作

**前言** 本次我們聊一聊Elasticsearch的基本操作CRUD,他跟我們常用的關係型資料庫的操作又有什麼不一樣的地方呢?今天我們就來好好講解一番。 [TOC] # 說明 本次演示用的版本是7.11。 工具可以使用Kibana的控制檯,介面美觀且有一定的縮排,而且能簡化命令列的curl操作,如果對安裝有問題的,可以看一下我之前的文章。 ![image.png](https://upload-images.jianshu.io/upload_images/5377351-99857d49cf28e1c1.png) # API約定 關係型資料庫用的是SQL進行資料的訪問,而Elasticsearch用的是REST進行資料的訪問,HTTP的請求頭PUT、GET、POST、DELETE正好可以對應CRUD(create、read、update、delete)四種資料操作。 資料的格式用的是JSON。 # 索引操作 ## 建立索引 建立索引movie ``` PUT /movie { "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 0 } } } ``` number_of_shards是主分片數,number_of_replicas是一個主分片有多少個本,那麼總的分片數就是“(number_of_replicas + 1) * number_of_shards” ## 檢視索引 ``` GET /movie/ ``` ## 刪除索引 ``` DELETE /movie/ ``` # 文件操作 ## 插入文件 7.x版本,type預設是“_doc”。可以用POST,也可以用PUT ``` // 自動生成_id POST /movie/_doc { "title": "The Pursuit of Happyness", "actors": [ "Will Smith", "Jaden Smith", "Thandie Newton" ] } // 指定_id=1 PUT /movie/_doc/1 { "title": "The Pursuit of Happyness", "actors": [ "Will Smith", "Jaden Smith", "Thandie Newton" ] } // 演示覆蓋 PUT /movie/_doc/1 { "title": "xxx" } ``` 如果是指定_id的情況下(稱為index操作),那麼如果文件已經存在的話,會直接進行覆蓋,也就是如果裡面有些欄位沒傳,那個欄位就不會儲存了,比如上面第三個請求,執行完後去獲取“_id=1”的資料,只能獲取到title欄位,actors欄位是不存在的。 ## 更新文件 更新“_id=1”的資料,注意需要有“doc”。如果用“POST /movie/_update/1”這種語法,就直接覆蓋了。 ``` POST /movie/_update/1 { "doc":{ "title": "The Pursuit of Happyness xxx" } } ``` ## 刪除文件 刪除“_id=1”的資料 ``` DELETE /movie/_doc/1 ``` ## 獲取文件 獲取“_id=1”的資料 ``` GET /movie/_doc/1 ``` ## 搜尋文件 ``` GET /movies/_search { "profile": "true", "_source": ["movieId", "title","genres"], "sort": [{"movieId": "desc"}], "from": 0, "size": 3, "query": { "match_all": {} } } ``` - movies是之前匯入的資料,非前面用的movie,需要測試的話要先匯入一下資料。 - profile 相當於MySQL中的explain - _source 是要返回的欄位 上面的請求,類比SQL如下 ``` select movieId, title, genres from movies order by movieId desc limit 0, 3 ``` 更復雜的搜尋查詢,後面持續更新。 # 批量文件操作 ## 批量操作 ``` POST movie/_bulk {"index":{"_index":"movie","_id":1}} {"title": "xxx xx"} {"index":{"_index":"movie","_id":2}} {"title": "The Pursuit of Happyness"} {"update":{"_index":"movie","_id":2}} {"doc":{"title": "xxx xx"}} ``` 支援在一次API呼叫中,對不同的索引做不同的操作,減少網路請求的次數,提高效能。支援的操作有index、create、update、delete。批量操作,如果其中一條有錯誤沒法執行,不會阻礙其他的請求,會繼續執行下去。 請求體要特別注意一下,不能格式化,而且第一行指定index跟id,第二行指定資料,以此類推。 ## 批量讀取 請求體可以格式化 ``` GET _mget { "docs": [ { "_index": "movie", "_id": 1 }, { "_index": "movie", "_id": 2 } ] } ``` 如果是對同一個index進行操作,可以在URI指定index ``` GET movie/_mget { "docs": [ { "_id": 1 }, { "_id": 2 } ] ``` ## 批量查詢 ``` GET /movies/_msearch {} {"from":0,"size":1,"query":{"match_all":{}}} {} {"from":0,"size":2,"query":{"match_all":{}}} ``` 與_bulk操作類似,不能進行格