CouchDB的安裝與使用簡介

Posted by Y Cheung on Tue, Aug 8, 2017

CouchDB 是一個通過 RESTful API 訪問的多版本控制文檔型存儲的 NoSQL,支持 Map/Reduce,不支持動態查詢。

安裝CouchDB

RedHat 系統執行命令安裝:

1sudo yum -y install epel-release && yum install couchdb

你也可以下載源碼自己編譯安裝,(不建議,超麻煩,Y.Cheung 已經失敗好多次)。

安裝好之後啟用服務

1sudo service couchdb start

訪問CouchDB

瀏覽器訪問網址 http://127.0.0.1:5984/_utils/index.html

CouchDB index page

校驗安裝 http://localhost:5984/_utils/verify_install.html

CouchDB配置 http://localhost:5984/_utils/config.html

創建管理員用戶

CouchDB 默認所有用戶都可以以管理員賬戶訪問數據庫,因此為了安全需要為數據庫創建管理員賬戶。

點擊web界面右下角的Fix this鏈接創建用戶:

Fix this

然後在彈出窗口中輸入用戶名和密碼,並點擊Create創建。

Create Server Admin

完成後右下角會顯示:

創建/刪除數據庫

創建數據庫 new_database

1curl -X PUT http://localhost:5984/new_database -u "admin:password"

刪除數據庫 new_database

1curl -X DELETE http://localhost:5984/new_database -u "admin:password"

如果成功,都會返回:

1{"ok":true}

插入/更新/刪除/查看數據文檔

  • 插入
1curl -X PUT http://127.0.0.1:5984/my_database/"001" -d '{ " Name " : " Raju " , " age " :" 23 " , " Designation " : " Designer " }'
  • 刪除數據文檔
1curl -X GET http://127.0.0.1:5984/my_database/001
  • 指定版本號進行刪除
1curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-3fcc78daac7a90803f0a5e383f4f1e1e
  • 查看數據文檔
1curl -X GET http://127.0.0.1:5984/my_database/001
  • 更新數據文檔 更新數據文檔需要指定版本號,所以流程上需要先獲取當前文檔的版本號 _rev,然後根據這個 _rev 進行PUT更新。比如
1curl -X GET http://127.0.0.1:5984/my_database/001

獲取得到結果中的 _rev2-04d8eac1680d237ca25b68b36b8899d3

1{
2   "_id" : "001",
3   "_rev" : "2-04d8eac1680d237ca25b68b36b8899d3 " ,
4   "age" : "23"
5}

然後在更新的json文檔中加入這個_rev字段,如下:

1curl -X PUT http://127.0.0.1:5984/my_database/001/ -d ' { " age " : " 24 " , " _rev " : " 1-1c2fae390fa5475d9b809301bbf3f25e " } '

參考此文檔

通用數據庫操作指令索引

跨於資源共享CORS問題解決方法

在CouchDB配置 http://localhost:5984/_utils/config.html 中更改以下設置

1[httpd]
2enable_cors = true
3
4[cors]
5origins = *

參考cross-origin-resource-sharing