Couchdb 简明教程

CouchDB - Quick Guide

CouchDB - Introduction

数据库管理系统提供存储和检索数据的机制。数据库管理系统主要有三种类型,即 RDBMS(关系数据库管理系统)、OLAP(联机分析处理系统)和 NoSQL。

Database management system provides mechanism for storage and retrieval of data. There are three main types of database management systems namely RDBMS (Relational Database management Systems), OLAP (Online Analytical Processing Systems) and NoSQL.

RDBMS

RDBMS 表示关系数据库管理系统。RDBMS 是 SQL 和所有现代数据库系统(例如 MS SQL Server、IBM DB2、Oracle、MySQL 和 Microsoft Access)的基础。

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

关系数据库管理系统 (RDBMS) 是一个数据库管理系统 (DBMS),其基于 E. F. Codd 引入的关系模型。

A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd.

RDBMS 中的数据存储在名为 tables 的数据库对象中。表是相关数据项的集合,并且由列和行组成。它只存储结构化数据。

The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows. It stores only structured data.

OLAP

联机分析处理服务器 (OLAP) 以多维数据模型为基础。它允许经理和分析师通过快速、一致且交互方式访问信息来深入了解该信息。

Online Analytical Processing Server (OLAP) is based on the multidimensional data model. It allows managers and analysts to get an insight of the information through fast, consistent, and interactive access to information.

NoSQL Databases

NoSQL 数据库(有时称为非 SQL)是除关系数据库中使用的表格关系以外提供存储和检索数据的机制的数据库。这些数据库没有架构,支持简单的复制,拥有简单的 API,最终一致,并且能处理大量数据(大数据)。

A NoSQL database (sometimes called as Not Only SQL) is a database that provides a mechanism to store and retrieve data other than the tabular relations used in relational databases. These databases are schema-free, support easy replication, have simple API, eventually consistent, and can handle huge amounts of data (big data).

NoSQL 数据库的主要目标是拥有以下内容 −

The primary objective of a NoSQL database is to have the following −

  1. Simplicity of design,

  2. Horizontal scaling, and

  3. Finer control over availability.

与关系数据库相比,NoSQL 数据库使用不同的数据结构。它让一些操作在 NoSQL 中更快。给定 NoSQL 数据库的适用性取决于它必须解决的问题。这些数据库存储结构化数据和非结构化数据,如音频文件、视频文件、文档等。这些 NoSQL 数据库分为三类,如下所述。

NoSQL databases use different data structures compared to relational databases. It makes some operations faster in NoSQL. The suitability of a given NoSQL database depends on the problem it must solve. These databases store both structured data and unstructured data like audio files, video files, documents, etc. These NoSQL databases are classified into three types and they are explained below.

Key-value Store − 这些数据库旨在将数据存储在键值对中,并且这些数据库没有任何架构。在这些数据库中,每个数据值都包含一个已编制索引的键和该键的一个值。

Key-value Store − These databases are designed for storing data in key-value pairs and these databases will not have any schema. In these databases, each data value consists of an indexed key and a value for that key.

示例 − BerkeleyDB、Cassandra、DynamoDB、Riak。

Examples − BerkeleyDB, Cassandra, DynamoDB, Riak.

Column Store − 在这些数据库中,数据存储在分组为数据列的单元格中,并且这些列进一步分组到列族中。这些列族可以包含任意数量的列。

Column Store − In these databases, data is stored in cells grouped in columns of data, and these columns are further grouped into Column families. These column families can contain any number of columns.

示例 − BigTable、HBase 和 HyperTable。

Examples − BigTable, HBase, and HyperTable.

Document Store - 这是基于键值存储的基本理念开发的数据库,其中“文档”包含更多复杂的数据。此处,每个文档都会被分配一个唯一键,这个键用于检索文档。这些文档被设计用于存储、检索和管理面向文档的信息,也称为半结构化数据。

Document Store − These are the databases developed on the basic idea of key-value stores where "documents" contain more complex data. Here, each document is assigned a unique key, which is used to retrieve the document. These are designed for storing, retrieving, and managing document-oriented information, also known as semi-structured data.

示例 − CouchDB 和 MongoDB。

Examples − CouchDB and MongoDB.

What is CouchDB?

CouchDB 是由 Apache 软件基金会开发的一个开源数据库。其重点在于易用性,涵盖网络。它是一个 NoSQL 文档存储数据库。

CouchDB is an open source database developed by Apache software foundation. The focus is on the ease of use, embracing the web. It is a NoSQL document store database.

它使用 JSON 来存储数据(文档),使用 JavaScript 作为查询语言来转换文档,使用 http 协议,通过 api 访问文档,使用 web 浏览器查询索引。它是一个多主应用,发布的时间是 2005 年,并且在 2008 年成为了一个 Apache 项目。

It uses JSON, to store data (documents), java script as its query language to transform the documents, http protocol for api to access the documents, query the indices with the web browser. It is a multi master application released in 2005 and it became an apache project in 2008.

Why CouchDB?

  1. CouchDB have an HTTP-based REST API, which helps to communicate with the database easily. And the simple structure of HTTP resources and methods (GET, PUT, DELETE) are easy to understand and use.

  2. As we store data in the flexible document-based structure, there is no need to worry about the structure of the data.

  3. Users are provided with powerful data mapping, which allows querying, combining, and filtering the information.

  4. CouchDB provides easy-to-use replication, using which you can copy, share, and synchronize the data between databases and machines.

Data Model

  1. Database is the outermost data structure/container in CouchDB.

  2. Each database is a collection of independent documents.

  3. Each document maintains its own data and self-contained schema.

  4. Document metadata contains revision information, which makes it possible to merge the differences occurred while the databases were disconnected.

  5. CouchDB implements multi version concurrency control, to avoid the need to lock the database field during writes.

Features of CouchDB:Reduce the Content

Document Storage

CouchDB 是一个 NoSQL 文档存储数据库。它提供了存储具有唯一名称的文档的功能,并且还提供了一个称为 RESTful HTTP API 的 API,用于读取和更新(添加、编辑、删除)数据库文档。

CouchDB is a document storage NoSQL database. It provides the facility of storing documents with unique names, and it also provides an API called RESTful HTTP API for reading and updating (add, edit, delete) database documents.

在 CouchDB 中,文档是数据的基本单位,它们也包括元数据。文档字段具有唯一名称,并且包含各种类型的属性值(文本、数字、布尔值、列表等);文本大小或元素数量没有固定的限制。

In CouchDB, documents are the primary unit of data and they also include metadata. Document fields are uniquely named and contain values of varying types (text, number, Boolean, lists, etc.), and there is no set limit to text size or element count.

文档更新(添加、编辑、删除)遵循原子性,即它们将被完全保存或根本不会被保存。数据库将不会有任何部分保存或编辑的文档。

Document updates (add, edit, delete) follow Atomicity, i.e., they will be saved completely or not saved at all. The database will not have any partially saved or edited documents.

Json Document Structure

{
   "field" : "value",
   "field" : "value",
   "field" : "value",
}

ACID Properties

CouchDB 包含 ACID 属性作为其一项功能。

CouchDB contains ACID properties as one of its features.

一致性 − 当 CouchDB 中的数据被提交一次时,就不允许修改或覆盖该数据。因此,CouchDB 确保数据库文件将始终处于一致的状态。

Consistency − When the data in CouchDB was once committed, then this data will not be modified or overwritten. Thus, CouchDB ensures that the database file will always be in a consistent state.

CouchDB reads 使用多版本并发控制 (MVCC) 模型,因此客户端将从读取操作的开始到结束看到数据库的一致快照。

A multi-Version Concurrency Control (MVCC) model is used by CouchDB reads, because of which the client will see a consistent snapshot of the database from the beginning to the end of the read operation.

每当更新文档时,CouchDB 便会将数据写入到磁盘中,并将更新后的数据库标头写入两个连续且相同的块中,以构成文件的前 4k,然后同步写入磁盘。写入期间的部分更新会丢弃。

Whenever a documents is updated, CouchDB flushes the data into the disk, and the updated database header is written in two consecutive and identical chunks to make up the first 4k of the file, and then synchronously flushed to disk. Partial updates during the flush will be discarded.

如果写入标头时出现故障,先前相同的标头副本将继续保留,从而保证所有先前提交数据的一致性。除了标头区域之外,在崩溃或断电后永远不需要执行一致性检查或修复。

If the failure occurred while committing the header, a surviving copy of the previous identical headers will remain, ensuring coherency of all previously committed data. Except the header area, consistency checks or fix-ups after a crash or a power failure are never necessary.

Compaction

每当数据库文件中空间浪费超过某个程度时,所有活动数据都会被复制(克隆)到一个新文件中。复制过程完全完成后,旧文件将被丢弃。所有这些都是由压缩过程完成的。数据库在压缩期间保持联机,并且允许所有更新和读取都成功完成。

Whenever the space in the database file got wasted above certain extent, all the active data will be copied (cloned) to a new file. When the copying process is entirely done, then the old file will be discarded. All this is done by compaction process. The database remains online during the compaction and all updates and reads are allowed to complete successfully.

Views

CouchDB 中的数据存储在半结构化文档中,这些文档以各个隐式结构为基础非常灵活,但它是一个用于数据存储和共享的简单文档模型。如果我们希望以多种不同的方式查看数据,我们需要一种方法来筛选、组织和报告尚未分解为表的数据。

Data in CouchDB is stored in semi-structured documents that are flexible with individual implicit structures, but it is a simple document model for data storage and sharing. If we want see our data in many different ways, we need a way to filter, organize and report on data that hasn’t been decomposed into tables.

为了解决这个问题,CouchDB 提供一个视图模型。视图是聚合同数据库中文档并对其报告的方法,并且根据需要进行构建以聚合、联接和报告数据库文档。由于视图是动态构建的,且不会影响基础文档,因此您可以拥有任意多个不同视图表示相同的同一数据。

To solve this problem, CouchDB provides a view model. Views are the method of aggregating and reporting on the documents in a database, and are built on-demand to aggregate, join and report on database documents. Because views are built dynamically and don’t affect the underlying document, you can have as many different view representations of the same data as you like.

History

  1. CouchDB was written in Erlang programming language.

  2. It was started by Damien Katz in 2005.

  3. CouchDB became an Apache project in 2008.

CouchDB 的当前版本是 1.61。

The current version of CouchDB is 1.61.

CouchDB - Installation

本章教您如何在 Windows 和 Linux 系统中安装 CouchDB。

This chapter teaches you how to install CouchDB in windows as well as Linux systems.

Installing CouchDB in Windows

Download CouchDB

CouchDB 的官方网站是 https://couchdb.apache.org 。如果您单击给定的链接,您可以获得如下所示的 CouchDB 官方网站主页。

The official website for CouchDB is https://couchdb.apache.org. If you click the given link, you can get the home page of the CouchDB official website as shown below.

download couchdb

如果您单击下载按钮,则会转到一个页面,其中提供了各种格式的 CouchDB 下载链接。以下快照对此进行了说明。

If you click on the download button that will lead to a page where download links of CouchDB in various formats are provided. The following snapshot illustrates the same.

couchdb formats

为 Windows 系统选择下载链接,并选择提供的其中一个镜像以开始下载。

Choose the download link for windows systems and select one of the provided mirrors to start your download.

Installing CouchDB

CouchDB 将以名为 setup-couchdb-1.6.1_R16B02.exe. 的安装文件形式下载到您的系统。运行安装文件并继续安装。

CouchDB will be downloaded to your system in the form of setup file named setup-couchdb-1.6.1_R16B02.exe. Run the setup file and proceed with the installation.

安装后,通过访问以下 * link: [role="bare"]http://127.0.0.1:5984/.* 打开 CouchDB 的内置 Web 界面。如果一切顺利,这将给您一个包含以下输出的网页。

After installation, open built-in web interface of CouchDB by visiting the following link: [role="bare"]http://127.0.0.1:5984/. If everything goes fine, this will give you a web page, which have the following output.

{
   "couchdb":"Welcome","uuid":"c8d48ac61bb497f4692b346e0f400d60",
   "version":"1.6.1",
   "vendor":{
      "version":"1.6.1","name":"The Apache Software Foundation"
   }
}

您可以使用以下 URL 与 CouchDB Web 界面进行交互 −

You can interact with the CouchDB web interface by using the following url −

http://127.0.0.1:5984/_utils/

这会向您展示 Futon 的索引页面,它是 CouchDB 的 Web 界面。

This shows you the index page of Futon, which is the web interface of CouchDB.

web interface

Installing CouchDB in Linux Systems

对于许多以 Linux 为基础的系统,它们内部提供了 CouchDB。若要安装此 CouchDB,请遵循说明。

For many of the Linux flavored systems, they provide CouchDB internally. To install this CouchDB follow the instructions.

在 Ubuntu 和 Debian 上,您可以使用 −

On Ubuntu and Debian you can use −

sudo aptitude install couchdb

在 Gentoo Linux 上有一个可用的 CouchDB ebuild −

On Gentoo Linux there is a CouchDB ebuild available −

sudo emerge couchdb

如果你的 Linux 系统没有 CouchDB,请遵循下一部分来安装 CouchDB 及其依赖项。

If your Linux system does not have CouchDB, follow the next section to install CouchDB and its dependencies.

Installing CouchDB Dependencies

以下是需要安装以获取系统中的 CouchDB 的依赖项列表−

Following is the list of dependencies that are to be installed to get CouchDB in your system−

  1. Erlang OTP

  2. ICU

  3. OpenSSL

  4. Mozilla SpiderMonkey

  5. GNU Make

  6. GNU Compiler Collection

  7. libcurl

  8. help2man

  9. Python for docs

  10. Python Sphinx

要安装这些依赖项,请在终端中键入以下命令。这里我们使用 Centos 6.5,并且以下命令将安装与 Centos 6.5 兼容的所需软件。

To install these dependencies, type the following commands in the terminal. Here we are using Centos 6.5 and the following commands will install the required softwares compatible to Centos 6.5.

$sudo yum install autoconf
$sudo yum install autoconf-archive
$sudo yum install automake
$sudo yum install curl-devel
$sudo yum install erlang-asn1
$sudo yum install erlang-erts
$sudo yum install erlang-eunit
$sudo yum install erlang-os_mon
$sudo yum install erlang-xmerl
$sudo yum install help2man
$sudo yum install js-devel
$sudo yum install libicu-devel
$sudo yum install libtool
$sudo yum install perl-Test-Harness

Note − 对于所有这些命令,你需要使用 sudo。以下过程将普通用户转换为 sudoer。

Note − For all these commands you need to use sudo. The following procedure converts a normal user to a sudoer.

  1. Login as root in admin user

  2. Open sudo file using the following command −

visudo
  1. Then edit as shown below to give your existing user the sudoer privileges −

Hadoop All=(All) All , and press esc : x to write the changes to the file.

在你的系统中下载完所有依赖项后,按照给定的说明下载 CouchDB。

After downloading all the dependencies in your system, download CouchDB following the given instructions.

Downloading CouchDB

Apache 软件基金会将不会提供 CouchDB 的完整 .tar 文件,所以你必须从源码安装它。

Apache software foundation will not provide the complete .tar file for CouchDB, so you have to install it from the source.

创建一个新目录来安装 CouchDB,浏览到这样的已创建目录并通过执行以下命令下载 CouchDB 源码 −

Create a new directory to install CouchDB, browse to such created directory and download CouchDB source by executing the following commands −

$ cd
$ mkdir CouchDB
$ cd CouchDB/
$ wget
http://www.google.com/url?q=http%3A%2F%2Fwww.apache.org%2Fdist%2Fcouchdb%2Fsource%2F1.6.1%2Fapache-couchdb-1.6.1.tar.gz

这将会在你系统中下载 CouchDB 源码文件。现在解压 apache-couchdb-1.6.1.tar.gz ,如下所示。

This will download CouchDB source file into your system. Now unzip the apache-couchdb-1.6.1.tar.gz as shown below.

$ tar zxvf apache-couchdb-1.6.1.tar.gz

Configuring CouchDB

要配置 CouchDB,请执行以下操作 −

To configure CouchDB, do the following −

  1. Browse to the home folder of CouchDB.

  2. Login as superuser.

  3. Configure using ./configure prompt as shown below −

$ cd apache-couchdb-1.6.1
$ su
Password:
# ./configure --with-erlang=/usr/lib64/erlang/usr/include/

它给你如下所示的输出,其中一行总结说 − You have configured Apache CouchDB, time to relax

It gives you the following output similar to that shown below with a concluding line saying − You have configured Apache CouchDB, time to relax.

# ./configure --with-erlang=/usr/lib64/erlang/usr/include/

checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking how to create a ustar tar archive... gnutar
………………………………………………………..
……………………….
config.status: creating var/Makefile
config.status: creating config.h
config.status: config.h is unchanged
config.status: creating src/snappy/google-snappy/config.h
config.status: src/snappy/google-snappy/config.h is unchanged
config.status: executing depfiles commands
config.status: executing libtool commands

You have configured Apache CouchDB, time to relax.

Run `make && sudo make install' to install.

Installing CouchDB

现在键入以下命令以在你的系统中安装 CouchDB。

Now type the following command to install CouchDB in your system.

# make && sudo make install

它在你的系统中安装 CouchDB,其中一行总结说 − You have installed Apache CouchDB, time to relax

It installs CouchDB in your system with a concluding line saying − You have installed Apache CouchDB, time to relax.

Starting CouchDB

要启动 CouchDB,请浏览到 CouchDB 主文件夹并使用以下命令 −

To start CouchDB, browse to the CouchDB home folder and use the following command −

$ cd apache-couchdb-1.6.1
$ cd etc
$ couchdb start

CouchDB 的输出:−

It starts CouchDB giving the following output: −

Apache CouchDB 1.6.1 (LogLevel=info) is starting.
Apache CouchDB has started. Time to relax.
[info] [lt;0.31.0gt;] Apache CouchDB has started on http://127.0.0.1:5984/
[info] [lt;0.112.0gt;] 127.0.0.1 - - GET / 200
[info] [lt;0.112.0gt;] 127.0.0.1 - - GET /favicon.ico 200

Verification

由于 CouchDB 是一个网络界面,试着用浏览器中输入以下主页 URL:

Since CouchDB is a web interface, try to type the following homepage url in the browser.

http://127.0.0.1:5984/

产出如下所示 −

It produces the following output −

{
   "couchdb":"Welcome",
   "uuid":"8f0d59acd0e179f5e9f0075fa1f5e804",
   "version":"1.6.1",
   "vendor":{
      "name":"The Apache Software Foundation",
      "version":"1.6.1"
   }
}

CouchDB - Curl & Futon

cURL Utility

cURL 实用程序是一种与 CouchDB 通信的方法。

cURL utility is a way to communicate with CouchDB.

它是一种使用支持协议(HTTP、HTTPS、FTP、FTPS、TFTP、DICT、TELNET、LDAP 或 FILE)之一,从服务器或向服务器传输数据的工具。这个命令设计为无需用户互动即可工作。cURL 提供了一系列的实用技巧,如代理支持、用户认证、ftp 上传、HTTP Post、SSL (https:) 连接、cookie、文件传输恢复等。

It is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, TFTP, DICT, TELNET, LDAP or FILE). The command is designed to work without user interaction. cURL offers a busload of useful tricks like proxy support, user authentication, ftp upload, HTTP post, SSL (https:) connections, cookies, file transfer resume and more.

cURL 实用程序在 UNIX、Linux、Mac OS X 和 Windows 等操作系统中可用。它是一个命令行实用程序,用户可以用它直接从命令行访问 HTTP 协议。本章将指导你如何使用 cURL 实用程序。

The cURL utility is available in operating systems such as UNIX, Linux, Mac OS X and Windows. It is a command line utility using which user can access HTTP protocol straight away from the command line. This chapter teaches you how to use cURL utility.

Using cURL Utility

你可以通过简单地输入 cURL 及其后跟网站地址来使用 cURL 实用程序访问任何网站,如下所示:−

You can access any website using cURL utility by simply typing cURL followed by the website address as shown below −

curl www.tutorialspoint.com/

默认情况下,cURL 实用程序返回请求页面源代码。它在终端窗口中显示此代码。

By default, the cURL utility returns the source code of the requested page. It displays this code on the terminal window.

cURL Utility Options

cURL 实用程序提供多种选项供使用,你可以在 cURL 使用帮助中查看它们。

cURL utility provides various options to work with, and you can see them in cURL utility help.

以下代码展示了 cURL 帮助的其中一部分。

The following code shows some portion of cURL help.

$ curl --help
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
      --anyauth Pick "any" authentication method (H)
   -a/--append Append to target file when uploading (F/SFTP)
      --basic Use HTTP Basic Authentication (H)
      --cacert <file> CA certificate to verify peer against (SSL)
-d/--data <data> HTTP POST data (H)
      --data-ascii <data> HTTP POST ASCII data (H)
      --data-binary <data> HTTP POST binary data (H)
      --data-urlencode <name=data/name@filename> HTTP POST data
urlencoded (H)
      --delegation STRING GSS-API delegation permission
      --digest Use HTTP Digest Authentication (H)
      --disable-eprt Inhibit using EPRT or LPRT (F)
      --disable-epsv Inhibit using EPSV (F)

   -F/--form <name=content> Specify HTTP multipart POST data (H)
      --form-string <name=string> Specify HTTP multipart POST data (H)
      --ftp-account <data> Account data to send when requested by server
(F)
      --ftp-alternative-to-user <cmd> String to replace "USER [name]" (F)
      --ftp-create-dirs Create the remote dirs if not present (F)
      --ftp-method [multi cwd/no cwd/single cwd] Control CWD usage (F)
      --ftp-pasv Use PASV/EPSV instead of PORT (F)

   -G/--get Send the -d data with a HTTP GET (H)

   -H/--header <line> Custom header to pass to server (H)
   -I/--head Show document info only
   -h/--help This help text
      --hostpubmd5 <md5> Hex encoded MD5 string of the host public key.
(SSH)
   -0/--http1.0 Use HTTP 1.0 (H)
      --ignore-content-length Ignore the HTTP Content-Length header
   -i/--include Include protocol headers in the output (H/F)

   -M/--manual Display the full manual

   -o/--output <file> Write output to <file> instead of stdout
      --pass <pass> Pass phrase for the private key (SSL/SSH)
      --post301 Do not switch to GET after following a 301
redirect (H)
      --post302 Do not switch to GET after following a 302
redirect (H)
   -O/--remote-name Write output to a file named as the remote file
      --remote-name-all Use the remote file name for all URLs
   -R/--remote-time Set the remote file's time on the local output
   -X/--request <command> Specify request command to use
      --retry <num> Retry request <num> times if transient problems
occur
      --retry-delay <seconds> When retrying, wait this many seconds
between each
      --retry-max-time <seconds> Retry only within this period
   -T/--upload-file <file> Transfer <file> to remote site
      --url <URL> Set URL to work with
   -B/--use-ascii Use ASCII/text transfer

在与 CouchDB 通信时,我们大量地使用了 cURL 实用程序的某些选项。以下是 cURL 实用程序部分重要选项的简要说明,包括 CouchDB 使用的选项。

While communicating with CouchDB, certain options of cURL utility were extensively used. Following are the brief descriptions of some important options of cURL utility including those used by CouchDB.

-X flag

(HTTP) 指定在与 HTTP 服务器通信时使用的自定义请求方法。已指定请求代替已使用的方法(默认为 GET)。完整信息和解释,请阅读 HTTP 1.1 规范。

(HTTP) Specifies a custom request method used when communicating with the HTTP server. The specified request is used instead of the method otherwise used (which defaults to GET). Read the HTTP 1.1 specification for details and explanations.

(FTP) 与使用 ftp 进行文件列表时指定一个自定义 FTP 命令,以代替 LIST。

(FTP) Specifies a custom FTP command to use instead of LIST when doing file lists with ftp.

-H

(HTTP) 获取网页时使用额外的报头。注意,如果你添加了一个自定义报头,该报头与 cURL 将要使用的内部报头具有相同的名称,那么你的外部设置报头将代替内部报头。这使你可以完成 cURL 通常无法完成的即使更加棘手的操作。你不应该在不明白自己所做的事情的情况下替换内部设置报头。用冒号右侧没有内容的报头替换内部报头将防止该报头出现。

(HTTP) Extra header is used when getting a web page. Note that if you add a custom header that has the same name as one of the internal ones cURL would use, your externally set header will be used instead of the internal one. This allows you to make even trickier work than cURL would normally do. You should not replace internally set headers without perfectly knowing what you’re doing. Replacing an internal header with the one without content on the right side of the colon, will prevent that header from appearing.

cURL 确保你添加/替换的每个报头使用适当的行尾标记发送。你也不应该将此作为报头内容的一部分添加,也不应该添加换行符或回车符来弄乱。

cURL assures that each header you add/replace get sent with the proper end of line marker. Neither you should add that as a part of the header content nor add newlines or carriage returns to disorder things.

另请参阅 -A/--user-agent 和 -e/--referer 选项。

See also the -A/--user-agent and -e/--referer options.

此选项可以多次使用,以添加/替换/删除多个报头。

This option can be used multiple times to add/replace/remove multiple headers.

-d flag

使用 cURL 的此标记,你可以将数据与 HTTP POST 请求一起发送到服务器,就好像用户通过表单填写并提交数据一样。

Using this flag of cURL, you can send data along with the HTTP POST request to the server, as if it was filled by the user in the form and submitted.

Example

假设有一个网站,你想使用以下 cURL 实用程序的 –d 标记登录其中或向该网站发送一些数据。

Suppose there is a website and you want to login into it or send some data to the website using –d flag of cURL utility as shown below.

curl -X PUT http://mywebsite.com/login.html -d userid=001 -d password=tutorialspoint

它发送一个看起来像 "userid=001&password=tutorialspoint" 的 post 块。同样地,你也可以使用 -d 标记发送文档 (JSON)。

It sends a post chunk that looks like "userid=001&password=tutorialspoint". Likewise you can also send documents (JSON ) using -d flag.

-o flag

使用此标志,cURL 将请求输出写入文件。

Using this flag, cURL writes the output of the request to a file.

Example

以下示例显示了 cURL 实用工具的 -o 标志的用法。

The following example shows the use of -o flag of cURL utility.

$ curl -o example.html www.tutorialspoint.com/index.htm
% Total % Received % Xferd Average Speed Time Time Time Current
      Dload Upload Total Spent Left Speed
100 81193 0 81193 0 0 48168 0 --:--:-- 0:00:01 --:--:--
58077

它获取 tutorialspoint.com 主页的源代码,创建一个名为 example.com 的文件并将输出保存在名为 example.html 的文件中。

This gets the source code of the homepage of tutorialspoint.com, creates a file named example.com and saves the output in the file named example.html.

以下是 example.html 的快照。

Following is the snapshot of the example.html.

example html

-O

此标志类似于 –o ,唯一的区别是使用此标志,会创建一个与请求的 URL 同名的文件,并将请求的 URL 的源代码复制到其中。

This flag is similar to –o, the only difference is with this flag, a new file with the same name as the requested url was created, and the source code of the requested url will be copied to it.

Example

以下示例显示了 cURL 实用工具的 -O 标志的用法。

The following example shows the use of -O flag of cURL utility.

$ curl -O www.tutorialspoint.com/index.htm
% Total % Received % Xferd Average Speed Time Time Time Current
      Dload Upload Total Spent Left
Speed
100 81285 0 81285 0 0 49794 0 --:--:-- 0:00:01 --:--:--
60077

它创建一个名为 index.htm 的文件,并将 tutorialspoint.com 索引页的源代码保存在其中。

It creates a new file with the name index.htm and saves the source code of the index page of tutorialspoint.com in it.

Hello CouchDB

您可以通过向已安装的 CouchDB 实例发送 GET 请求来访问 CouchDB 主页。首先,确保您已在 Linux 环境中安装 CouchDB 并且它运行成功,然后使用以下语法向 CouchDB 实例发送 get 请求。

You can access the homepage of the CouchDB by sending a GET request to the CouchDB instance installed. First of all make sure you have installed CouchDB in your Linux environment and it is running successfully, and then use the following syntax to send a get request to the CouchDB instance.

curl http://127.0.0.1:5984/

这会向您提供如以下所示的 JSON 文档,其中 CouchDB 指定了详细信息,例如版本号、供应商名称和软件版本。

This gives you a JSON document as shown below where CouchDB specifies the details such as version number, name of the vendor, and version of the software.

$ curl http://127.0.0.1:5984/
{
   "couchdb" : "Welcome",
   "uuid" : "8f0d59acd0e179f5e9f0075fa1f5e804",
   "version" : "1.6.1",
   "vendor" : {
      "name":"The Apache Software Foundation",
      "version":"1.6.1"
   }
}

List of All Databases

您可以发送 get 请求以及字符串 "_all_dbs string " ,以获取所创建的所有数据库的列表。以下是要获取 CouchDB 中所有数据库列表的语法。

You can get the list of all the databases created, by sending a get request along with the string "_all_dbs string ". Following is the syntax to get the list of all databases in CouchDB.

curl -X GET http://127.0.0.1:5984/_all_dbs

它向您提供以下所示的 CouchDB 中所有数据库的列表。

It gives you the list of all databases in CouchDB as shown below.

$ curl -X GET http://127.0.0.1:5984/_all_dbs
[ "_replicator" , "_users" ]

Creating a Database

您可以使用具有以下语法的 PUT 标头的 cURL 在 CouchDB 中创建数据库 −

You can create a database in CouchDB using cURL with PUT header using the following syntax −

$ curl -X PUT http://127.0.0.1:5984/database_name

Example

例如,使用上述给定的语法,创建一个名为 my_database 的数据库,如下所示。

As an example, using the above given syntax create a database with name my_database as shown below.

$ curl -X PUT http://127.0.0.1:5984/my_database
{"ok":true}

Verification

通过列出所有数据库,验证数据库是否已创建,如下所示。在这里,您可以在列表中看到新创建的数据库 "my_database" 的名称。

Verify whether the database is created, by listing out all the databases as shown below. Here you can observe the name of newly created database, "my_database" in the list

$ curl -X GET http://127.0.0.1:5984/_all_dbs

[ "_replicator " , "_users" , "my_database" ]

Getting Database Info

您可以使用 get 请求以及数据库名称来获取数据库的信息。以下是要获取数据库信息的语法。

You can get the information about database using the get request along with the database name. Following is the syntax to get the database information.

Example

例如让我们获取名为 my_database 的数据库的信息,如下所示。在这里,您可以得到您的数据库信息的响应。

As an example let us get the information of the database named my_database as shown below. Here you can get the information about your database as a response.

$ curl -X GET http://127.0.0.1:5984/my_database

{
   "db_name" : "my_database",
   "doc_count" : 0,
   "doc_del_count" : 0,
   "update_seq" : 0,
   "purge_seq" : 0,
   "compact_running" : false,
   "disk_size" : 79,
   "data_size" : 0,
   "instance_start_time" : "1423628520835029",
   "disk_format_version" : 6,
   "committed_update_seq" : 0
 }

Futon

Futon 是 CouchDB 内置的基于 Web 的管理界面。它提供了一个简单的图形界面,可用于与 CouchDB 交互。它是一个朴素的界面,并提供了对所有 CouchDB 功能的完全访问。以下是这些功能的列表 −

Futon is the built-in, web based, administration interface of CouchDB. It provides a simple graphical interface using which you can interact with CouchDB. It is a naive interface and it provides full access to all CouchDB features. Following is the list of those features −

  1. Creates databases.

  2. Destroys databases.

  3. Creates documents.

  4. Updates documents.

  5. Edits documents.

  6. Deletes documents.

Starting Futon

确保 CouchDB 正在运行,然后在浏览器中打开以下 URL −

Make sure CouchDB is running and then open the following url in browser −

http://127.0.0.1:5984/_utils/

如果您打开此 URL,它将显示以下所示的 Futon 主页 −

If you open this url, it displays the Futon home page as shown below −

futon homepage
  1. On the left hand side of this page you can observe the list of all the current databases of CouchDB. In this illustration, we have a database named my_database, along with system defined databases _replicator and _user.

  2. On the right hand side you can see the following − Tools − In this section you can find Configuration to configure CouchDB, Replicator to perform replications, and Status to verify status of CouchDB and recent modifications done on CouchDB. Documentation − This section contains the complete documentation for the recent version of CouchDB. Diagnostics − Under this you can verify the installation of CouchDB. Recent Databases − Under this you can find the names of recently added databases.

CouchDB - HTTP API

使用 HTTP 请求头,你可以与 CouchDB 通信。通过这些请求,我们可以从数据库中检索数据,以文档的形式将数据存储到数据库中,并且我们可以查看以及格式化存储在数据库中的文档。

Using HTTP request headers, you can communicate with CouchDB. Through these requests we can retrieve data from the database, store data in to the database in the form of documents, and we can view as well as format the documents stored in a database.

HTTP Request Formats

在与数据库通信时,我们将使用不同的请求格式,如 get、head、post、put、delete 和 copy。对于 CouchDB 中的所有操作,输入数据和输出数据结构将采用 JavaScript 对象表示法 (JSON) 对象的形式。

While communicating with the database we will use different request formats like get, head, post, put, delete, and copy. For all operations in CouchDB, the input data and the output data structures will be in the form of JavaScript Object Notation (JSON) object.

以下是用于与 CouchDB 通信的 HTTP 协议的不同请求格式。

Following are the different request formats of HTTP Protocol used to communicate with CouchDB.

  1. GET − This format is used to get a specific item. To get different items, you have to send specific url patterns. In CouchDB using this GET request, we can get static items, database documents and configuration, and statistical information in the form of JSON documents (in most cases).

  2. HEAD − The HEAD method is used to get the HTTP header of a GET request without the body of the response.

  3. POST − Post request is used to upload data. In CouchDB using POST request, you can set values, upload documents, set document values, and can also start certain administration commands.

  4. PUT − Using PUT request, you can create new objects, databases, documents, views and design documents.

  5. DELETE − Using DELETE request, you can delete documents, views, and design documents.

  6. COPY − Using COPY method, you can copy documents and objects.

HTTP Request Headers

应提供 HTTP 头部来获取正确的格式和编码。在向 CouchDB 服务器发送请求时,你可以随同请求发送 Http 请求头。以下是不同的 Http 请求标头。

HTTP headers should be supplied to get the right format and encoding. While sending the request to the CouchDB server, you can send Http request headers along with the request. Following are the different Http request headers.

  1. Content-type − This Header is used to specify the content type of the data that we supply to the server along with the request. Mostly the type of the content we send along with the request will be MIME type or JSON (application/json). Using Content-type on a request is highly recommended.

  2. Accept − This header is used to specify the server, the list of data types that client can understand, so that the server will send its response using those data types. Generally here, you can send the list of MIME data types the client accepts, separated by colons. Though, using Accept in queries of CouchDB is not required, it is highly recommended to ensure that the data returned can be processed by the client.

Response Headers

这些是由服务器发送的响应头。这些标头提供有关服务器作为响应发送的内容的信息。

These are the headers of the response sent by the server. These headers give information about the content send by the server as response.

  1. Content-type − This header specifies the MIME type of the data returned by the server. For most request, the returned MIME type is text/plain.

  2. Cache-control − This header suggests the client about treating the information sent by the server. CouchDB mostly returns the must-revalidate, which indicates that the information should be revalidated if possible.

  3. Content-length − This header returns the length of the content sent by the server, in bytes.

  4. Etag − This header is used to show the revision for a document, or a view.

Status Codes

以下是在 http 标头中发送的状态代码的表格形式及其说明。

Following is the tabular form of the status code sent by the http header and the description of it.

Sr.No.

Status Code & Description

1

200 − OK This status will be issued when a request completed successfully.

2

201 − Created This status will be issued when a document is created.

3

202 − Accepted This status will be issued when a request is accepted.

4

404 − Not Found This status will be issued when the server is unable to find the requested content.

5

405 − Resource Not Allowed This status is issued when the HTTP request type used is invalid.

6

409 − Conflict This status is issued whenever there is any update conflict.

7

415 − Bad Content Type This status indicated that the requested content type is not supported by the server.

8

500 − Internal Server Error This status is issued whenever the data sent in the request is invalid.

HTTP URL Paths

可以通过某些 URL 路径直接与数据库交互。以下是此类 URL 路径的表格形式。

There are certain url paths using which, you can interact with the database directly. Following is the tabular format of such url paths.

Sr.No.

URL & Operation

1

PUT /db This url is used to create a new database.

2

GET /db This url is used to get the information about the existing database.

3

PUT /db/document This url is used to create a document/update an existing document.

4

GET /db/document This url is used to get the document.

5

DELETE /db/document This url is used to delete the specified document from the specified database.

6

GET /db/_design/design-doc This url is used to get the definition of a design document.

7

GET /db/_design/designdoc/_view/view-name This url is used to access the view, view-name from the design document from the specified database.

CouchDB - Creating a Database

数据库是 CouchDB 中最外层的 data 结构,用于存储您的文档。您可以使用 CouchDB 提供的 cURL 实用程序以及 CouchDB 的 Web 界面 Futon 来创建这些数据库。

Database is the outermost data structure in CouchDB where your documents are stored. You can create these databases using cURL utility provided by CouchDB, as well as Futon the web interface of CouchDB.

Creating a Database using cURL Utility

您可以通过 cURL 实用程序使用 PUT 方法向服务器发送一个 HTTP 请求在 CouchDB 中创建一个数据库。以下是创建数据库的语法:

You can create a database in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a database −

$ curl -X PUT http://127.0.0.1:5984/database name

使用 −X ,我们可以指定要使用的 HTTP 自定义请求方法。在此情况下,我们使用 PUT 方法。当使用 PUT 操作/方法时,url 的内容指定我们使用 HTTP 请求创建的对象名称。此处我们必须在 url 中使用 put 请求发送数据库的名称来创建数据库。

Using −X we can specify HTTP custom request method to be used. In this case, we are using PUT method. When we use the PUT operation/method, the content of the url specifies the object name we are creating using HTTP request. Here we have to send the name of the database using put request in the url to create a database.

Example

如果您想使用上述给定的语法创建一个名为 my_database 的数据库,则可以按照以下方式创建:

Using the above given syntax if you want to create a database with name my_database, you can create it as follows

curl -X PUT http://127.0.0.1:5984/my_database
{
   "ok":true
}

作为响应,服务器将返回一个 JSON 文档,其中内容为 “ok”true ,表示操作成功。

As a response the server will return you a JSON document with content “ok”true indicating the operation was successful.

Verification

通过如下所示列出所有数据库,验证是否已创建数据库。此处您可以在列表中观察到新创建的数据库 " my_database " 的名称。

Verify whether the database is created, by listing out all the databases as shown below. Here you can observe the name of a newly created database, " my_database " in the list.

$ curl -X GET http://127.0.0.1:5984/_all_dbs

[ "_replicator " , " _users " , " my_database " ]

Creating a Database using Futon

要创建数据库,请打开 http://127.0.0.1:5984/_utils/ 。您将获得如下所示的 CouchDB 概览/索引页面。

To create a database open the http://127.0.0.1:5984/_utils/. You will get an Overview/index page of CouchDB as shown below.

futon homepage

在此页面中,您可以看到 CouchDB 中的数据库列表,左侧有一个创建数据库选项按钮。

In this page, you can see the list of databases in CouchDB, an option button Create Database on the left hand side.

现在,点击创建数据库链接。您可以看到一个弹出窗口 Create New Databases ,询问新数据库的数据库名称。根据所述条件选择任意名称。此处我们创建一个名为 tutorials_point 的新数据库。点击屏幕截图中所示的创建按钮。

Now click on the create database link. You can see a popup window Create New Databases asking for the database name for the new database. Choose any name following the mentioned criteria. Here we are creating another database with name tutorials_point. Click on the create button as shown in the following screenshot.

create database

CouchDB - Deleting a Database

Deleting a Database using cURL Utility

您可以通过使用 DELETE 方法,通过 cURL 实用程序向服务器发送请求来删除 CouchDB 中的数据库。以下是在 CouchDB 中创建数据库的语法:

You can delete a database in CouchDB by sending a request to the server using DELETE method through cURL utility. Following is the syntax to create a database −

$ curl -X DELETE http://127.0.0.1:5984/database name

使用 −X ,我们可以指定在与 HTTP 服务器通信时使用的 HTTP 自定义请求方法。在此情况下,我们使用 DELETE 方法。向服务器发送 url,并在其中指定要删除的数据库。

Using −X we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using the DELETE method. Send the url to the server by specifying the database to be deleted in it.

Example

假设 CouchDB 中有一个名为 my_database2 的数据库。如果您想使用上述给定的语法删除它,则可以按照以下方式进行:

Assume there is a database named my_database2 in CouchDB. Using the above given syntax if you want to delete it, you can do it as follows −

$ curl -X DELETE http://127.0.0.1:5984/my_database2
{
   "ok" : true
}

作为响应,服务器将返回一个 JSON 文档,其中内容为 “ok”true ,表示操作成功。

As a response, the server will return you a JSON document with content “ok”true indicating the operation was successful.

Verification

通过如下所示列出所有数据库,验证是否已删除数据库。此处您可以观察到已删除数据库 "my_database" 的名称不在列表中。

Verify whether the database is deleted by listing out all the databases as shown below. Here you can observe the name of the deleted database, "my_database" is not there in the list.

$ curl -X GET http://127.0.0.1:5984/_all_dbs

[ "_replicator " , " _users " ]

Deleting a Database using Futon

要删除数据库,请打开 http://127.0.0.1:5984/_utils/ url,您将获得如下所示的 CouchDB 概览/索引页面。

To delete a database, open the http://127.0.0.1:5984/_utils/ url where you will get an Overview/index page of CouchDB as shown below.

delete database1

此处您可以看到三个用户创建的数据库。让我们删除名为 tutorials_point2 的数据库。要删除数据库,请从数据库列表中选择一个,然后单击它,这将转到所选数据库的概览页面,您可以在其中查看数据库的各种操作。以下屏幕截图显示了相同的页面:

Here you can see three user created databases. Let us delete the database named tutorials_point2. To delete a database, select one from the list of databases, and click on it, which will lead to the overview page of the selected database where you can see the various operations on databases. The following screenshot shows the same −

delete database2

在这些选项中,您可以找到 Delete Database 选项。通过单击它,您将获得一个弹出窗口,询问您是否确定!单击删除以删除所选数据库。

Among them you can find Delete Database option. By clicking on it you will get a popup window, asking whether you are sure! Click on delete, to delete the selected database.

delete database3

CouchDB - Creating a Document

文档是 CouchDB 的中心数据结构。数据库的内容将以文档形式而不是表的形式存储。您可以使用 CouchDB 和 Futon 提供的 cURL 实用程序来创建这些文档。本章涵盖在数据库中创建文档的方法。

Documents are CouchDB’s central data structure. Contents of the database will be stored in the form of Documents instead of tables. You can create these documents using cURL utility provided by CouchDB, as well as Futon. This chapter covers the ways to create a document in a database.

CouchDB 中的每个文档都有一个唯一的 ID。您可以选择您自己的 ID,它应该是字符串形式。通常使用 UUID(通用唯一标识符),它们是随机数,产生重复的可能性最小。首选这些以避免冲突。

Each document in CouchDB has a unique ID. You can choose your own ID that should be in the form of a string. Generally, UUID (Universally Unique IDentifier) is used, which are random numbers that have least chance of creating a duplicate. These are preferred to avoid collisions.

Creating a Document using cURL Utility

您可以使用 PUT 方法向服务器发送 HTTP 请求,通过 cURL 实用程序在 CouchDB 中创建一个文档。以下是在 CouchDB 中创建文档的语法:

You can create a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to create a document.

$ curl -X PUT http://127.0.0.1:5984/database name/"id" -d ' { document} '

使用 −X ,我们可以指定在与 HTTP 服务器通信时使用的 HTTP 自定义请求方法。在此情况下,我们使用 PUT 方法。当我们使用 PUT 方法时,url 的内容指定我们使用 HTTP 请求创建的对象名称。此处我们必须发送以下内容:

Using −X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using PUT method. When we use the PUT method, the content of the url specifies the object name we are creating using the HTTP request. Here we have to send the following −

  1. The name of the database name in which we are creating the document.

  2. The document id.

  3. The data of the document. −d option is used to send the data/document through HTTP request. While writing a document simply enter your Field-Value pairs separated by colon, within flower brackets as shown below −

{
   Name : Raju
   age : 23
   Designation : Designer
}

Example

使用上述给出的语法,如果你想在名称为 my_database 的数据库中使用 id 001 创建文档,那么你可以按照如下所示进行创建。

Using the above given syntax if you want to create a document with id 001 in a database with name my_database, you can create it as shown below.

$ curl -X PUT http://127.0.0.1:5984/my_database/"001" -d
'{ " Name " : " Raju " , " age " :" 23 " , " Designation " : " Designer " }'

{"ok":true,"id":"001","rev":"1-1c2fae390fa5475d9b809301bbf3f25e"}

CouchDB 对此请求的响应包含三个字段 −

The response of CouchDB to this request contains three fields −

  1. "ok", indicating the operation was successful.

  2. "id", which stores the id of the document and

  3. "rev", this indicates the revision id. Every time you revise (update or modify) a document a _rev value will be generated by CouchDB. If you want to update or delete a document, CouchDB expects you to include the _rev field of the revision you wish to change. When CouchDB accepts the change, it will generate a new revision number. This mechanism ensures concurrency control.

Verification

如果你想查看创建的文档,可以使用文档按如下所示获取。

If you want to view the created document you can get it using the document as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "1-3fcc78daac7a90803f0a5e383f4f1e1e",
   "Name": "Raju",
   "age": 23,
   "Designation": "Designer"
}

Creating a Document using Futon

要创建文档,请打开 http://127.0.0.1:5984/_utils/ url 以获取 CouchDB 的概述/索引页面,如下所示。

To Create a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below.

create document

选择你要在其中创建文档的数据库。打开数据库的概述页面,然后选择 New Document 选项,如下所示。

Select the database in which you want to create the document. Open the Overview page of the database and select New Document option as shown below.

new document

当你选择 New Document 选项时,CouchDB 创建一个新的数据库文档,分配给它一个新的 id。你可以编辑 id 的值,并且可以以字符串的形式分配你自己的值。在下面的插图中,我们使用 id 001 创建了一个新文档。

When you select the New Document option, CouchDB creates a new database document, assigning it a new id. You can edit the value of the id and can assign your own value in the form of a string. In the following illustration, we have created a new document with an id 001.

new document id

在此页面,你可以观察到三个选项 − 保存文档、添加字段和上传附件。

In this page, you can observe three options − save Document, Add Field and Upload Attachment.

Add Field to the Document

要向文档中添加字段,请单击 Add Field 选项。在创建数据库之后,你可以使用此选项向其中添加字段。单击它将获得一对文本框,即 Field, value. 你可以单击它们来编辑这些值。编辑这些值并输入你想要的字段-值对。单击绿色按钮保存这些值。

To add field to the document click on Add Field option. After creating a database, you can add a field to it using this option. Clicking on it will get you a pair of text boxes, namely, Field, value. You can edit these values by clicking on them. Edit those values and type your desired Field-Value pair. Click on the green button to save these values.

在下面的插图中,我们创建了员工的三个字段姓名、年龄和职务。

In the following illustration, we have created three fields Name, age and, Designation of the employee.

create field

Save Document

你可以单击此选项保存对文档所做的更改。保存后,将生成一个新的 id _rev ,如下所示。

You can save the changes made to the document by clicking on this option. After saving, a new id _rev will be generated as shown below.

save document

CouchDB - Updating a Document

Updating Documents using cURL

你可以使用 cURL 实用程序通过使用 PUT 方法向服务器发送 HTTP 请求来更新 CouchDB 中的文档。以下是对文档进行更新的语法。

You can update a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to update a document.

curl -X PUT http://127.0.0.1:5984/database_name/document_id/ -d '{ "field" : "value", "_rev" : "revision id" }'

Example

假设在名为 my_database 的数据库中有一个 id 为 001 的文档。你可以按照如下所示删除此内容。

Suppose there is a document with id 001 in the database named my_database. You can delete this as shown below.

首先,获取要更新的文档的修订 id。你可以在文档本身中找到文档的 _rev ,因此按如下所示获取文档。

First of all, get the revision id of the document that is to be updated. You can find the _rev of the document in the document itself, therefore get the document as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id" : "001",
   "_rev" : "2-04d8eac1680d237ca25b68b36b8899d3 " ,
   "age" : "23"
}

从文档中使用修订 id _rev 更新文档。在这里,我们将年龄从 23 更新为 24。

Use revision id _rev from the document to update the document. Here we are updating the age from 23 to 24.

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

{ " ok " : true , " id " : " 001 " , " rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " }

Verification

若要验证文档,请按如下所示使用 GET 请求再次获取文档。

To verify the document, get the document again using GET request as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   " _id " : " 001 ",
   " _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " ,
   " age " : " 23 "
 }

以下是更新文档时需要指出的几个要点。

Following are some important points to be noted while updating a document.

  1. The URL we send in the request containing the database name and the document id.

  2. Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID.

  3. We have to supply the revision number as a part of the JSON request.

  4. In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number.

Updating Documents using Futon

若要删除文档,请打开 http://127.0.0.1:5984/_utils/ URL 以获取如下图所示的 CouchDB 的概述/索引页面。

To delete a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below.

create document

选择存在待更新文档的数据库并单击它。我们在此更新名为 tutorials_point 的数据库中的一个文档。你将获得数据库中的文档列表,如下图所示。

Select the database in which the document to be updated exists and click it. Here we are updating a document in the database named tutorials_point. You will get the list of documents in the database as shown below.

update document

选择要更新的文档并单击它。你将获得文档的内容,如下图所示。

Select a document that you want to update and click on it. You will get the contents of the documents as shown below.

document contents

在此,若要将位置从德里更新为海得拉巴,请单击文本框,编辑字段,然后单击绿色按钮以保存更改,如下图所示。

Here, to update the location from Delhi to Hyderabad, click on the text box, edit the field, and click the green button to save the changes as shown below.

save changes

CouchDB - Deleting a Document

Deleting a Document using cURL Utility

你可以通过使用 cURL 实用工具通过 DELETE 方法向服务器发送 HTTP 请求,在 CouchDB 中删除文档。以下是删除文档的语法。

You can delete a document in CouchDB by sending an HTTP request to the server using DELETE method through cURL utility. Following is the syntax to delete a document.

curl -X DELETE http : // 127.0.0.1:5984 / database name/database id?_rev id

使用 −X, ,我们可以指定与 HTTP 服务器通信时正在使用的自定义 HTTP 请求方法。在本例中,我们正在使用 Delete 方法。删除数据库 /database_name/database_id/ 不够。你必须通过 URL 传递最近的版本 ID。若要提及任何数据结构的属性,请使用 "?"

Using −X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using Delete method. To delete a database /database_name/database_id/ is not enough. You have to pass the recent revision id through the url. To mention attributes of any data structure "?" is used.

Example

假设名为 my_database 的数据库中有一个文档,其文档 ID 为 001。要删除此文档,你必须获取该文档的修订版 ID。按照如下所示获取文档数据。

Suppose there is a document in database named my_database with document id 001. To delete this document, you have to get the rev id of the document. Get the document data as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   " _id " : " 001 ",
   " _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " ,
   " age " : " 23 "
}

现在指定待删除的文档的版本 ID、文档 ID 以及文档所属的数据库名称,如下所示:

Now specify the revision id of the document to be deleted, id of the document, and database name the document belongs to, as shown below −

$ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-
3fcc78daac7a90803f0a5e383f4f1e1e

{"ok":true,"id":"001","rev":"2-3a561d56de1ce3305d693bd15630bf96"}

Verification

若要验证文档是否被删除,请尝试使用 GET 方法获取文档。由于你要获取已删除的文档,这会给你一个错误消息,如下所示:

To verify whether the document is deleted, try to fetch the document by using the GET method. Since you are fetching a deleted document, this will give you an error message as shown below −

$ curl -X GET http://127.0.0.1:5984/my_database/001
{"error":"not_found","reason":"deleted"}

Deleting a Document using Futon

首先,验证数据库中的文档。以下是名为 tutorials_point 的数据库的快照。

First of all, verify the documents in the database. Following is the snapshot of the database named tutorials_point.

deleting document

你可以在此观察到,数据库包含三个文档。若要删除其中任何文档,如 003, ,请执行以下操作:

Here you can observe, the database consists of three documents. To delete any of the documents say 003, do the following −

  1. Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs.

  2. This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document.

  3. Click on Delete Document option.

  4. You will get a dialog box saying "Are you sure you want to delete this document?" Click on delete, to delete the document.

delete document2

CouchDB - Attaching Files

Attaching Files using cURL

你可以像电子邮件一样附加文件到 CouchDB。文件包含元数据,例如名称,以及包含的 MIME 类型和附件包含的字节数。若要将文件附加到文档中,你必须向服务器发送 PUT 请求。以下是要将文件附加到文档中的语法代码:

You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document −

$ curl -vX PUT http://127.0.0.1:5984/database_name/database_id
/filename?rev=document rev_id --data-binary @filename -H "Content-Type:
type of the content"

请求具有多种选项,如下所示:

The request has various options that are explained below.

  1. --data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body.

  2. -H − This option is used to mention the content type of the file we are going to upload.

Example

让我们通过向 CouchDB 发送 PUT 请求,将名为 boy.jpg, 的文件附加到数据库中 ID 为 001, 的文档上。在此之前,你必须获取 ID 为 001 的文档的数据,才能获取其当前 rev ID,如下所示:

Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "1-967a00dff5e02add41819138abb3284d"
}

现在,使用 _rev 值,向 CouchDB 服务器发送 PUT 请求,如下所示:

Now using the _rev value, send the PUT request to the CouchDB server as shown below.

$ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1-
967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H "ContentType:
image/jpg"

Verification

若要验证附件是否已上传,请获取文档内容,如下所示:

To verify whether the attachment is uploaded, fetch the document content as shown below−

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "2-4705a219cdcca7c72aac4f623f5c46a8",
   "_attachments": {
      "boy.jpg": {
         "content_type": "image/jpg",
         "revpos": 2,
         "digest": "md5-9Swz8jvmga5mfBIsmCxCtQ==",
         "length": 91408,
         "stub": true
      }
   }
}

Attaching Files using Futon

Upload Attachment

使用此选项,你可以将新附件(例如文件、图像或文档)上传到数据库。为此,请点击 Upload Attachment 按钮。将出现一个对话框,你可以在其中选择要上传的文件。选择文件,然后点击 Upload 按钮。

Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button.

upload attachment

已上传的文件将显示在 _attachments 字段下。稍后,你可以通过点击该文件来查看该文件。

The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it.