CouchDB的安裝與使用簡介

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

安裝CouchDB

RedHat 系統執行命令安裝:

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

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

安裝好之後啟用服務

$ sudo 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
curl -X PUT http://localhost:5984/new_database -u "admin:password"
  • 刪除數據庫new_database
curl -X DELETE http://localhost:5984/new_database -u "admin:password"

如果成功,都會返回

{"ok":true}

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

  • 插入
$ curl -X PUT http://127.0.0.1:5984/my_database/"001" -d
'{ " Name " : " Raju " , " age " :" 23 " , " Designation " : " Designer " }'
  • 刪除數據文檔
$ curl -X GET http://127.0.0.1:5984/my_database/001

也可以指定版本號進行刪除

$ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-
3fcc78daac7a90803f0a5e383f4f1e1e
  • 查看數據文檔
$ curl -X GET http://127.0.0.1:5984/my_database/001
  • 更新數據文檔
    更新數據文檔需要指定版本號,所以流程上需要先獲取當前文檔的版本號_rev,然後根據這個_rev進行PUT更新。
    比如
$ curl -X GET http://127.0.0.1:5984/my_database/001

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

{
   "_id" : "001",
   "_rev" : "2-04d8eac1680d237ca25b68b36b8899d3 " ,
   "age" : "23"
}

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

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

參考 此文檔

通用數據庫操作指令索引

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

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

[httpd]
enable_cors = true

[cors]
origins = *

參考cross-origin-resource-sharing

Y Cheung

Y Cheung

Blogger, Programer & Traveler.
Shanghai