Basic authentication (RFC 2617) is a quick and simple way to authenticate with CouchDB. The main drawback is the need to send user credentials with each request which may be insecure and could hurt operation performance (since CouchDB must compute password hash with every request):
Request:
GET / HTTP/1.1
Accept: application/json
Authorization: Basic cm9vdDpyZWxheA==
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 177
Content-Type: application/json
Date: Mon, 03 Dec 2012 00:44:47 GMT
Server: CouchDB (Erlang/OTP)
{
"couchdb":"Welcome",
"uuid":"0a959b9b8227188afc2ac26ccdf345a6",
"version":"1.3.0",
"vendor": {
"version":"1.3.0",
"name":"The Apache Software Foundation"
}
}
For cookie authentication (RFC 2109) CouchDB generates a token that the client can use for the next few requests to CouchDB. Tokens are valid until a timeout. When CouchDB sees a valid token in a subsequent request, it will authenticate user by this token without requesting the password again. By default, cookies are valid for 10 minutes, but it’s adjustable. Also it’s possible to make cookies persistent
To obtain the first token and thus authenticate a user for the first time, the username and password must be sent to the _session API.
Initiates new session for specified user credentials by providing Cookie value.
| Request Headers: | |
|---|---|
|
|
| Query Parameters: | |
|
|
| Form Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /_session HTTP/1.1
Accept: application/json
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
Host: localhost:5984
name=root&password=relax
It’s also possible to send data as JSON:
POST /_session HTTP/1.1
Accept: application/json
Content-Length: 37
Content-Type: application/json
Host: localhost:5984
{
"name": "root",
"password": "relax"
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 43
Content-Type: application/json
Date: Mon, 03 Dec 2012 01:23:14 GMT
Server: CouchDB (Erlang/OTP)
Set-Cookie: AuthSession=cm9vdDo1MEJCRkYwMjq0LO0ylOIwShrgt8y-UkhI-c6BGw; Version=1; Path=/; HttpOnly
{"ok":true,"name":"root","roles":["_admin"]}
If next query parameter was provided the response will trigger redirection to the specified location in case of successful authentication:
Request:
POST /_session?next=/blog/_design/sofa/_rewrite/recent-posts HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: localhost:5984
name=root&password=relax
Response:
HTTP/1.1 302 Moved Temporarily
Cache-Control: must-revalidate
Content-Length: 43
Content-Type: application/json
Date: Mon, 03 Dec 2012 01:32:46 GMT
Location: http://localhost:5984/blog/_design/sofa/_rewrite/recent-posts
Server: CouchDB (Erlang/OTP)
Set-Cookie: AuthSession=cm9vdDo1MEJDMDEzRTp7Vu5GKCkTxTVxwXbpXsBARQWnhQ; Version=1; Path=/; HttpOnly
{"ok":true,"name":null,"roles":["_admin"]}
Returns complete information about authenticated user. This information contains User Context Object, authentication method and available ones and authentication database.
| Query Parameters: | |
|---|---|
|
|
| Status Codes: |
|
Request:
GET /_session HTTP/1.1
Host: localhost:5984
Accept: application/json
Cookie: AuthSession=cm9vdDo1MEJDMDQxRDpqb-Ta9QfP9hpdPjHLxNTKg_Hf9w
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 175
Content-Type: application/json
Date: Fri, 09 Aug 2013 20:27:45 GMT
Server: CouchDB (Erlang/OTP)
Set-Cookie: AuthSession=cm9vdDo1MjA1NTBDMTqmX2qKt1KDR--GUC80DQ6-Ew_XIw; Version=1; Path=/; HttpOnly
{
"info": {
"authenticated": "cookie",
"authentication_db": "_users",
"authentication_handlers": [
"oauth",
"cookie",
"default"
]
},
"ok": true,
"userCtx": {
"name": "root",
"roles": [
"_admin"
]
}
}
Closes user’s session.
| Status Codes: |
|
|---|
Request:
DELETE /_session HTTP/1.1
Accept: application/json
Cookie: AuthSession=cm9vdDo1MjA1NEVGMDo1QXNQkqC_0Qmgrk8Fw61_AzDeXw
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Fri, 09 Aug 2013 20:30:12 GMT
Server: CouchDB (Erlang/OTP)
Set-Cookie: AuthSession=; Version=1; Path=/; HttpOnly
{
"ok": true
}
Note
To use this authentication method make sure that the {couch_httpd_auth, proxy_authentification_handler} value in added to the list of the active httpd/authentication_handlers:
[httpd]
authentication_handlers = {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, proxy_authentification_handler}, {couch_httpd_auth, default_authentication_handler}
Proxy authentication is very useful in case your application already uses some external authentication service and you don’t want to duplicate users and their roles in CouchDB.
This authentication method allows creation of a User Context Object for remotely authenticated user. By default, the client just need to pass specific headers to CouchDB with related request:
Request:
GET /_session HTTP/1.1
Host: localhost:5984
Accept: application/json
Content-Type: application/json; charset=utf-8
X-Auth-CouchDB-Roles: users,blogger
X-Auth-CouchDB-UserName: foo
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 190
Content-Type: application/json
Date: Fri, 14 Jun 2013 10:16:03 GMT
Server: CouchDB (Erlang/OTP)
{
"info": {
"authenticated": "proxy",
"authentication_db": "_users",
"authentication_handlers": [
"oauth",
"cookie",
"proxy",
"default"
]
},
"ok": true,
"userCtx": {
"name": "foo",
"roles": [
"users",
"blogger"
]
}
}
Note that you don’t need to request session to be authenticated by this method if all required HTTP headers are provided.
CouchDB supports OAuth 1.0 authentication (RFC 5849). OAuth provides a method for clients to access server resources without sharing real credentials (username and password).
First, configure oauth, by setting consumer and token with their secrets and binding token to real CouchDB username.
Probably, it’s not good idea to work with plain curl, let use some scripting language like Python:
#!/usr/bin/env python2
from oauth import oauth # pip install oauth
import httplib
URL = 'http://localhost:5984/_session'
CONSUMER_KEY = 'consumer1'
CONSUMER_SECRET = 'sekr1t'
TOKEN = 'token1'
SECRET = 'tokensekr1t'
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
token = oauth.OAuthToken(TOKEN, SECRET)
req = oauth.OAuthRequest.from_consumer_and_token(
consumer,
token=token,
http_method='GET',
http_url=URL,
parameters={}
)
req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,token)
headers = req.to_header()
headers['Accept'] = 'application/json'
con = httplib.HTTPConnection('localhost', 5984)
con.request('GET', URL, headers=headers)
resp = con.getresponse()
print resp.read()
or Ruby:
#!/usr/bin/env ruby
require 'oauth' # gem install oauth
URL = 'http://localhost:5984'
CONSUMER_KEY = 'consumer1'
CONSUMER_SECRET = 'sekr1t'
TOKEN = 'token1'
SECRET = 'tokensekr1t'
@consumer = OAuth::Consumer.new CONSUMER_KEY,
CONSUMER_SECRET,
{:site => URL}
@access_token = OAuth::AccessToken.new(@consumer, TOKEN, SECRET)
puts @access_token.get('/_session').body
Both snippets produces similar request and response pair:
GET /_session HTTP/1.1
Host: localhost:5984
Accept: application/json
Authorization: OAuth realm="", oauth_nonce="81430018", oauth_timestamp="1374561749", oauth_consumer_key="consumer1", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="token1", oauth_signature="o4FqJ8%2B9IzUpXH%2Bk4rgnv7L6eTY%3D"
HTTP/1.1 200 OK
Cache-Control : must-revalidate
Content-Length : 167
Content-Type : application/json
Date : Tue, 23 Jul 2013 06:51:15 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true,
"info": {
"authenticated": "oauth",
"authentication_db": "_users",
"authentication_handlers": ["oauth", "cookie", "default"]
},
"userCtx": {
"name": "couchdb_username",
"roles": []
}
}
There we request the _session resource to ensure that authentication was successful and the target CouchDB username is correct. Change the target URL to request required resource.
The CouchDB API Server Configuration Methods provide an interface to query and update the various configuration values within a running CouchDB instance.
Returns the entire CouchDB server configuration as a JSON structure. The structure is organized by different configuration sections, with individual values.
| Request Headers: | |
|---|---|
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request
GET /_config HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 4148
Content-Type: application/json
Date: Sat, 10 Aug 2013 12:01:42 GMT
Server: CouchDB (Erlang/OTP)
{
"attachments": {
"compressible_types": "text/*, application/javascript, application/json, application/xml",
"compression_level": "8"
},
"couch_httpd_auth": {
"auth_cache_size": "50",
"authentication_db": "_users",
"authentication_redirect": "/_utils/session.html",
"require_valid_user": "false",
"timeout": "600"
},
"couchdb": {
"database_dir": "/var/lib/couchdb",
"delayed_commits": "true",
"max_attachment_chunk_size": "4294967296",
"max_dbs_open": "100",
"max_document_size": "4294967296",
"os_process_timeout": "5000",
"uri_file": "/var/lib/couchdb/couch.uri",
"util_driver_dir": "/usr/lib64/couchdb/erlang/lib/couch-1.5.0/priv/lib",
"view_index_dir": "/var/lib/couchdb"
},
"daemons": {
"auth_cache": "{couch_auth_cache, start_link, []}",
"db_update_notifier": "{couch_db_update_notifier_sup, start_link, []}",
"external_manager": "{couch_external_manager, start_link, []}",
"httpd": "{couch_httpd, start_link, []}",
"query_servers": "{couch_query_servers, start_link, []}",
"stats_aggregator": "{couch_stats_aggregator, start, []}",
"stats_collector": "{couch_stats_collector, start, []}",
"uuids": "{couch_uuids, start, []}",
"view_manager": "{couch_view, start_link, []}"
},
"httpd": {
"allow_jsonp": "false",
"authentication_handlers": "{couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}",
"bind_address": "<IP_ADDRESS>",
"default_handler": "{couch_httpd_db, handle_request}",
"max_connections": "2048",
"port": "5984",
"secure_rewrites": "true",
"vhost_global_handlers": "_utils, _uuids, _session, _oauth, _users"
},
"httpd_db_handlers": {
"_changes": "{couch_httpd_db, handle_changes_req}",
"_compact": "{couch_httpd_db, handle_compact_req}",
"_design": "{couch_httpd_db, handle_design_req}",
"_temp_view": "{couch_httpd_view, handle_temp_view_req}",
"_view_cleanup": "{couch_httpd_db, handle_view_cleanup_req}"
},
"httpd_design_handlers": {
"_info": "{couch_httpd_db, handle_design_info_req}",
"_list": "{couch_httpd_show, handle_view_list_req}",
"_rewrite": "{couch_httpd_rewrite, handle_rewrite_req}",
"_show": "{couch_httpd_show, handle_doc_show_req}",
"_update": "{couch_httpd_show, handle_doc_update_req}",
"_view": "{couch_httpd_view, handle_view_req}"
},
"httpd_global_handlers": {
"/": "{couch_httpd_misc_handlers, handle_welcome_req, <<\"Welcome\">>}",
"_active_tasks": "{couch_httpd_misc_handlers, handle_task_status_req}",
"_all_dbs": "{couch_httpd_misc_handlers, handle_all_dbs_req}",
"_config": "{couch_httpd_misc_handlers, handle_config_req}",
"_log": "{couch_httpd_misc_handlers, handle_log_req}",
"_oauth": "{couch_httpd_oauth, handle_oauth_req}",
"_replicate": "{couch_httpd_misc_handlers, handle_replicate_req}",
"_restart": "{couch_httpd_misc_handlers, handle_restart_req}",
"_session": "{couch_httpd_auth, handle_session_req}",
"_stats": "{couch_httpd_stats_handlers, handle_stats_req}",
"_utils": "{couch_httpd_misc_handlers, handle_utils_dir_req, \"/usr/share/couchdb/www\"}",
"_uuids": "{couch_httpd_misc_handlers, handle_uuids_req}",
"favicon.ico": "{couch_httpd_misc_handlers, handle_favicon_req, \"/usr/share/couchdb/www\"}"
},
"log": {
"file": "/var/log/couchdb/couch.log",
"include_sasl": "true",
"level": "info"
},
"query_server_config": {
"reduce_limit": "true"
},
"query_servers": {
"javascript": "/usr/bin/couchjs /usr/share/couchdb/server/main.js"
},
"replicator": {
"max_http_pipeline_size": "10",
"max_http_sessions": "10"
},
"stats": {
"rate": "1000",
"samples": "[0, 60, 300, 900]"
},
"uuids": {
"algorithm": "utc_random"
}
}
Gets the configuration structure for a single section.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
GET /_config/httpd HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 444
Content-Type: application/json
Date: Sat, 10 Aug 2013 12:10:40 GMT
Server: CouchDB (Erlang/OTP)
{
"allow_jsonp": "false",
"authentication_handlers": "{couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}",
"bind_address": "<IP_ADDRESS>",
"default_handler": "{couch_httpd_db, handle_request}",
"enable_cors": "false",
"log_max_chunk_size": "1000000",
"port": "5984",
"secure_rewrites": "true",
"vhost_global_handlers": "_utils, _uuids, _session, _oauth, _users"
}
Gets a single configuration value from within a specific configuration section.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
GET /_config/log/level HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 8
Content-Type: application/json
Date: Sat, 10 Aug 2013 12:12:59 GMT
Server: CouchDB (Erlang/OTP)
"debug"
Note
The returned value will be the JSON of the value, which may be a string or numeric value, or an array or object. Some client environments may not parse simple strings or numeric values as valid JSON.
Updates a configuration value. The new value should be supplied in the request body in the corresponding JSON format. If you are setting a string value, you must supply a valid JSON string. In response CouchDB sends old value for target section key.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
PUT /_config/log/level HTTP/1.1
Accept: application/json
Content-Length: 7
Content-Type: application/json
Host: localhost:5984
"info"
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 8
Content-Type: application/json
Date: Sat, 10 Aug 2013 12:12:59 GMT
Server: CouchDB (Erlang/OTP)
"debug"
Deletes a configuration value. The returned JSON will be the value of the configuration parameter before it was deleted.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
DELETE /_config/log/level HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 7
Content-Type: application/json
Date: Sat, 10 Aug 2013 12:29:03 GMT
Server: CouchDB (Erlang/OTP)
"info"
The Database methods provide an interface to an entire database withing CouchDB. These are database, rather than document, level requests.
For all the database methods, the database name within the URL path should be the database name that you wish to perform the operation on. For example, to obtain the meta information for the database recipes, you would use the HTTP request:
GET /recipes
For clarity, the form below is used in the URL paths:
GET /db
Where db is the name of any database.
Returns the HTTP Headers containing a minimal amount of information about the specified database. Since the response body is empty this method is a lightweight way to check if the database exists already or not.
| Parameters: |
|
|---|---|
| Status Codes: |
|
Request:
HEAD /test HTTP/1.1
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Mon, 12 Aug 2013 01:27:41 GMT
Server: CouchDB (Erlang/OTP)
Gets information about the specified database.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /receipts HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 258
Content-Type: application/json
Date: Mon, 12 Aug 2013 01:38:57 GMT
Server: CouchDB (Erlang/OTP)
{
"committed_update_seq": 292786,
"compact_running": false,
"data_size": 65031503,
"db_name": "receipts",
"disk_format_version": 6,
"disk_size": 137433211,
"doc_count": 6146,
"doc_del_count": 64637,
"instance_start_time": "1376269325408900",
"purge_seq": 0,
"update_seq": 292786
}
Creates a new database. The database name {db} must be composed by following next rules:
If you’re familiar with Regular Expressions, the rules above could be written as ^[a-z][a-z0-9_$()+/-]*$.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
PUT /db HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 08:01:45 GMT
Location: http://localhost:5984/db
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
If we repeat the same request to CouchDB, it will response with 412 since the database already exists:
Request:
PUT /db HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 412 Precondition Failed
Cache-Control: must-revalidate
Content-Length: 95
Content-Type: application/json
Date: Mon, 12 Aug 2013 08:01:16 GMT
Server: CouchDB (Erlang/OTP)
{
"error": "file_exists",
"reason": "The database could not be created, the file already exists."
}
If an invalid database name is supplied, CouchDB returns response with 400:
Request:
PUT /_db HTTP/1.1
Accept: application/json
Host: localhost:5984
Request:
HTTP/1.1 400 Bad Request
Cache-Control: must-revalidate
Content-Length: 194
Content-Type: application/json
Date: Mon, 12 Aug 2013 08:02:10 GMT
Server: CouchDB (Erlang/OTP)
{
"error": "illegal_database_name",
"reason": "Name: '_db'. Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
}
Deletes the specified database, and all the documents and attachments contained within it.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
DELETE /db HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 08:54:00 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
Creates a new document in the specified database, using the supplied JSON document structure.
If the JSON structure includes the _id field, then the document will be created with the specified document ID.
If the _id field is not specified, a new unique ID will be generated, following whatever UUID algorithm is configured for that server.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db HTTP/1.1
Accept: application/json
Content-Length: 81
Content-Type: application/json
{
"servings": 4,
"subtitle": "Delicious with fresh bread",
"title": "Fish Stew"
}
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 95
Content-Type: application/json
Date: Tue, 13 Aug 2013 15:19:25 GMT
ETag: "1-9c65296036141e575d32ba9c034dd3ee"
Location: http://localhost:5984/db/ab39fe0993049b84cfa81acd6ebad09d
Server: CouchDB (Erlang/OTP)
{
"id": "ab39fe0993049b84cfa81acd6ebad09d",
"ok": true,
"rev": "1-9c65296036141e575d32ba9c034dd3ee"
}
The document ID can be specified by including the _id field in the JSON of the submitted record. The following request will create the same document with the ID FishStew.
Request:
POST /db HTTP/1.1 Accept: application/json Content-Length: 98 Content-Type: application/json { "_id": "FishStew", "servings": 4, "subtitle": "Delicious with fresh bread", "title": "Fish Stew" }Response:
HTTP/1.1 201 Created Cache-Control: must-revalidate Content-Length: 71 Content-Type: application/json Date: Tue, 13 Aug 2013 15:19:25 GMT ETag: "1-9c65296036141e575d32ba9c034dd3ee" Location: http://localhost:5984/db/FishStew Server: CouchDB (Erlang/OTP) { "id": "FishStew", "ok": true, "rev": "1-9c65296036141e575d32ba9c034dd3ee" }
You can write documents to the database at a higher rate by using the batch option. This collects document writes together in memory (on a user-by-user basis) before they are committed to disk. This increases the risk of the documents not being stored in the event of a failure, since the documents are not written to disk immediately.
To use the batched mode, append the batch=ok query argument to the URL of the PUT or POST /{db} request. The CouchDB server will respond with a HTTP 202 Accepted response code immediately.
Note
Creating or updating documents with batch mode doesn’t guarantee that all documents will be successfully stored on disk. For example, individual documents may not be saved due to conflicts, rejection by validation function or by other reasons, even if overall the batch was sucessfully submitted.
Request:
POST /db?batch=ok HTTP/1.1
Accept: application/json
Content-Length: 98
Content-Type: application/json
{
"_id": "FishStew",
"servings": 4,
"subtitle": "Delicious with fresh bread",
"title": "Fish Stew"
}
Response:
HTTP/1.1 202 Accepted
Cache-Control: must-revalidate
Content-Length: 28
Content-Type: application/json
Date: Tue, 13 Aug 2013 15:19:25 GMT
Location: http://localhost:5984/db/FishStew
Server: CouchDB (Erlang/OTP)
{
"id": "FishStew",
"ok": true
}
Returns a JSON structure of all of the documents in a given database. The information is returned as a JSON structure containing meta information about the return structure, including a list of all documents and basic contents, consisting the ID, revision and key. The key is the from the document’s _id.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /db/_all_docs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Sat, 10 Aug 2013 16:22:56 GMT
ETag: "1W2DJUZFZSZD9K78UFA3GZWB4"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset": 0,
"rows": [
{
"id": "16e458537602f5ef2a710089dffd9453",
"key": "16e458537602f5ef2a710089dffd9453",
"value": {
"rev": "1-967a00dff5e02add41819138abb3284d"
}
},
{
"id": "a4c51cdfa2069f3e905c431114001aff",
"key": "a4c51cdfa2069f3e905c431114001aff",
"value": {
"rev": "1-967a00dff5e02add41819138abb3284d"
}
},
{
"id": "a4c51cdfa2069f3e905c4311140034aa",
"key": "a4c51cdfa2069f3e905c4311140034aa",
"value": {
"rev": "5-6182c9c954200ab5e3c6bd5e76a1549f"
}
},
{
"id": "a4c51cdfa2069f3e905c431114003597",
"key": "a4c51cdfa2069f3e905c431114003597",
"value": {
"rev": "2-7051cbe5c8faecd085a3fa619e6e6337"
}
},
{
"id": "f4ca7773ddea715afebc4b4b15d4f0b3",
"key": "f4ca7773ddea715afebc4b4b15d4f0b3",
"value": {
"rev": "2-7051cbe5c8faecd085a3fa619e6e6337"
}
}
],
"total_rows": 5
}
The POST to _all_docs allows to specify multiple keys to be selected from the database. This enables you to request multiple documents in a single request, in place of multiple GET /{db}/{docid} requests.
The request body should contain a list of the keys to be returned as an array to a keys object. For example:
POST /db/_all_docs HTTP/1.1
Accept: application/json
Content-Length: 70
Content-Type: application/json
Host: localhost:5984
{
"keys" : [
"Zingylemontart",
"Yogurtraita"
]
}
The returned JSON is the all documents structure, but with only the selected keys in the output:
{
"total_rows" : 2666,
"rows" : [
{
"value" : {
"rev" : "1-a3544d296de19e6f5b932ea77d886942"
},
"id" : "Zingylemontart",
"key" : "Zingylemontart"
},
{
"value" : {
"rev" : "1-91635098bfe7d40197a1b98d7ee085fc"
},
"id" : "Yogurtraita",
"key" : "Yogurtraita"
}
],
"offset" : 0
}
The bulk document API allows you to create and update multiple documents at the same time within a single request. The basic operation is similar to creating or updating a single document, except that you batch the document structure and information.
When creating new documents the document ID (_id) is optional.
For updating existing documents, you must provide the document ID, revision information (_rev), and new document values.
In case of batch deleting documents all fields as document ID, revision information and deletion status (_deleted) are required.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Request JSON Object: | |
|
|
| Response Headers: | |
|
|
| Response JSON Array of Objects: | |
|
|
| Status Codes: |
|
Request:
POST /db/_bulk_docs HTTP/1.1
Accept: application/json
Content-Length: 109
Content-Type:application/json
Host: localhost:5984
{
"docs": [
{
"_id": "FishStew"
},
{
"_id": "LambStew",
"_rev": "2-0786321986194c92dd3b57dfbfc741ce",
"_deleted": true
}
]
}
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 144
Content-Type: application/json
Date: Mon, 12 Aug 2013 00:15:05 GMT
Server: CouchDB (Erlang/OTP)
[
{
"ok": true,
"id": "FishStew",
"rev":" 1-967a00dff5e02add41819138abb3284d"
},
{
"ok": true,
"id": "LambStew",
"rev": "3-f9c62b2169d0999103e9f41949090807"
}
]
Each time a document is stored or updated in CouchDB, the internal B-tree is updated. Bulk insertion provides efficiency gains in both storage space, and time, by consolidating many of the updates to intermediate B-tree nodes.
It is not intended as a way to perform ACID-like transactions in CouchDB, the only transaction boundary within CouchDB is a single update to a single database. The constraints are detailed in Bulk Documents Transaction Semantics.
To insert documents in bulk into a database you need to supply a JSON structure with the array of documents that you want to add to the database. Using this method you can either include a document ID, or allow the document ID to be automatically generated.
For example, the following update inserts three new documents, two with the supplied document IDs, and one which will have a document ID generated:
{
"docs" : [
{
"_id" : "FishStew",
"servings" : 4,
"subtitle" : "Delicious with fresh bread",
"title" : "Fish Stew"
},
{
"_id" : "LambStew",
"servings" : 6,
"subtitle" : "Delicious with scone topping",
"title" : "Lamb Stew"
},
{
"servings" : 8,
"subtitle" : "Delicious with suet dumplings",
"title" : "Beef Stew"
},
]
}
The return type from a bulk insertion will be 201, with the content of the returned structure indicating specific success or otherwise messages on a per-document basis.
The return structure from the example above contains a list of the documents created, here with the combination and their revision IDs:
POST http://couchdb:5984/recipes/_bulk_docs
Content-Type: application/json
[
{
"id" : "FishStew",
"rev" : "1-9c65296036141e575d32ba9c034dd3ee",
},
{
"id" : "LambStew",
"rev" : "1-34c318924a8f327223eed702ddfdc66d",
},
{
"id" : "7f7638c86173eb440b8890839ff35433",
"rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
}
]
The content and structure of the returned JSON will depend on the transaction semantics being used for the bulk update; see Bulk Documents Transaction Semantics for more information. Conflicts and validation errors when updating documents in bulk must be handled separately; see Bulk Document Validation and Conflict Errors.
The bulk document update procedure is similar to the insertion procedure, except that you must specify the document ID and current revision for every document in the bulk update JSON string.
For example, you could send the following request:
POST http://couchdb:5984/recipes/_bulk_docs
Content-Type: application/json
{
"docs" : [
{
"_id" : "FishStew",
"_rev" : "1-9c65296036141e575d32ba9c034dd3ee",
"servings" : 4,
"subtitle" : "Delicious with freshly baked bread",
"title" : "Fish Stew"
},
{
"_id" : "LambStew",
"_rev" : "1-34c318924a8f327223eed702ddfdc66d",
"servings" : 6,
"subtitle" : "Serve with a wholemeal scone topping",
"title" : "Lamb Stew"
},
{
"_id" : "7f7638c86173eb440b8890839ff35433"
"_rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
"servings" : 8,
"subtitle" : "Hand-made dumplings make a great accompaniment",
"title" : "Beef Stew"
}
]
}
The return structure is the JSON of the updated documents, with the new revision and ID information:
[
{
"id" : "FishStew",
"rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
},
{
"id" : "LambStew",
"rev" : "2-0786321986194c92dd3b57dfbfc741ce"
},
{
"id" : "7f7638c86173eb440b8890839ff35433",
"rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
}
]
You can optionally delete documents during a bulk update by adding the _deleted field with a value of true to each document ID/revision combination within the submitted JSON structure.
The return type from a bulk insertion will be 201, with the content of the returned structure indicating specific success or otherwise messages on a per-document basis.
The content and structure of the returned JSON will depend on the transaction semantics being used for the bulk update; see Bulk Documents Transaction Semantics for more information. Conflicts and validation errors when updating documents in bulk must be handled separately; see Bulk Document Validation and Conflict Errors.
CouchDB supports two different modes for updating (or inserting) documents using the bulk documentation system. Each mode affects both the state of the documents in the event of system failure, and the level of conflict checking performed on each document. The two modes are:
non-atomic
The default mode is non-atomic, that is, CouchDB will only guarantee that some of the documents will be saved when you send the request. The response will contain the list of documents successfully inserted or updated during the process. In the event of a crash, some of the documents may have been successfully saved, and some will have been lost.
In this mode, the response structure will indicate whether the document was updated by supplying the new _rev parameter indicating a new document revision was created. If the update failed, then you will get an error of type conflict. For example:
[
{
"id" : "FishStew",
"error" : "conflict",
"reason" : "Document update conflict."
},
{
"id" : "LambStew",
"error" : "conflict",
"reason" : "Document update conflict."
},
{
"id" : "7f7638c86173eb440b8890839ff35433",
"error" : "conflict",
"reason" : "Document update conflict."
}
]
In this case no new revision has been created and you will need to submit the document update, with the correct revision tag, to update the document.
all-or-nothing
In all-or-nothing mode, either all documents are written to the database, or no documents are written to the database, in the event of a system failure during commit.
In addition, the per-document conflict checking is not performed. Instead a new revision of the document is created, even if the new revision is in conflict with the current revision in the database. The returned structure contains the list of documents with new revisions:
[
{
"id" : "FishStew",
"rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
},
{
"id" : "LambStew",
"rev" : "2-0786321986194c92dd3b57dfbfc741ce"
},
{
"id" : "7f7638c86173eb440b8890839ff35433",
"rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
}
]
When updating documents using this mode the revision of a document included in views will be arbitrary. You can check the conflict status for a document by using the conflicts=true query argument when accessing the view. Conflicts should be handled individually to ensure the consistency of your database.
To use this mode, you must include the all_or_nothing field (set to true) within the main body of the JSON of the request.
The effects of different database operations on the different modes are summarized below:
Replication of documents is independent of the type of insert or update. The documents and revisions created during a bulk insert or update are replicated in the same way as any other document. This can mean that if you make use of the all-or-nothing mode the exact list of documents, revisions (and their conflict state) may or may not be replicated to other databases correctly.
The JSON returned by the _bulk_docs operation consists of an array of JSON structures, one for each document in the original submission. The returned JSON structure should be examined to ensure that all of the documents submitted in the original request were successfully added to the database.
When a document (or document revision) is not correctly committed to the database because of an error, you should check the error field to determine error type and course of action. Errors will be one of the following type:
conflict
The document as submitted is in conflict. If you used the default bulk transaction mode then the new revision will not have been created and you will need to re-submit the document to the database. If you used all-or-nothing mode then you will need to manually resolve the conflicted revisions of the document.
Conflict resolution of documents added using the bulk docs interface is identical to the resolution procedures used when resolving conflict errors during replication.
forbidden
Entries with this error type indicate that the validation routine applied to the document during submission has returned an error.
For example, if your validation routine includes the following:
throw({forbidden: 'invalid recipe ingredient'});
The error returned will be:
{
"id" : "7f7638c86173eb440b8890839ff35433",
"error" : "forbidden",
"reason" : "invalid recipe ingredient"
}
Returns a sorted list of changes made to documents in the database, in time order of application, can be obtained from the database’s _changes resource. Only the most recent change for a given document is guaranteed to be provided, for example if a document has had fields added, and then deleted, an API client checking for changes will not necessarily receive the intermediate state of added documents.
This can be used to listen for update and modifications to the database for post processing or synchronization, and for practical purposes, a continuously connected _changes feed is a reasonable approach for generating a real-time log for most applications.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
The result field of database changes
| JSON Object: |
|
|---|
Request:
GET /db/_changes?style=all_docs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Mon, 12 Aug 2013 00:54:58 GMT
ETag: "6ASLEKEMSRABT0O5XY9UPO9Z"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"last_seq": 11,
"results": [
{
"changes": [
{
"rev": "2-7051cbe5c8faecd085a3fa619e6e6337"
}
],
"id": "6478c2ae800dfc387396d14e1fc39626",
"seq": 6
},
{
"changes": [
{
"rev": "3-7379b9e515b161226c6559d90c4dc49f"
}
],
"deleted": true,
"id": "5bbc9ca465f1b0fcd62362168a7c8831",
"seq": 9
},
{
"changes": [
{
"rev": "6-460637e73a6288cb24d532bf91f32969"
},
{
"rev": "5-eeaa298781f60b7bcae0c91bdedd1b87"
}
],
"id": "729eb57437745e506b333068fff665ae",
"seq": 11
}
]
}
Changed in version 0.11.0: added include_docs parameter
Changed in version 1.2.0: added view parameter and special value _view for filter one
Changed in version 1.3.0: since parameter could take now value to start listen changes since current seq number.
Changed in version 1.3.0: eventsource feed type added.
Changed in version 1.4.0: Support Last-Event-ID header.
Requests the database changes feed in the same way as GET /{db}/_changes does, but this method is widely used with ?filter=_doc_ids query parameter and allows to pass larger list of document IDs to filter.
Request:
POST /recipes/_changes?filter=_doc_ids HTTP/1.1
Accept: application/json
Content-Length: 40
Content-Type: application/json
Host: localhost:5984
{
"doc_ids": [
"SpaghettiWithMeatballs"
]
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Sat, 28 Sep 2013 07:23:09 GMT
ETag: "ARIHFWL3I7PIS0SPVTFU6TLR2"
Server: CouchDB (Erlang OTP)
Transfer-Encoding: chunked
{
"last_seq": 38,
"results": [
{
"changes": [
{
"rev": "13-bcb9d6388b60fd1e960d9ec4e8e3f29e"
}
],
"id": "SpaghettiWithMeatballs",
"seq": 38
}
]
}
By default all changes are immediately returned within the JSON body:
GET /somedatabase/_changes HTTP/1.1
{"results":[
{"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]},
{"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]},
{"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
],
"last_seq":5}
results is the list of changes in sequential order. New and changed documents only differ in the value of the rev; deleted documents include the "deleted": true attribute. (In the style=all_docs mode, deleted applies only to the current/winning revision. The other revisions listed might be deleted even if there is no deleted property; you have to GET them individually to make sure.)
last_seq is the sequence number of the last update returned. (Currently it will always be the same as the seq of the last item in results.)
Sending a since param in the query string skips all changes up to and including the given sequence number:
GET /somedatabase/_changes?since=3 HTTP/1.1
The return structure for normal and longpoll modes is a JSON array of changes objects, and the last update sequence number.
In the return format for continuous mode, the server sends a CRLF (carriage-return, linefeed) delimited line for each change. Each line contains the JSON object described above.
You can also request the full contents of each document change (instead of just the change notification) by using the include_docs parameter.
{
"last_seq": 5
"results": [
{
"changes": [
{
"rev": "2-eec205a9d413992850a6e32678485900"
}
],
"deleted": true,
"id": "deleted",
"seq": 5,
}
]
}
The longpoll feed, probably most applicable for a browser, is a more efficient form of polling that waits for a change to occur before the response is sent. longpoll avoids the need to frequently poll CouchDB to discover nothing has changed!
The request to the server will remain open until a change is made on the database and is subsequently transferred, and then the connection will close. This is low load for both server and client.
The response is basically the same JSON as is sent for the normal feed.
Because the wait for a change can be significant you can set a timeout before the connection is automatically closed (the timeout argument). You can also set a heartbeat interval (using the heartbeat query argument), which sends a newline to keep the connection active.
Continually polling the CouchDB server is not ideal - setting up new HTTP connections just to tell the client that nothing happened puts unnecessary strain on CouchDB.
A continuous feed stays open and connected to the database until explicitly closed and changes are sent to the client as they happen, i.e. in near real-time.
As with the longpoll feed type you can set both the timeout and heartbeat intervals to ensure that the connection is kept open for new changes and updates.
The continuous feed’s response is a little different than the other feed types to simplify the job of the client - each line of the response is either empty or a JSON object representing a single change, as found in the normal feed’s results.
GET /somedatabase/_changes?feed=continuous HTTP/1.1
{"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]}
{"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]}
{"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
... tum tee tum ...
{"seq":6,"id":"updated","changes":[{"rev":"3-825cb35de44c433bfb2df415563a19de"}]}
Obviously, ... tum tee tum ... does not appear in the actual response, but represents a long pause before the change with seq 6 occurred.
The eventsource feed provides push notifications that can be consumed in the form of DOM events in the browser. Refer to the W3C eventsource specification for further details. CouchDB also honours the Last-Event-ID parameter.
GET /somedatabase/_changes?feed=eventsource HTTP/1.1
// define the event handling function
if (window.EventSource) {
var source = new EventSource("/somedatabase/_changes?feed=eventsource");
source.onerror = function(e) {
alert('EventSource failed.');
};
var results = [];
var sourceListener = function(e) {
var data = JSON.parse(e.data);
results.push(data);
};
// start listening for events
source.addEventListener('message', sourceListener, false);
// stop listening for events
source.removeEventListener('message', sourceListener, false);
}
Note
EventSource connections are subject to cross-origin resource sharing restrictions. You might need to configure CORS support to get the EventSource to work in your application.
You can filter the contents of the changes feed in a number of ways. The most basic way is to specify one or more document IDs to the query. This causes the returned structure value to only contain changes for the specified IDs. Note that the value of this query argument should be a JSON formatted array.
You can also filter the _changes feed by defining a filter function within a design document. The specification for the filter is the same as for replication filters. You specify the name of the filter function to the filter parameter, specifying the design document name and filter name. For example:
GET /db/_changes?filter=design_doc/filtername
Additionally, there are couple of builtin filters are available and described below.
This filter accepts only changes for documents which ID in specified in doc_ids query parameter or payload’s object array. See POST /{db}/_changes for an example.
The _design filter accepts only changes for any design document within the requested database.
Request:
GET /recipes/_changes?filter=_design HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Sat, 28 Sep 2013 07:28:28 GMT
ETag: "ARIHFWL3I7PIS0SPVTFU6TLR2"
Server: CouchDB (Erlang OTP)
Transfer-Encoding: chunked
{
"last_seq": 38,
"results": [
{
"changes": [
{
"rev": "10-304cae84fd862832ea9814f02920d4b2"
}
],
"id": "_design/ingredients",
"seq": 29
},
{
"changes": [
{
"rev": "123-6f7c1b7c97a9e4f0d22bdf130e8fd817"
}
],
"deleted": true,
"id": "_design/cookbook",
"seq": 35
},
{
"changes": [
{
"rev": "6-5b8a52c22580e922e792047cff3618f3"
}
],
"deleted": true,
"id": "_design/meta",
"seq": 36
}
]
}
New in version 1.2.
The special filter _view allows to use existed map function as the filter. If the map function emits anything for the processed document he counts as accepted and the changes event emits to the feed. For most use-practice cases filter functions are very similar to map ones, so this feature helps to reduce amount of duplicated code.
Warning
While map functions doesn’t process the design documents, using _view filter forces them to do this. You need to be sure, that they are ready to handle documents with alien structure without panic crush.
Note
Using _view filter doesn’t queries the view index files, so you cannot use common view query parameters to additionally filter the changes feed by index key. Also, CouchDB doesn’t returns the result instantly as he does for views - it really uses the specified map function as filter.
Moreover, you cannot make such filters dynamic e.g. process the request query parameters or handle the User Context Object - the map function is only operates with the document.
Request:
GET /recipes/_changes?filter=_view&view=ingredients/by_recipe HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Sat, 28 Sep 2013 07:36:40 GMT
ETag: "ARIHFWL3I7PIS0SPVTFU6TLR2"
Server: CouchDB (Erlang OTP)
Transfer-Encoding: chunked
{
"last_seq": 38,
"results": [
{
"changes": [
{
"rev": "13-bcb9d6388b60fd1e960d9ec4e8e3f29e"
}
],
"id": "SpaghettiWithMeatballs",
"seq": 38
}
]
}
Request compaction of the specified database. Compaction compresses the disk database file by performing the following operations:
Compaction can only be requested on an individual database; you cannot compact all the databases for a CouchDB instance. The compaction process runs as a background process.
You can determine if the compaction process is operating on a database by obtaining the database meta information, the compact_running value of the returned database structure will be set to true. See GET /{db}.
You can also obtain a list of running processes to determine whether compaction is currently running. See /_active_tasks.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_compact HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: localhost:5984
Response:
HTTP/1.1 202 Accepted
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 09:27:43 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
Compacts the view indexes associated with the specified design document. If may be that compacting a large view can return more storage than compacting the atual db. Thus, you can use this in place of the full database compaction if you know a specific set of view indexes have been affected by a recent database change.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_compact/posts HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: localhost:5984
Response:
HTTP/1.1 202 Accepted
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 09:36:44 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
.. note::
View indexes are stored in a separate ``.couch`` file based on
a hash of the design document's relevant functions, in a sub directory
of where the main ``.couch`` database files are located.
Commits any recent changes to the specified database to disk. You should call this if you want to ensure that recent changes have been flushed. This function is likely not required, assuming you have the recommended configuration setting of delayed_commits=false, which requires CouchDB to ensure changes are written to disk before a 200 or similar result is returned.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_ensure_full_commit HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: localhost:5984
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 53
Content-Type: application/json
Date: Mon, 12 Aug 2013 10:22:19 GMT
Server: CouchDB (Erlang/OTP)
{
"instance_start_time": "1376269047459338",
"ok": true
}
Removes view index files that are no longer required by CouchDB as a result of changed views within design documents. As the view filename is based on a hash of the view functions, over time old views will remain, consuming storage. This call cleans up the cached view output on disk for a given view.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_view_cleanup HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: localhost:5984
Response:
HTTP/1.1 202 Accepted
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 09:27:43 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
Returns the current security object from the specified database.
The security object consists of two compulsory elements, admins and members, which are used to specify the list of users and/or roles that have admin and members rights to the database respectively:
Both members and admins objects are contains two array-typed fields:
Any other additional fields in the security object are optional. The entire security object is made available to validation and other internal functions so that the database can control and limit functionality.
If both the names and roles fields of either the admins or members properties are empty arrays, it means the database has no admins or members.
Having no admins, only server admins (with the reserved _admin role) are able to update design document and make other admin level changes.
Having no members, any user can write regular documents (any non-design document) and read documents from the database.
If there are any member names or roles defined for a database, then only authenticated users having a matching name or role are allowed to read documents from the database (or do a GET /{db} call).
Note
If the security object for a database has never been set, then the value returned will be empty.
Also note, that security objects are not regular versioned documents (that is, they are not under MVCC rules). This is a design choice to speedup authorization checks (avoids traversing a database`s documents B-Tree).
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /db/_security HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 109
Content-Type: application/json
Date: Mon, 12 Aug 2013 19:05:29 GMT
Server: CouchDB (Erlang/OTP)
{
"admins": {
"names": [
"superuser"
],
"roles": [
"admins"
]
},
"members": {
"names": [
"user1",
"user2"
],
"roles": [
"developers"
]
}
}
Sets the security object for the given database.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Request JSON Object: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
PUT /db/_security HTTP/1.1
Accept: application/json
Content-Length: 121
Content-Type: application/json
Host: localhost:5984
{
"admins": {
"names": [
"superuser"
],
"roles": [
"admins"
]
},
"members": {
"names": [
"user1",
"user2"
],
"roles": [
"developers"
]
}
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Tue, 13 Aug 2013 11:26:28 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
Creates (and executes) a temporary view based on the view function supplied in the JSON request.
The arguments also available to standard view requests also apply to temporary views, but the execution of the view may take some time as it relies on being executed at the time of the request. This means that for every temporary view you create, the entire database will be read one doc at a time and passed through the view function.
This should not be used on production CouchDB instances, and is purely a convenience function for quick development testing. You should use a defined view if you want to achieve the best performance.
See /db/_design/design-doc/_view/view-name for more info.
Request:
POST /db/_temp_view?group=true HTTP/1.1
Accept: application/json
Content-Length: 92
Content-Type: application/json
Host: localhost:5984
{
"map": "function(doc) { if (doc.value) { emit(doc.value, null); } }",
"reduce": "_count"
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Tue, 13 Aug 2013 12:28:12 GMT
ETag: "AU33B3N7S9K4SAZSFA048HVB4"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"rows": [
{
"key": -10,
"value": 1
},
{
"key": 10,
"value": 2
},
{
"key": 15,
"value": 1
}
]
}
A database purge permanently removes the references to deleted documents from the database. Normal deletion of a document within CouchDB does not remove the document from the database, instead, the document is marked as _deleted=true (and a new revision is created). This is to ensure that deleted documents can be replicated to other databases as having been deleted. This also means that you can check the status of a document and identify that the document has been deleted by its absence.
Warning
Purging a document from a database should only be done as a last resort when sensitive information has been introduced inadvertently into a database. In clustered or replicated environments it is very difficult to guarantee that a particular purged document has been removed from all replicas. Do not rely on this API as a way of doing secure deletion.
The purge operation removes the references to the deleted documents from the database. The purging of old documents is not replicated to other databases. If you are replicating between databases and have deleted a large number of documents you should run purge on each database.
Note
Purging documents does not remove the space used by them on disk. To reclaim disk space, you should run a database compact (see /db/_compact), and compact views (see /db/_compact/design-doc).
The format of the request must include the document ID and one or more revisions that must be purged.
The response will contain the purge sequence number, and a list of the document IDs and revisions successfully purged.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Request JSON Object: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_purge HTTP/1.1
Accept: application/json
Content-Length: 76
Content-Type: application/json
Host: localhost:5984
{
"c6114c65e295552ab1019e2b046b10e": [
"3-b06fcd1c1c9e0ec7c480ee8aa467bf3b",
"3-0e871ef78849b0c206091f1a7af6ec41"
]
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 103
Content-Type: application/json
Date: Mon, 12 Aug 2013 10:53:24 GMT
Server: CouchDB (Erlang/OTP)
{
"purge_seq":3,
"purged":{
"c6114c65e295552ab1019e2b046b10e": [
"3-b06fcd1c1c9e0ec7c480ee8aa467bf3b"
]
}
}
The number of purges on a database is tracked using a purge sequence. This is used by the view indexer to optimize the updating of views that contain the purged documents.
When the indexer identifies that the purge sequence on a database has changed, it compares the purge sequence of the database with that stored in the view index. If the difference between the stored sequence and database is sequence is only 1, then the indexer uses a cached list of the most recently purged documents, and then removes these documents from the index individually. This prevents completely rebuilding the index from scratch.
If the difference between the stored sequence number and current database sequence is greater than 1, then the view index is entirely rebuilt. This is an expensive operation as every document in the database must be examined.
With given a list of document revisions, returns the document revisions that do not exist in the database.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Request JSON Object: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_missing_revs HTTP/1.1
Accept: application/json
Content-Length: 76
Content-Type: application/json
Host: localhost:5984
{
"c6114c65e295552ab1019e2b046b10e": [
"3-b06fcd1c1c9e0ec7c480ee8aa467bf3b",
"3-0e871ef78849b0c206091f1a7af6ec41"
]
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 64
Content-Type: application/json
Date: Mon, 12 Aug 2013 10:53:24 GMT
Server: CouchDB (Erlang/OTP)
{
"missed_revs":{
"c6114c65e295552ab1019e2b046b10e": [
"3-b06fcd1c1c9e0ec7c480ee8aa467bf3b"
]
}
}
Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database.
Its primary use is by the replicator, as an important optimization: after receiving a set of new revision IDs from the source database, the replicator sends this set to the destination database’s _revs_diff to find out which of them already exist there. It can then avoid fetching and sending already-known document bodies.
Both the request and response bodies are JSON objects whose keys are document IDs; but the values are structured differently:
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Request JSON Object: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
POST /db/_revs_diff HTTP/1.1
Accept: application/json
Content-Length: 113
Content-Type: application/json
Host: localhost:5984
{
"190f721ca3411be7aa9477db5f948bbb": [
"3-bb72a7682290f94a985f7afac8b27137",
"4-10265e5a26d807a3cfa459cf1a82ef2e"
]
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 88
Content-Type: application/json
Date: Mon, 12 Aug 2013 16:56:02 GMT
Server: CouchDB (Erlang/OTP)
{
"190f721ca3411be7aa9477db5f948bbb": {
"missing": [
"3-bb72a7682290f94a985f7afac8b27137"
]
}
}
Gets the current revs_limit (revision limit) setting.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
GET /db/_revs_limit HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 5
Content-Type: application/json
Date: Mon, 12 Aug 2013 17:27:30 GMT
Server: CouchDB (Erlang/OTP)
1000
Sets the maximum number of document revisions that will be tracked by CouchDB, even after compaction has occurred. You can set the revision limit on a database with a scalar integer of the limit that you want to set as the request body.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
PUT /db/_revs_limit HTTP/1.1
Accept: application/json
Content-Length: 5
Content-Type: application/json
Host: localhost:5984
1000
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 12
Content-Type: application/json
Date: Mon, 12 Aug 2013 17:47:52 GMT
Server: CouchDB (Erlang/OTP)
{
"ok": true
}
The CouchDB API Server Document methods detail how to create, read, update and delete documents within a database.
Returns the HTTP Headers containing a minimal amount of information about the specified document. The method supports the same query arguments as the GET /{db}/{docid} method, but only the header information (including document size, and the revision as an ETag), is returned.
The ETag header shows the current revision for the requested document, and the Content-Length specifies the length of the data, if the document were requested in full.
Adding any of the query arguments (see GET /{db}/{docid}), then the resulting HTTP Headers will correspond to what would be returned.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
GET /db/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 660
Content-Type: application/json
Date: Tue, 13 Aug 2013 21:35:37 GMT
ETag: "12-151bb8678d45aaa949ec3698ef1c7e78"
Server: CouchDB (Erlang/OTP)
Returns document by the specified docid from the specified db. Unless you request a specific revision, the latest revision of the document will always be returned.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 660
Content-Type: application/json
Date: Tue, 13 Aug 2013 21:35:37 GMT
ETag: "1-917fa2381192822767f010b95b45325b"
Server: CouchDB (Erlang/OTP)
{
"_id": "SpaghettiWithMeatballs",
"_rev": "1-917fa2381192822767f010b95b45325b",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
The PUT method creates a new named document, or creates a new revision of the existing document. Unlike the POST /{db} method, you must specify the document ID in the request URL.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
PUT /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Content-Length: 196
Content-Type: application/json
Host: localhost:5984
{
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 85
Content-Type: application/json
Date: Wed, 14 Aug 2013 20:31:39 GMT
ETag: "1-917fa2381192822767f010b95b45325b"
Location: http://localhost:5984/recipes/SpaghettiWithMeatballs
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs",
"ok": true,
"rev": "1-917fa2381192822767f010b95b45325b"
}
Deletes the specified document from the database. You must supply the current (latest) revision, either by using the rev parameter to specify the revision.
Note
Note that deletion of a record increments the revision number. The use of a revision for deletion of the record allows replication of the database to correctly track the deletion in synchronized copies.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
DELETE /recipes/FishStew?rev=1-9c65296036141e575d32ba9c034dd3ee HTTP/1.1
Accept: application/json
Host: localhost:5984
Alternatively, instead of rev query parameter you may use If-Match header:
DELETE /recipes/FishStew HTTP/1.1
Accept: application/json
If-Match: 1-9c65296036141e575d32ba9c034dd3ee
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 71
Content-Type: application/json
Date: Wed, 14 Aug 2013 12:23:13 GMT
ETag: "2-056f5f44046ecafc08a2bc2b9c229e20"
Server: CouchDB (Erlang/OTP)
{
"id": "FishStew",
"ok": true,
"rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
}
The COPY (which is non-standard HTTP) copies an existing document to a new or existing document.
The source document is specified on the request line, with the Destination header of the request specifying the target document.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
COPY /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Destination: SpaghettiWithMeatballs_Italian
Host: localhost:5984
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 93
Content-Type: application/json
Date: Wed, 14 Aug 2013 14:21:00 GMT
ETag: "1-e86fdf912560c2321a5fcefc6264e6d9"
Location: http://localhost:5984/recipes/SpaghettiWithMeatballs_Italian
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs_Italian",
"ok": true,
"rev": "1-e86fdf912560c2321a5fcefc6264e6d9"
}
If the document includes attachments, then the returned structure will contain a summary of the attachments associated with the document, but not the attachment data itself.
The JSON for the returned document will include the _attachments field, with one or more attachment definitions.
The _attachments object keys are attachments names while values are information objects with next structure:
Request:
GET /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 660
Content-Type: application/json
Date: Tue, 13 Aug 2013 21:35:37 GMT
ETag: "5-fd96acb3256302bf0dd2f32713161f2a"
Server: CouchDB (Erlang/OTP)
{
"_attachments": {
"grandma_recipe.txt": {
"content_type": "text/plain",
"digest": "md5-Ids41vtv725jyrN7iUvMcQ==",
"length": 1872,
"revpos": 4,
"stub": true
},
"my_recipe.txt": {
"content_type": "text/plain",
"digest": "md5-198BPPNiT5fqlLxoYYbjBA==",
"length": 85,
"revpos": 5,
"stub": true
},
"photo.jpg": {
"content_type": "image/jpeg",
"digest": "md5-7Pv4HW2822WY1r/3WDbPug==",
"length": 165504,
"revpos": 2,
"stub": true
}
},
"_id": "SpaghettiWithMeatballs",
"_rev": "5-fd96acb3256302bf0dd2f32713161f2a",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
It’s possible to retrieve document with all attached files content by using attachements=true query parameter:
Request:
GET /db/pixel?attachments=true HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 553
Content-Type: application/json
Date: Wed, 14 Aug 2013 11:32:40 GMT
ETag: "4-f1bcae4bf7bbb92310079e632abfe3f4"
Server: CouchDB (Erlang/OTP)
{
"_attachments": {
"pixel.gif": {
"content_type": "image/gif",
"data": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
"digest": "md5-2JdGiI2i2VELZKnwMers1Q==",
"revpos": 2
},
"pixel.png": {
"content_type": "image/png",
"data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAAXNSR0IArs4c6QAAAANQTFRFAAAAp3o92gAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgOCx8VHgmcNwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=",
"digest": "md5-Dgf5zxgGuchWrve73evvGQ==",
"revpos": 3
}
},
"_id": "pixel",
"_rev": "4-f1bcae4bf7bbb92310079e632abfe3f4"
}
Or retrieve attached files content since specific revision using atts_since query parameter:
Request:
GET /recipes/SpaghettiWithMeatballs?atts_since=[%224-874985bc28906155ba0e2e0538f67b05%22] HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 760
Content-Type: application/json
Date: Tue, 13 Aug 2013 21:35:37 GMT
ETag: "5-fd96acb3256302bf0dd2f32713161f2a"
Server: CouchDB (Erlang/OTP)
{
"_attachments": {
"grandma_recipe.txt": {
"content_type": "text/plain",
"digest": "md5-Ids41vtv725jyrN7iUvMcQ==",
"length": 1872,
"revpos": 4,
"stub": true
},
"my_recipe.txt": {
"content_type": "text/plain",
"data": "MS4gQ29vayBzcGFnaGV0dGkKMi4gQ29vayBtZWV0YmFsbHMKMy4gTWl4IHRoZW0KNC4gQWRkIHRvbWF0byBzYXVjZQo1LiAuLi4KNi4gUFJPRklUIQ==",
"digest": "md5-198BPPNiT5fqlLxoYYbjBA==",
"revpos": 5
},
"photo.jpg": {
"content_type": "image/jpeg",
"digest": "md5-7Pv4HW2822WY1r/3WDbPug==",
"length": 165504,
"revpos": 2,
"stub": true
}
},
"_id": "SpaghettiWithMeatballs",
"_rev": "5-fd96acb3256302bf0dd2f32713161f2a",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
As you had noted above, retrieving document with attachements=true returns large JSON object where all attachments are included. While you document and files are smaller it’s ok, but if you have attached something bigger like media files (audio/video), parsing such response might be very expensive.
To solve this problem, CouchDB allows to get documents in multipart/related format:
Request:
GET /recipes/secret?attachments=true HTTP/1.1
Accept: multipart/related
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Content-Length: 538
Content-Type: multipart/related; boundary="e89b3e29388aef23453450d10e5aaed0"
Date: Sat, 28 Sep 2013 08:08:22 GMT
ETag: "2-c1c6c44c4bc3c9344b037c8690468605"
Server: CouchDB (Erlang OTP)
--e89b3e29388aef23453450d10e5aaed0
Content-Type: application/json
{"_id":"secret","_rev":"2-c1c6c44c4bc3c9344b037c8690468605","_attachments":{"recipe.txt":{"content_type":"text/plain","revpos":2,"digest":"md5-HV9aXJdEnu0xnMQYTKgOFA==","length":86,"follows":true}}}
--e89b3e29388aef23453450d10e5aaed0
Content-Disposition: attachment; filename="recipe.txt"
Content-Type: text/plain
Content-Length: 86
1. Take R
2. Take E
3. Mix with L
4. Add some A
5. Serve with X
--e89b3e29388aef23453450d10e5aaed0--
In this response the document contains only attachments stub information and quite short while all attachments goes as separate entities which reduces memory footprint and processing overhead (you’d noticed, that attachment content goes as raw data, not in base64 encoding, right?).
By using att_encoding_info=true query parameter you may retrieve information about compressed attachments size and used codec.
Request:
GET /recipes/SpaghettiWithMeatballs?att_encoding_info=true HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 736
Content-Type: application/json
Date: Tue, 13 Aug 2013 21:35:37 GMT
ETag: "5-fd96acb3256302bf0dd2f32713161f2a"
Server: CouchDB (Erlang/OTP)
{
"_attachments": {
"grandma_recipe.txt": {
"content_type": "text/plain",
"digest": "md5-Ids41vtv725jyrN7iUvMcQ==",
"encoded_length": 693,
"encoding": "gzip",
"length": 1872,
"revpos": 4,
"stub": true
},
"my_recipe.txt": {
"content_type": "text/plain",
"digest": "md5-198BPPNiT5fqlLxoYYbjBA==",
"encoded_length": 100,
"encoding": "gzip",
"length": 85,
"revpos": 5,
"stub": true
},
"photo.jpg": {
"content_type": "image/jpeg",
"digest": "md5-7Pv4HW2822WY1r/3WDbPug==",
"length": 165504,
"revpos": 2,
"stub": true
}
},
"_id": "SpaghettiWithMeatballs",
"_rev": "5-fd96acb3256302bf0dd2f32713161f2a",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
To create a document with multiple attachments with single request you need just inline base64 encoded attachments data into the document body:
{
"_id":"multiple_attachments",
"_attachments":
{
"foo.txt":
{
"content_type":"text\/plain",
"data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
},
"bar.txt":
{
"content_type":"text\/plain",
"data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
}
}
}
Alternatively, you can upload a document with attachments more efficiently in multipart/related format. This avoids having to Base64-encode the attachments, saving CPU and bandwidth. To do this, set the Content-Type header of the PUT /{db}/{docid} request to multipart/related.
The first MIME body is the document itself, which should have its own Content-Type of application/json". It also should include an _attachments metadata object in which each attachment object has a key follows with value true.
The subsequent MIME bodies are the attachments.
Request:
PUT /temp/somedoc HTTP/1.1
Accept: application/json
Content-Length: 372
Content-Type: multipart/related;boundary="abc123"
Host: localhost:5984
User-Agent: HTTPie/0.6.0
--abc123
Content-Type: application/json
{
"body": "This is a body.",
"_attachments": {
"foo.txt": {
"follows": true,
"content_type": "text/plain",
"length": 21
},
"bar.txt": {
"follows": true,
"content_type": "text/plain",
"length": 20
}
}
}
--abc123
this is 21 chars long
--abc123
this is 20 chars lon
--abc123--
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 72
Content-Type: application/json
Date: Sat, 28 Sep 2013 09:13:24 GMT
ETag: "1-5575e26acdeb1df561bb5b70b26ba151"
Location: http://localhost:5984/temp/somedoc
Server: CouchDB (Erlang OTP)
{
"id": "somedoc",
"ok": true,
"rev": "1-5575e26acdeb1df561bb5b70b26ba151"
}
You can obtain a list of the revisions for a given document by adding the revs=true parameter to the request URL:
Request:
GET /recipes/SpaghettiWithMeatballs?revs=true HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 584
Content-Type: application/json
Date: Wed, 14 Aug 2013 11:38:26 GMT
ETag: "5-fd96acb3256302bf0dd2f32713161f2a"
Server: CouchDB (Erlang/OTP)
{
"_id": "SpaghettiWithMeatballs",
"_rev": "8-6f5ad8db0f34af24a6e0984cd1a6cfb9",
"_revisions": {
"ids": [
"6f5ad8db0f34af24a6e0984cd1a6cfb9",
"77fba3a059497f51ec99b9b478b569d2",
"136813b440a00a24834f5cb1ddf5b1f1",
"fd96acb3256302bf0dd2f32713161f2a",
"874985bc28906155ba0e2e0538f67b05",
"0de77a37463bf391d14283e626831f2e",
"d795d1b924777732fdea76538c558b62",
"917fa2381192822767f010b95b45325b"
],
"start": 8
},
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
The returned JSON structure includes the original document, including a _revisions structure that includes the revision information in next form:
(latest first)
start (number): Prefix number for the latest revision
You can get additional information about the revisions for a given document by supplying the revs_info argument to the query:
Request:
GET /recipes/SpaghettiWithMeatballs?revs_info=true HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 802
Content-Type: application/json
Date: Wed, 14 Aug 2013 11:40:55 GMT
Server: CouchDB (Erlang/OTP)
{
"_id": "SpaghettiWithMeatballs",
"_rev": "8-6f5ad8db0f34af24a6e0984cd1a6cfb9",
"_revs_info": [
{
"rev": "8-6f5ad8db0f34af24a6e0984cd1a6cfb9",
"status": "available"
},
{
"rev": "7-77fba3a059497f51ec99b9b478b569d2",
"status": "deleted"
},
{
"rev": "6-136813b440a00a24834f5cb1ddf5b1f1",
"status": "available"
},
{
"rev": "5-fd96acb3256302bf0dd2f32713161f2a",
"status": "missing"
},
{
"rev": "4-874985bc28906155ba0e2e0538f67b05",
"status": "missing"
},
{
"rev": "3-0de77a37463bf391d14283e626831f2e",
"status": "missing"
},
{
"rev": "2-d795d1b924777732fdea76538c558b62",
"status": "missing"
},
{
"rev": "1-917fa2381192822767f010b95b45325b",
"status": "missing"
}
],
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
The returned document contains _rev_info field with extended revision information, including the availability and status of each revision. This array field contains objects with following structure:
To get a specific revision, use the rev argument to the request, and specify the full revision number. The specified revision of the document will be returned, including a _rev field specifying the revision that was requested.
Request:
GET /recipes/SpaghettiWithMeatballs?rev=6-136813b440a00a24834f5cb1ddf5b1f1 HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 271
Content-Type: application/json
Date: Wed, 14 Aug 2013 11:40:55 GMT
Server: CouchDB (Erlang/OTP)
{
"_id": "SpaghettiWithMeatballs",
"_rev": "6-136813b440a00a24834f5cb1ddf5b1f1",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs"
}
CouchDB doesn’t actually deletes documents via DELETE /{db}/{docid}. Instead of this, it leaves tombstone with very basic information about document. If you just GET /{db}/{docid} CouchDB returns 404 Not Found response:
Request:
GET /recipes/FishStew HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 404 Object Not Found
Cache-Control: must-revalidate
Content-Length: 41
Content-Type: application/json
Date: Wed, 14 Aug 2013 12:23:27 GMT
Server: CouchDB (Erlang/OTP)
{
"error": "not_found",
"reason": "deleted"
}
However, you may retrieve document’s tombstone by using rev query parameter with GET /{db}/{docid} request:
Request:
GET /recipes/FishStew?rev=2-056f5f44046ecafc08a2bc2b9c229e20 HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 79
Content-Type: application/json
Date: Wed, 14 Aug 2013 12:30:22 GMT
ETag: "2-056f5f44046ecafc08a2bc2b9c229e20"
Server: CouchDB (Erlang/OTP)
{
"_deleted": true,
"_id": "FishStew",
"_rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
}
To update an existing document you must specify the current revision number within the _rev parameter.
Request:
PUT /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Content-Length: 258
Content-Type: application/json
Host: localhost:5984
{
"_rev": "1-917fa2381192822767f010b95b45325b",
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs",
"serving": "hot"
}
Alternatively, you can supply the current revision number in the If-Match HTTP header of the request:
PUT /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Content-Length: 258
Content-Type: application/json
If-Match: 1-917fa2381192822767f010b95b45325b
Host: localhost:5984
{
"description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.",
"ingredients": [
"spaghetti",
"tomato sauce",
"meatballs"
],
"name": "Spaghetti with meatballs",
"serving": "hot"
}
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 85
Content-Type: application/json
Date: Wed, 14 Aug 2013 20:33:56 GMT
ETag: "2-790895a73b63fb91dd863388398483dd"
Location: http://localhost:5984/recipes/SpaghettiWithMeatballs
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs",
"ok": true,
"rev": "2-790895a73b63fb91dd863388398483dd"
}
To copy from a specific version, use the rev argument to the query string or If-Match:
Request:
COPY /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Destination: http://localhost:5984/recipes_old/SpaghettiWithMeatballs_Original
If-Match: 1-917fa2381192822767f010b95b45325b
Host: localhost:5984
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 93
Content-Type: application/json
Date: Wed, 14 Aug 2013 14:21:00 GMT
ETag: "1-917fa2381192822767f010b95b45325b"
Location: http://localhost:5984/recipes_old/SpaghettiWithMeatballs_Original
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs_Original",
"ok": true,
"rev": "1-917fa2381192822767f010b95b45325b"
}
To copy to an existing document, you must specify the current revision string for the target document by appending the rev parameter to the Destination header string.
Request:
COPY /recipes/SpaghettiWithMeatballs?rev=8-6f5ad8db0f34af24a6e0984cd1a6cfb9 HTTP/1.1
Accept: application/json
Destination: http://localhost:5984/recipes_old/SpaghettiWithMeatballs_Original?rev=1-917fa2381192822767f010b95b45325b
Host: localhost:5984
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 93
Content-Type: application/json
Date: Wed, 14 Aug 2013 14:21:00 GMT
ETag: "2-62e778c9ec09214dd685a981dcc24074""
Location: http://localhost:5984/recipes_old/SpaghettiWithMeatballs_Original
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs_Original",
"ok": true,
"rev": "2-62e778c9ec09214dd685a981dcc24074"
}
Returns the HTTP headers containing a minimal amount of information about the specified attachment. The method supports the same query arguments as the GET /{db}/{docid}/{attname} method, but only the header information (including attachment size, encoding and the MD5 hash as an ETag), is returned.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Status Codes: |
|
Request:
HEAD /recipes/SpaghettiWithMeatballs/recipe.txt HTTP/1.1
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Accept-Ranges: none
Cache-Control: must-revalidate
Content-Encoding: gzip
Content-Length: 100
Content-MD5: vVa/YgiE1+Gh0WfoFJAcSg==
Content-Type: text/plain
Date: Thu, 15 Aug 2013 12:42:42 GMT
ETag: "vVa/YgiE1+Gh0WfoFJAcSg=="
Server: CouchDB (Erlang/OTP)
Returns the file attachment associated with the document. The raw data of the associated attachment is returned (just as if you were accessing a static file. The returned Content-Type will be the same as the content type set when the document attachment was submitted into the database.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response: | Stored content |
| Status Codes: |
|
Uploads the supplied content as an attachment to the specified document. The attachment name provided must be a URL encoded string. You must also supply either the rev query argument or the If-Match HTTP header for validation, and the HTTP headers (to set the attachment content type).
If case when uploading an attachment using an existing attachment name, CouchDB will update the corresponding stored content of the database. Since you must supply the revision information to add an attachment to the document, this serves as validation to update the existing attachment.
Note
Uploading an attachment updates the corresponding document revision. Revisions are tracked for the parent document, not individual attachments.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
PUT /recipes/SpaghettiWithMeatballs/recipe.txt HTTP/1.1
Accept: application/json
Content-Length: 86
Content-Type: text/plain
Host: localhost:5984
If-Match: 1-917fa2381192822767f010b95b45325b
1. Cook spaghetti
2. Cook meatballs
3. Mix them
4. Add tomato sauce
5. ...
6. PROFIT!
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 85
Content-Type: application/json
Date: Thu, 15 Aug 2013 12:38:04 GMT
ETag: "2-ce91aed0129be8f9b0f650a2edcfd0a4"
Location: http://localhost:5984/recipes/SpaghettiWithMeatballs/recipe.txt
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs",
"ok": true,
"rev": "2-ce91aed0129be8f9b0f650a2edcfd0a4"
}
Deletes the attachment attachment of the specified doc. You must supply the rev query parameter or If-Match with the current revision to delete the attachment.
Note
Deleting an attachment updates the corresponding document revision. Revisions are tracked for the parent document, not individual attachments.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
DELETE /recipes/SpaghettiWithMeatballs?rev=6-440b2dd39c20413045748b42c6aba6e2 HTTP/1.1
Accept: application/json
Host: localhost:5984
Alternatively, instead of rev query parameter you may use If-Match header:
DELETE /recipes/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
If-Match: 6-440b2dd39c20413045748b42c6aba6e2
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 85
Content-Type: application/json
Date: Wed, 14 Aug 2013 12:23:13 GMT
ETag: "7-05185cf5fcdf4b6da360af939431d466"
Server: CouchDB (Erlang/OTP)
{
"id": "SpaghettiWithMeatballs",
"ok": true,
"rev": "7-05185cf5fcdf4b6da360af939431d466"
}
HTTP allows you to specify byte ranges for requests. This allows the implementation of resumable downloads and skippable audio and video streams alike. This is available for all attachments inside CouchDB.
This is just a real quick run through how this looks under the hood. Usually, you will have larger binary files to serve from CouchDB, like MP3s and videos, but to make things a little more obvious, I use a text file here (Note that I use the application/octet-stream :header`Content-Type` instead of text/plain).
shell> cat file.txt
My hovercraft is full of eels!
Now let’s store this text file as an attachment in CouchDB. First, we create a database:
shell> curl -X PUT http://<IP_ADDRESS>:5984/test
{"ok":true}
Then we create a new document and the file attachment in one go:
shell> curl -X PUT http://<IP_ADDRESS>:5984/test/doc/file.txt \
-H "Content-Type: application/octet-stream"<EMAIL_ADDRESS>{"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
Now we can request the whole file easily:
shell> curl -X GET http://<IP_ADDRESS>:5984/test/doc/file.txt
My hovercraft is full of eels!
But say we only want the first 13 bytes:
shell> curl -X GET http://<IP_ADDRESS>:5984/test/doc/file.txt \
-H "Range: bytes=0-12"
My hovercraft
HTTP supports many ways to specify single and even multiple byte ranges. Read all about it in RFC 2616.
Note
Databases that have been created with CouchDB 1.0.2 or earlier will support range requests in 1.5, but they are using a less-optimal algorithm. If you plan to make heavy use of this feature, make sure to compact your database with CouchDB 1.5 to take advantage of a better algorithm to find byte ranges.
In CouchDB, design documents provide the main interface for building a CouchDB application. The design document defines the views used to extract information from CouchDB through one or more views. Design documents are created within your CouchDB instance in the same way as you create database documents, but the content and definition of the documents is different. Design Documents are named using an ID defined with the design document URL path, and this URL can then be used to access the database contents.
Views and lists operate together to provide automated (and formatted) output from your database.
Returns the HTTP Headers containing a minimal amount of information about the specified design document.
See also
Returns design document with the specified design document` from the specified database. Unless you request a specific revision, the latest revision of the document will always be returned.
See also
The PUT method creates a new named design document, or creates a new revision of the existing design document.
The design documents have some agreement upon their fields and structure. Currently it is the next:
Note, that for filters, lists, shows and updates fields objects are mapping of function name to string function source code. For views mapping is the same except that values are objects with map and reduce (optional) keys which also contains functions source code.
See also
Deletes the specified document from the database. You must supply the current (latest) revision, either by using the rev parameter to specify the revision.
See also
The COPY (which is non-standard HTTP) copies an existing design document to a new or existing one.
Note
Copying a design document does automatically reconstruct the view indexes. These will be recreated, as with other views, the first time the new view is accessed.
See also
Returns the HTTP headers containing a minimal amount of information about the specified attachment.
See also
Returns the file attachment associated with the design document. The raw data of the associated attachment is returned (just as if you were accessing a static file.
See also
Uploads the supplied content as an attachment to the specified design document. The attachment name provided must be a URL encoded string.
See also
Deletes the attachment of the specified design document.
See also
Obtains information about the specified design document, including the index, index size and current status of the design document and associated index information.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /recipes/_design/recipe/_info HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 263
Content-Type: application/json
Date: Sat, 17 Aug 2013 12:54:17 GMT
Server: CouchDB (Erlang/OTP)
{
"name": "recipe",
"view_index": {
"compact_running": false,
"data_size": 926691,
"disk_size": 1982704,
"language": "python",
"purge_seq": 0,
"signature": "a59a1bb13fdf8a8a584bc477919c97ac",
"update_seq": 12397,
"updater_running": false,
"waiting_clients": 0,
"waiting_commit": false
}
}
The response from GET /{db}/_design/{ddoc}/_info contains view_index (object) field with the next structure:
Executes the specified view function from the specified design document.
| Parameters: |
|
|---|---|
| Request Headers: | |
|
|
| Query Parameters: | |
|
|
| Response Headers: | |
|
|
| Response JSON Object: | |
|
|
| Status Codes: |
|
Request:
GET /recipes/_design/ingredients/_view/by_name HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 09:12:06 GMT
ETag: "2FOLSBSW4O6WB798XU4AQYA9B"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset": 0,
"rows": [
{
"id": "SpaghettiWithMeatballs",
"key": "meatballs",
"value": 1
},
{
"id": "SpaghettiWithMeatballs",
"key": "spaghetti",
"value": 1
},
{
"id": "SpaghettiWithMeatballs",
"key": "tomato sauce",
"value": 1
}
],
"total_rows": 3
}
Executes the specified view function from the specified design document. Unlike the GET /{db}/_design/{ddoc}/_view/{view} method for accessing views, the POST method supports the specification of explicit keys to be retrieved from the view results. The remainder of the POST view functionality is identical to the GET /{db}/_design/{ddoc}/_view/{view} API.
Request:
POST /recipes/_design/ingredients/_view/by_name HTTP/1.1
Accept: application/json
Content-Length: 37
Host: localhost:5984
{
"keys": [
"meatballs",
"spaghetti"
]
}
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 09:14:13 GMT
ETag: "6R5NM8E872JIJF796VF7WI3FZ"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset": 0,
"rows": [
{
"id": "SpaghettiWithMeatballs",
"key": "meatballs",
"value": 1
},
{
"id": "SpaghettiWithMeatballs",
"key": "spaghetti",
"value": 1
}
],
"total_rows": 3
}
There are two view indexing options that can be defined in a design document as boolean properties of an options object. Unlike the others querying options, these aren’t URL parameters because they take effect when the view index is generated, not when it’s accessed:
In additional to these options, you may specify any other with their default value. E.g. having option "include_docs": true will automatically includes document body for view results response. You still may override such by explicitly defining same query parameter name with other value.
The definition of a view within a design document also creates an index based on the key information defined within each view. The production and use of the index significantly increases the speed of access and searching or selecting documents from the view.
However, the index is not updated when new documents are added or modified in the database. Instead, the index is generated or updated, either when the view is first accessed, or when the view is accessed after a document has been updated. In each case, the index is updated before the view query is executed against the database.
View indexes are updated incrementally in the following situations:
View indexes are rebuilt entirely when the view definition changes. To achieve this, a ‘fingerprint’ of the view definition is created when the design document is updated. If the fingerprint changes, then the view indexes are entirely rebuilt. This ensures that changes to the view definitions are reflected in the view indexes.
Note
View index rebuilds occur when one view from the same the view group (i.e. all the views defined within a single a design document) has been determined as needing a rebuild. For example, if if you have a design document with different views, and you update the database, all three view indexes within the design document will be updated.
Because the view is updated when it has been queried, it can result in a delay in returned information when the view is accessed, especially if there are a large number of documents in the database and the view index does not exist. There are a number of ways to mitigate, but not completely eliminate, these issues. These include:
None of these can completely eliminate the need for the indexes to be rebuilt or updated when the view is accessed, but they may lessen the effects on end-users of the index update affecting the user experience.
Another alternative is to allow users to access a ‘stale’ version of the view index, rather than forcing the index to be updated and displaying the updated results. Using a stale view may not return the latest information, but will return the results of the view query using an existing version of the index.
For example, to access the existing stale view by_recipe in the recipes design document:
http://localhost:5984/recipes/_design/recipes/_view/by_recipe?stale=ok
Accessing a stale view:
As an alternative, you use the update_after value to the stale parameter. This causes the view to be returned as a stale view, but for the update process to be triggered after the view information has been returned to the client.
In addition to using stale views, you can also make use of the update_seq query argument. Using this query argument generates the view information including the update sequence of the database from which the view was generated. The returned value can be compared this to the current update sequence exposed in the database information (returned by GET /{db}).
Each element within the returned array is sorted using native UTF-8 sorting according to the contents of the key portion of the emitted content. The basic order of output is as follows:
Request:
GET /db/_design/test/_view/sorting HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 10:09:25 GMT
ETag: "8LA1LZPQ37B6R9U8BK9BGQH27"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset": 0,
"rows": [
{
"id": "dummy-doc",
"key": null,
"value": null
},
{
"id": "dummy-doc",
"key": false,
"value": null
},
{
"id": "dummy-doc",
"key": true,
"value": null
},
{
"id": "dummy-doc",
"key": 0,
"value": null
},
{
"id": "dummy-doc",
"key": 1,
"value": null
},
{
"id": "dummy-doc",
"key": 10,
"value": null
},
{
"id": "dummy-doc",
"key": 42,
"value": null
},
{
"id": "dummy-doc",
"key": "10",
"value": null
},
{
"id": "dummy-doc",
"key": "hello",
"value": null
},
{
"id": "dummy-doc",
"key": "Hello",
"value": null
},
{
"id": "dummy-doc",
"key": "\u043f\u0440\u0438\u0432\u0435\u0442",
"value": null
},
{
"id": "dummy-doc",
"key": [],
"value": null
},
{
"id": "dummy-doc",
"key": [
1,
2,
3
],
"value": null
},
{
"id": "dummy-doc",
"key": [
2,
3
],
"value": null
},
{
"id": "dummy-doc",
"key": [
3
],
"value": null
},
{
"id": "dummy-doc",
"key": {},
"value": null
},
{
"id": "dummy-doc",
"key": {
"foo": "bar"
},
"value": null
}
],
"total_rows": 17
}
You can reverse the order of the returned view information by using the descending query value set to true:
Request:
GET /db/_design/test/_view/sorting?descending=true HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 10:09:25 GMT
ETag: "Z4N468R15JBT98OM0AMNSR8U"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset": 0,
"rows": [
{
"id": "dummy-doc",
"key": {
"foo": "bar"
},
"value": null
},
{
"id": "dummy-doc",
"key": {},
"value": null
},
{
"id": "dummy-doc",
"key": [
3
],
"value": null
},
{
"id": "dummy-doc",
"key": [
2,
3
],
"value": null
},
{
"id": "dummy-doc",
"key": [
1,
2,
3
],
"value": null
},
{
"id": "dummy-doc",
"key": [],
"value": null
},
{
"id": "dummy-doc",
"key": "\u043f\u0440\u0438\u0432\u0435\u0442",
"value": null
},
{
"id": "dummy-doc",
"key": "Hello",
"value": null
},
{
"id": "dummy-doc",
"key": "hello",
"value": null
},
{
"id": "dummy-doc",
"key": "10",
"value": null
},
{
"id": "dummy-doc",
"key": 42,
"value": null
},
{
"id": "dummy-doc",
"key": 10,
"value": null
},
{
"id": "dummy-doc",
"key": 1,
"value": null
},
{
"id": "dummy-doc",
"key": 0,
"value": null
},
{
"id": "dummy-doc",
"key": true,
"value": null
},
{
"id": "dummy-doc",
"key": false,
"value": null
},
{
"id": "dummy-doc",
"key": null,
"value": null
}
],
"total_rows": 17
}
The sorting direction is applied before the filtering applied using the startkey and endkey query arguments. For example the following query:
GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?startkey=%22carrots%22&endkey=%22egg%22
Accept: application/json
will operate correctly when listing all the matching entries between carrots and egg. If the order of output is reversed with the descending query argument, the view request will return no entries:
GET /recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22carrots%22&endkey=%22egg%22 HTTP/1.1
Accept: application/json
Host: localhost:5984
{
"total_rows" : 26453,
"rows" : [],
"offset" : 21882
}
The results will be empty because the entries in the view are reversed before the key filter is applied, and therefore the endkey of “egg” will be seen before the startkey of “carrots”, resulting in an empty list.
Instead, you should reverse the values supplied to the startkey and endkey parameters to match the descending sorting applied to the keys. Changing the previous example to:
GET /recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22egg%22&endkey=%22carrots%22 HTTP/1.1
Accept: application/json
Host: localhost:5984
By default CouchDB using ICU driver for sorting view results. It’s possible use binary collation instead for faster view builds where Unicode collation is not important.
To use raw collation add "collation": "raw" key-value pair to the design documents options object at the root level. After that, views will be regenerated and new order applied.
See also
By default requestion views result returns all records for it. That’s ok when they are small, but this may lead to problems when there are billions of them since the clients might have to read them all and consume all available memory.
But it’s possible to reduce output result rows by specifying limit query parameter. For example, retrieving the list of recipes using the by_title view and limited to 5 returns only 5 records, while there are total 2667 records in view:
Request:
GET /recipes/_design/recipes/_view/by_title?limit=5 HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 09:14:13 GMT
ETag: "9Q6Q2GZKPH8D5F8L7PB6DBSS9"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset" : 0,
"rows" : [
{
"id" : "3-tiersalmonspinachandavocadoterrine",
"key" : "3-tier salmon, spinach and avocado terrine",
"value" : [
null,
"3-tier salmon, spinach and avocado terrine"
]
},
{
"id" : "Aberffrawcake",
"key" : "Aberffraw cake",
"value" : [
null,
"Aberffraw cake"
]
},
{
"id" : "Adukiandorangecasserole-microwave",
"key" : "Aduki and orange casserole - microwave",
"value" : [
null,
"Aduki and orange casserole - microwave"
]
},
{
"id" : "Aioli-garlicmayonnaise",
"key" : "Aioli - garlic mayonnaise",
"value" : [
null,
"Aioli - garlic mayonnaise"
]
},
{
"id" : "Alabamapeanutchicken",
"key" : "Alabama peanut chicken",
"value" : [
null,
"Alabama peanut chicken"
]
}
],
"total_rows" : 2667
}
To omit some records you may use skip query parameter:
Request:
GET /recipes/_design/recipes/_view/by_title?limit=3&skip=2 HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 21 Aug 2013 09:14:13 GMT
ETag: "H3G7YZSNIVRRHO5FXPE16NJHN"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
{
"offset" : 2,
"rows" : [
{
"id" : "Adukiandorangecasserole-microwave",
"key" : "Aduki and orange casserole - microwave",
"value" : [
null,
"Aduki and orange casserole - microwave"
]
},
{
"id" : "Aioli-garlicmayonnaise",
"key" : "Aioli - garlic mayonnaise",
"value" : [
null,
"Aioli - garlic mayonnaise"
]
},
{
"id" : "Alabamapeanutchicken",
"key" : "Alabama peanut chicken",
"value" : [
null,
"Alabama peanut chicken"
]
}
],
"total_rows" : 2667
}
Warning
Using limit and skip parameters is not recommended for results pagination. Read pagination recipe why it’s so and how to make it better.
Applies show function for null document.
The request and response parameters are depended upon function implementation.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Query Parameters: | |
|
|
| Status Codes: |
|
Function:
function(doc, req) {
if (!doc) {
return {body: "no doc"}
} else {
return {body: doc.description}
}
}
Request:
GET /recipes/_design/recipe/_show/description HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Content-Length: 6
Content-Type: text/html; charset=utf-8
Date: Wed, 21 Aug 2013 12:34:07 GMT
Etag: "7Z2TO7FPEMZ0F4GH0RJCRIOAU"
Server: CouchDB (Erlang/OTP)
Vary: Accept
no doc
Applies show function for the specified document.
The request and response parameters are depended upon function implementation.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Query Parameters: | |
|
|
| Status Codes: |
|
Function:
function(doc, req) {
if (!doc) {
return {body: "no doc"}
} else {
return {body: doc.description}
}
}
Request:
GET /recipes/_design/recipe/_show/description/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Content-Length: 88
Content-Type: text/html; charset=utf-8
Date: Wed, 21 Aug 2013 12:38:08 GMT
Etag: "8IEBO8103EI98HDZL5Z4I1T0C"
Server: CouchDB (Erlang/OTP)
Vary: Accept
An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.
Applies list function for the view function from the same design document.
The request and response parameters are depended upon function implementation.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Query Parameters: | |
|
|
| Status Codes: |
|
Function:
function(head, req) {
var row = getRow();
if (!row){
return 'no ingredients'
}
send(row.key);
while(row=getRow()){
send(', ' + row.key);
}
}
Request:
GET /recipes/_design/recipe/_list/ingredients/by_name HTTP/1.1
Accept: text/plain
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Wed, 21 Aug 2013 12:49:15 GMT
Etag: "D52L2M1TKQYDD1Y8MEYJR8C84"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
Vary: Accept
meatballs, spaghetti, tomato sauce
Applies list function for the view function from the other design document.
The request and response parameters are depended upon function implementation.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Query Parameters: | |
|
|
| Status Codes: |
|
Function:
function(head, req) {
var row = getRow();
if (!row){
return 'no ingredients'
}
send(row.key);
while(row=getRow()){
send(', ' + row.key);
}
}
Request:
GET /recipes/_design/ingredient/_list/ingredients/recipe/by_ingredient?key="spaghetti" HTTP/1.1
Accept: text/plain
Host: localhost:5984
Response:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Wed, 21 Aug 2013 12:49:15 GMT
Etag: "5L0975X493R0FB5Z3043POZHD"
Server: CouchDB (Erlang/OTP)
Transfer-Encoding: chunked
Vary: Accept
spaghetti
Executes update function on server side for null document.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Status Codes: |
|
Function:
function(doc, req) {
if (!doc){
return [null, {'code': 400,
'json': {'error': 'missed',
'reason': 'no document to update'}}]
} else {
doc.ingredients.push(req.body);
return [doc, {'json': {'status': 'ok'}}];
}
}
Request:
POST /recipes/_design/recipe/_update/ingredients HTTP/1.1
Accept: application/json
Content-Length: 10
Content-Type: application/json
Host: localhost:5984
something
Response:
HTTP/1.1 404 Object Not Found
Cache-Control: must-revalidate
Content-Length: 52
Content-Type: application/json
Date: Wed, 21 Aug 2013 14:00:58 GMT
Server: CouchDB (Erlang/OTP)
{
"error": "missed",
"reason": "no document to update"
}
Executes update function on server side for the specified document.
| Parameters: |
|
|---|---|
| Response Headers: | |
|
|
| Status Codes: |
|
Function:
function(doc, req) {
if (!doc){
return [null, {'code': 400,
'json': {'error': 'missed',
'reason': 'no document to update'}}]
} else {
doc.ingredients.push(req.body);
return [doc, {'json': {'status': 'ok'}}];
}
}
Request:
POST /recipes/_design/recipe/_update/ingredients/SpaghettiWithMeatballs HTTP/1.1
Accept: application/json
Content-Length: 5
Content-Type: application/json
Host: localhost:5984
love
Response:
HTTP/1.1 201 Created
Cache-Control: must-revalidate
Content-Length: 16
Content-Type: application/json
Date: Wed, 21 Aug 2013 14:11:34 GMT
Server: CouchDB (Erlang/OTP)
X-Couch-Id: SpaghettiWithMeatballs
X-Couch-Update-NewRev: 12-a5e099df5720988dae90c8b664496baf
{
"status": "ok"
}
Rewrites the specified path by rules defined in the specified design document.
The rewrite rules are defined in array field of the design document called rewrites. Each rule is an object with next structure:
The to``and ``from paths may contains string patterns with leading : or * characters.
For example: /somepath/:var/*
The pattern matching is done by first matching the request method to a rule. By default all methods match a rule. (method is equal to "*" by default). Then It will try to match the path to one rule. If no rule match, then a 404 Not Found response returned.
Once a rule is found we rewrite the request url using the to and query fields. The identified token are matched to the rule and will replace var. If '*' is found in the rule it will contain the remaining part if it exists.
Examples:
| Rule | Url | Rewrite to | Tokens |
|---|---|---|---|
| {“from”: “/a”, “to”: “/some”} | /a | /some | |
| {“from”: “/a/*”, “to”: “/some/*} | /a/b/c | /some/b/c | |
| {“from”: “/a/b”, “to”: “/some”} | /a/b?k=v | /some?k=v | k=v |
| {“from”: “/a/b”, “to”: “/some/:var”} | /a/b | /some/b?var=b | var=b |
| {“from”: “/a/:foo/”, “to”: “/some/:foo/”} | /a/b/c | /some/b/c?foo=b | foo=b |
| {“from”: “/a/:foo”, “to”: “/some”, “query”: { “k”: ”:foo” }} | /a/b | /some/?k=b&foo=b | foo=b |
| {“from”: “/a”, “to”: “/some/:foo”} | /a?foo=b | /some/?b&foo=b | foo=b |
Request method, header, query parameters, request payload and response body are depended on endpoint to which url will be rewrited.
| Parameters: |
|
|---|
The Local (non-replicating) document interface allows you to create local documents that are not replicated to other databases. These documents can be used to hold configuration or other information that is required specifically on the local CouchDB instance.
Local documents have the following limitations:
Local documents can be used when you want to store configuration or other information for the current (local) instance of a given database.
A list of the available methods and URL paths are provided below:
| Method | Path | Description |
|---|---|---|
| GET | /db/_local/id | Returns the latest revision of the non-replicated document |
| PUT | /db/_local/id | Inserts a new version of the non-replicated document |
| DELETE | /db/_local/id | Deletes the non-replicated document |
| COPY | /db/_local/id | Copies the non-replicated document |
Gets the specified local document. The semantics are identical to accessing a standard document in the specified database, except that the document is not replicated. See GET /{db}/{docid}.
Stores the specified local document. The semantics are identical to storing a standard document in the specified database, except that the document is not replicated. See PUT /{db}/{docid}.
Deletes the specified local document. The semantics are identical to deleting a standard document in the specified database, except that the document is not replicated. See DELETE /{db}/{docid}.
Copies the specified local document. The semantics are identical to copying a standard document in the specified database, except that the document is not replicated. See COPY /{db}/{docid}.
The following appendix provides a quick reference to all the JSON structures that you can supply to CouchDB, or get in return to requests.
| Field | Description |
|---|---|
| total_rows | Number of documents in the database/view |
| offset | Offset where the document list started |
| update_seq (optional) | Current update sequence for the database |
| rows [array] | Array of document object |
| Field | Description |
|---|---|
| docs [array] | Bulk Docs Returned Documents |
| id | Document ID |
| error | Error type |
| reason | Error string with extended reason |
| Field | Description |
|---|---|
| all_or_nothing (optional) | Sets the database commit mode to use all-or-nothing semantics |
| docs [array] | Bulk Documents Document |
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| _deleted (optional) | Whether the document should be deleted |
| Field | Description |
|---|---|
| last_seq | Last change sequence number |
| results [array] | Changes made to a database |
| seq | Update sequence number |
| id | Document ID |
| changes [array] | List of changes, field-by-field, for this document |
| Field | Description |
|---|---|
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| Field | Description |
|---|---|
| id | Document ID |
| error | Error type |
| reason | Error string with extended reason |
| Field | Description |
|---|---|
| db_name | The name of the database. |
| committed_update_seq | The number of committed update. |
| doc_count | A count of the documents in the specified database. |
| doc_del_count | Number of deleted documents |
| compact_running | Set to true if the database compaction routine is operating on this database. |
| disk_format_version | The version of the physical format used for the data when it is stored on disk. |
| disk_size | Size in bytes of the data as stored on the disk. Views indexes are not included in the calculation. |
| instance_start_time | Timestamp of when the database was opened, expressed in microseconds since the epoch. |
| purge_seq | The number of purge operations on the database. |
| update_seq | The current number of updates to the database. |
| Field | Description |
|---|---|
| _id | Design Document ID |
| _rev | Design Document Revision |
| views | View |
| viewname | View Definition |
| map | Map Function for View |
| reduce (optional) | Reduce Function for View |
| Field | Description |
|---|---|
| name | Name/ID of Design Document |
| view_index | View Index |
| compact_running | Indicates whether a compaction routine is currently running on the view |
| disk_size | Size in bytes of the view as stored on disk |
| language | Language for the defined views |
| purge_seq | The purge sequence that has been processed |
| signature | MD5 signature of the views for the design document |
| update_seq | The update sequence of the corresponding database that has been indexed |
| updater_running | Indicates if the view is currently being updated |
| waiting_clients | Number of clients waiting on views from this design document |
| waiting_commit | Indicates if there are outstanding commits to the underlying database that need to processed |
| Field | Description |
|---|---|
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| _attachments (optional) | Document Attachment |
| filename | Attachment information |
| content_type | MIME Content type string |
| data | File attachment content, Base64 encoded |
| Field | Description |
|---|---|
| tasks [array] | Active Task |
| pid | Process ID |
| status | Task status message |
| task | Task name |
| type | Operation Type |
| Field | Description |
|---|---|
| source | Source database name or URL |
| target | Target database name or URL |
| create_target (optional) | Creates the target database |
| continuous (optional) | Configure the replication to be continuous |
| cancel (optional) | Cancels the replication |
| doc_ids (optional) | Array of document IDs to be synchronized |
| proxy (optional) | Address of a proxy server through which replication should occur |
| since_seq (optional) | Sequence from which the replication should start |
| filter (optional) | name of the filter function in the form of ddoc/myfilter |
| query_params (optional) | query parameter that are passed to the filter function; value should be a document containing parameters as members |
| Field | Description |
|---|---|
| ok | Replication status |
| session_id | Unique session ID |
| source_last_seq | Last sequence number read from source database |
| history [array] | Replication History |
| session_id | Session ID for this replication operation |
| recorded_seq | Last recorded sequence number |
| docs_read | Number of documents read |
| docs_written | Number of documents written to target |
| doc_write_failures | Number of document write failures |
| start_time | Date/Time replication operation started |
| start_last_seq | First sequence number in changes stream |
| end_time | Date/Time replication operation completed |
| end_last_seq | Last sequence number in changes stream |
| missing_checked | Number of missing documents checked |
| missing_found | Number of missing documents found |
| Field | Description |
|---|---|
| body | Request body data as string. If request method is GET method contains this field contains "undefined" value, while if DELETE or HEAD value is "" (empty string) |
| cookie | Cookies object. |
| form | Form data object. Contains decoded body as key-value pairs if Content-Type header was application/x-www-form-urlencoded. |
| headers | Request headers object. |
| id | Requested document id string if it was specified or null otherwise. |
| info | Database information |
| method | Request method as string or array. String value is method is one of: HEAD, GET, POST, PUT, DELETE, OPTIONS, and TRACE, otherwise it will be represented as array of char codes. |
| path | List of requested path sections. |
| peer | Request source IP address. |
| query | URL query parameters object. Note that multiple keys not supported and last key value suppress others. |
| requested_path | List of actual requested path section. |
| raw_path | Raw requested path string. |
| secObj | Security Object. |
| userCtx | User Context Object. |
| uuid | Generated UUID by specified algorithm in config file. |
{
"body": "undefined",
"cookie": {
"AuthSession": "cm9vdDo1MDZBRjQzRjrfcuikzPRfAn-EA37FmjyfM8G8Lw",
"m": "3234"
},
"form": {},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "en-US,en;q=0.8",
"Connection": "keep-alive",
"Cookie": "m=3234:t|3247:t|6493:t|6967:t|34e2:|18c3:t|2c69:t|5acb:t|ca3:t|c01:t|5e55:t|77cb:t|2a03:t|1d98:t|47ba:t|64b8:t|4a01:t; AuthSession=cm9vdDo1MDZBRjQzRjrfcuikzPRfAn-EA37FmjyfM8G8Lw",
"Host": "<IP_ADDRESS>:5984",
"User-Agent": "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7"
},
"id": "foo",
"info": {
"committed_update_seq": 2701412,
"compact_running": false,
"data_size":<PHONE_NUMBER>,
"db_name": "mailbox",
"disk_format_version": 6,
"disk_size":<PHONE_NUMBER>3,
"doc_count": 2262757,
"doc_del_count": 560,
"instance_start_time": "1347601025628957",
"purge_seq": 0,
"update_seq": 2701412
},
"method": "GET",
"path": [
"mailbox",
"_design",
"request",
"_show",
"dump",
"foo"
],
"peer": "<IP_ADDRESS>",
"query": {},
"raw_path": "/mailbox/_design/request/_show/dump/foo",
"requested_path": [
"mailbox",
"_design",
"request",
"_show",
"dump",
"foo"
],
"secObj": {
"admins": {
"names": [
"Bob"
],
"roles": []
},
"members": {
"names": [
"Mike",
"Alice"
],
"roles": []
}
},
"userCtx": {
"db": "mailbox",
"name": "Mike",
"roles": [
"user"
]
},
"uuid": "3184f9d1ea934e1f81a24c71bde5c168"
}
| Field | Description |
|---|---|
| code | HTTP status code number. |
| json | JSON encodable object. Implicitly sets Content-Type header as application/json. |
| body | Raw response text string. Implicitly sets Content-Type header as text/html; charset=utf-8. |
| base64 | Base64 encoded string. Implicitly sets Content-Type header as application/binary. |
| headers | Response headers object. Content-Type header from this object overrides any implicitly assigned one. |
| stop | boolean signal to stop iteration over view result rows (for list functions only) |
Warning
body, base64 and json object keys are overlaps each other and the last wins. Since most realizations of key-value objects doesn’t preserve key order mixing them may create confusing situation. Try to use only one of them.
Note
Any custom property makes CouchDB raise internal exception. Also Response object could be a simple string value which would be implicitly wrapped into {"body": ...} object.
| Field | Description |
|---|---|
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| _revs_info [array] | CouchDB Document Extended Revision Info |
| rev | Full revision string |
| status | Status of the revision |
| Field | Description |
|---|---|
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| _revisions | CouchDB Document Revisions |
| ids [array] | Array of valid revision IDs, in reverse order (latest first) |
| start | Prefix number for the latest revision |
| Field | Description |
|---|---|
| _id (optional) | Document ID |
| _rev (optional) | Revision ID (when updating an existing document) |
| _attachments (optional) | Document Attachment |
| filename | Attachment |
| stub | Indicates whether the attachment is a stub |
| content_type | MIME Content type string |
| length | Length (bytes) of the attachment data |
| revpos | Revision where this attachment exists |
| Field | Description |
|---|---|
| admins | Roles/Users with admin privileges |
| roles [array] | List of roles with parent privilege |
| users [array] | List of users with parent privilege |
| readers | Roles/Users with reader privileges |
| roles [array] | List of roles with parent privilege |
| users [array] | List of users with parent privilege |
{
"admins": {
"names": [
"Bob"
],
"roles": []
},
"members": {
"names": [
"Mike",
"Alice"
],
"roles": []
}
}
| Field | Description |
|---|---|
| db | Database name in context of provided operation. |
| name | User name. |
| roles | List of user roles. |
{
"db": "mailbox",
"name": null,
"roles": [
"_admin"
]
}
| Field | Description |
|---|---|
| total_rows | Number of documents in the view |
| offset | Offset where the document list started |
{
"total_rows": 42,
"offset": 3
}
This is a list of experimental features in CouchDB. They are included in a release because the development team is requesting feedback from the larger developer community. As such, please play around with these features and send us feedback, thanks!
Use at your own risk! Do not rely on these features for critical applications.
The NodeJS Query Server is an alternative runtime environment for the default JavaScript Query Server that runs on top of Node.JS and not SpiderMonkey like the default Query Server.
You will need to install Node.JS version 0.10.0 or later. See Node.JS Downloads for options.
Install the couchjs-node binary. Either from the CouchDB sources:
cd src/couchjs-node
npm link
Or via NPM:
npm install -g couchjs
Note
NPM in non-standard locations
If your Node.JS installation doesn’t store binaries in /usr/local/bin you will need to adjust CouchDB’s configuration. Add this to your local.ini file:
[query_servers]
nodejs = /path/to/couchjs-node /path/to/couchdb/share/server/main.js
And then restart your CouchDB instance.
2. Done. Now you can create design documents with the language parameter set to nodejs and all JavaScript functions in this design document will be processed by the Node.JS query server.
Enjoy!
V8 and SpiderMonkey roughly behave similar, but there might be engine- specific differences that make or break a JavaScript function in one or the other server.
See src/couch_plugins/README.md.
The documentation lives in the CouchDB source tree. We’ll start by forking and closing the CouchDB GitHub mirror. That will allow us to send the contribution to CouchDB with a pull request.
If you don’t have a GitHub account yet, it is a good time to get one, they are free. If you don’t want to use GitHub, there are alternate ways to contributing back, that we’ll cover next time.
Go to https://github.com/apache/couchdb and click the “fork” button in the top right. This will create a fork of CouchDB in your GitHub account. Mine is janl, so my fork lives at https://github.com/janl/couchdb. In the header, it tells me me my “GitHub Clone URL”. We need to copy that and start a terminal:
$ git clone https://github.com/janl/couchdb.git
$ cd couchdb
$ subl .
I’m opening the whole CouchDB source tree in my favourite editor. It gives me the usual directory listing:
.git/
.gitignore
.mailmap
.travis.yml
AUTHORS
BUGS
CHANGES
DEVELOPERS
INSTALL
INSTALL.Unix
INSTALL.Windows
LICENSE
Makefile.am
NEWS
NOTICE
README
THANKS.in
acinclude.m4.in
bin/
bootstrap
build-aux/
configure.ac
etc/
license.skip
share/
src/
test/
utils/
var/
The documentation sources live in share/doc/src, you can safely ignore all the other files and directories.
First we should determine where we want to document this inside the documentation. We can look through http://docs.couchdb.org/en/latest/ for inspiration. The JSON Structure Reference looks like a fine place to write this up.
The current state includes mostly tables describing the JSON structure (after all, that’s the title of this chapter), but some prose about the number representation can’t hurt. For future reference, since the topic in the thread includes views and different encoding in views (as opposed to the storage engine), we should remember to make a note in the views documentation as well, but we’ll leave this for later.
Let’s try and find the source file that builds the file http://docs.couchdb.org/en/latest/json-structure.html – we are in luck, under share/doc/src we find the file json-structure.rst. That looks promising. .rst stands for ReStructured Text (see http://thomas-cokelaer.info/tutorials/sphinx/rest_syntax.html for a markup reference), which is an ascii format for writing documents, documentation in this case. Let’s have a look and open it.
We see ascii tables with some additional formatting, all looking like the final HTML. So far so easy. For now, let’s just add to the bottom of this. We can worry about organising this better later.
We start by adding a new headline:
Number Handling
===============
Now we paste in the rest of the main email of the thread. It is mostly text, but it includes some code listings. Let’s mark them up. We’ll turn:
ejson:encode(ejson:decode(<<"1.1">>)).
<<"1.1000000000000000888">>
Into:
.. code-block:: erlang
ejson:encode(ejson:decode(<<"1.1">>)).
<<"1.1000000000000000888">>
And we follow along with the other code samples.
I cleaned up the text a little but to make it sound more like a documentation entry as opposed to a post on a mailing list.
The next step would be to validate that we got all the markup right. I’ll leave this for later. For now we’ll contribute our change back to CouchDB.
 Fill in the description with something useful and hit the “Send Pull Request” button.
And we’re done!
We now support Erlang/OTP R16B and R16B01; the minimum required version is R14B.
User document role values must now be strings. Other types of values will be refused when saving the user document.
You can upgrade your existing CouchDB 1.0.x installation to 1.3.0 without any specific steps or migration. When you run CouchDB, the existing data and index files will be opened and used as normal.
The first time you run a compaction routine on your database within 1.3.0, the data structure and indexes will be updated to the new version of the CouchDB database format that can only be read by CouchDB 1.3.0 and later. This step is not reversible. Once the data files have been updated and migrated to the new version the data files will no longer work with a CouchDB 1.0.x release.
Warning
If you want to retain support for opening the data files in CouchDB 1.0.x you must back up your data files before performing the upgrade and compaction process.
Warning
This version drops support for the database format that was introduced in version 0.9.0. Compact your older databases (that have not been compacted for a long time) before upgrading, or they will become inaccessible.
Warning
Version 1.2.1 contains important security fixes. Previous 1.2.x releases are not recommended for regular usage.
The interface to the _users and _replicator databases have been changed so that non-administrator users can see less information:
The new optional (but enabled by default) compression of disk files requires an upgrade of the on-disk format (5 -> 6) which occurs on creation for new databases and views, and on compaction for existing files. This format is not supported in previous releases, so rollback would require replication to the previous CouchDB release or restoring from backup.
Compression can be disabled by setting compression = none in your local.ini [couchdb] section, but the on-disk format will still be upgraded.
Warning
Version 1.1.2 contains important security fixes. Previous 1.1.x releases are not recommended for regular usage.
- Fix pull replication of documents with many revisions.
- Fix replication from an HTTP source to an HTTP target.
Note
All CHANGES for 1.0.2 and 1.0.3 also apply to 1.1.0.
Note, to replicate with a 1.0 CouchDB instance you must first upgrade in-place your current CouchDB to 1.0 or 0.11.1 – backporting so that 0.10.x can replicate to 1.0 wouldn’t be that hard. All that is required is patching the replicator to use the application/json content type.
Warning
Version 1.0.4 contains important security fixes. Previous 1.0.x releases are not recommended for regular usage.
people from getting locked out.
Warning
Version 0.11.2 contains important security fixes. Previous 0.11.x releases are not recommended for regular usage.
The req argument to show, list, update and validation functions now contains the member method with the specified HTTP method of the current request. Previously, this member was called verb. method is following RFC 2616 (HTTP 1.1) closer.
The /db/_admins handler has been removed and replaced with a /db/_security object. Any existing _admins will be dropped and need to be added to the security object again. The reason for this is that the old system made no distinction between names and roles, while the new one does, so there is no way to automatically upgrade the old admins list.
The security object has 2 special fields, admins and readers, which contain lists of names and roles which are admins or readers on that database. Anything else may be stored in other fields on the security object. The entire object is made available to validation functions.
JSON handling in the query server has been upgraded to use json2.js. This allows us to use faster native JSON serialization when it is available.
In previous versions, attempts to serialize undefined would throw an exception, causing the doc that emitted undefined to be dropped from the view index. The new behavior is to serialize undefined as null. Applications depending on the old behavior will need to explicitly check for undefined.