database¶
API module that maps to a Cloudant or CouchDB database instance.
-
class
cloudant.database.
CloudantDatabase
(client, database_name, fetch_limit=100, partitioned=False)¶ Bases:
cloudant.database.CouchDatabase
Encapsulates a Cloudant database. A CloudantDatabase object is instantiated with a reference to a client/session. It supports accessing the documents, and various database features such as the document indexes, changes feed, design documents, etc.
Parameters: - client (Cloudant) – Client instance used by the database.
- database_name (str) – Database name used to reference the database.
- fetch_limit (int) – Optional fetch limit used to set the max number of documents to fetch per query during iteration cycles. Defaults to 100.
- partitioned (bool) – Create as a partitioned database. Defaults to
False
.
-
get_partitioned_search_result
(partition_key, ddoc_id, index_name, **query_params)¶ Retrieves the raw JSON content from the remote database based on the partitioned search index on the server, using the query_params provided as query parameters.
See
get_search_result()
method for further details.Parameters: - partition_key (str) – Partition key.
- ddoc_id (str) – Design document id used to get the search result.
- index_name (str) – Name used in part to identify the index.
- query_params – See
get_search_result()
method for available keyword arguments.
Returns: Search query result data in JSON format.
Return type:
-
get_search_result
(ddoc_id, index_name, **query_params)¶ Retrieves the raw JSON content from the remote database based on the search index on the server, using the query_params provided as query parameters. A
query
parameter containing the Lucene query syntax is mandatory.Example for search queries:
# Assuming that 'searchindex001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve documents where the Lucene field name is 'name' and # the value is 'julia*' resp = db.get_search_result('ddoc001', 'searchindex001', query='name:julia*', include_docs=True) for row in resp['rows']: # Process search index data (in JSON format).
Example if the search query requires grouping by using the
group_field
parameter:# Assuming that 'searchindex001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve JSON response content, limiting response to 10 documents resp = db.get_search_result('ddoc001', 'searchindex001', query='name:julia*', group_field='name', limit=10) for group in resp['groups']: for row in group['rows']: # Process search index data (in JSON format).
Parameters: - ddoc_id (str) – Design document id used to get the search result.
- index_name (str) – Name used in part to identify the index.
- bookmark (str) – Optional string that enables you to specify which
page of results you require. Only valid for queries that do not
specify the
group_field
query parameter. - counts (list) – Optional JSON array of field names for which counts should be produced. The response will contain counts for each unique value of this field name among the documents matching the search query. Requires the index to have faceting enabled.
- drilldown (list) – Optional list of fields that each define a
pair of a field name and a value. This field can be used several
times. The search will only match documents that have the given
value in the field name. It differs from using
query=fieldname:value
only in that the values are not analyzed. - group_field (str) – Optional string field by which to group search matches. Fields containing other data (numbers, objects, arrays) can not be used.
- group_limit (int) – Optional number with the maximum group count.
This field can only be used if
group_field
query parameter is specified. - group_sort – Optional JSON field that defines the order of the
groups in a search using
group_field
. The default sort order is relevance. This field can have the same values as the sort field, so single fields as well as arrays of fields are supported. - limit (int) – Optional number to limit the maximum count of the returned documents. In case of a grouped search, this parameter limits the number of documents per group.
- query/q – A Lucene query in the form of
name:value
. If name is omitted, the special valuedefault
is used. Thequery
parameter can be abbreviated asq
. - ranges – Optional JSON facet syntax that reuses the standard
Lucene syntax to return counts of results which fit into each
specified category. Inclusive range queries are denoted by brackets.
Exclusive range queries are denoted by curly brackets.
For example
ranges={"price":{"cheap":"[0 TO 100]"}}
has an inclusive range of 0 to 100. Requires the index to have faceting enabled. - sort – Optional JSON string of the form
fieldname<type>
for ascending or-fieldname<type>
for descending sort order. Fieldname is the name of a string or number field and type is either number or string or a JSON array of such strings. The type part is optional and defaults to number. - stale (str) – Optional string to allow the results from a stale index to be used. This makes the request return immediately, even if the index has not been completely built yet.
- highlight_fields (list) – Optional list of fields which should be highlighted.
- highlight_pre_tag (str) – Optional string inserted before the
highlighted word in the highlights output. Defaults to
<em>
. - highlight_post_tag (str) – Optional string inserted after the
highlighted word in the highlights output. Defaults to
</em>
. - highlight_number (int) – Optional number of fragments returned in highlights. If the search term occurs less often than the number of fragments specified, longer fragments are returned. Default is 1.
- highlight_size (int) – Optional number of characters in each fragment for highlights. Defaults to 100 characters.
- include_fields (list) – Optional list of field names to include in
search results. Any fields included must have been indexed with the
store:true
option.
Returns: Search query result data in JSON format
-
security_document
()¶ Retrieves the security document for the current database containing information about the users that the database is shared with.
Returns: Security document as a dict
-
security_url
¶ Constructs and returns the security document URL.
Returns: Security document URL
-
shards
()¶ Retrieves information about the shards in the current remote database.
Returns: Shard information retrieval status in JSON format
Shares the current remote database with the username provided. You can grant varying degrees of access rights, default is to share read-only, but additional roles can be added by providing the specific roles as a
list
argument. If the user already has this database shared with them then it will modify/overwrite the existing permissions.Parameters: Returns: Share database status in JSON format
Removes all sharing with the named user for the current remote database. This will remove the entry for the user from the security document. To modify permissions, use the
share_database()
method instead.Parameters: username (str) – Cloudant user to unshare the database from. Returns: Unshare database status in JSON format
-
class
cloudant.database.
CouchDatabase
(client, database_name, fetch_limit=100, partitioned=False)¶ Bases:
dict
Encapsulates a CouchDB database. A CouchDatabase object is instantiated with a reference to a client/session. It supports accessing the documents, and various database features such as the document indexes, changes feed, design documents, etc.
Parameters: - client (CouchDB) – Client instance used by the database.
- database_name (str) – Database name used to reference the database.
- fetch_limit (int) – Optional fetch limit used to set the max number of documents to fetch per query during iteration cycles. Defaults to 100.
- partitioned (bool) – Create as a partitioned database. Defaults to
False
.
-
__getitem__
(key)¶ Overrides dictionary __getitem__ behavior to provide a document instance for the specified key from the current database.
If the document instance does not exist locally, then a remote request is made and the document is subsequently added to the local cache and returned to the caller.
If the document instance already exists locally then it is returned and a remote request is not performed.
A KeyError will result if the document does not exist locally or in the remote database.
Parameters: key (str) – Document id used to retrieve the document from the database. Returns: A Document or DesignDocument object depending on the specified document id (key)
-
__iter__
(remote=True)¶ Overrides dictionary __iter__ behavior to provide iterable Document results. By default, Documents are fetched from the remote database, in batches equal to the database object’s defined
fetch_limit
, yielding Document/DesignDocument objects.If
remote=False
then the locally cached Document objects are iterated over with no attempt to retrieve documents from the remote database.Parameters: remote (bool) – Dictates whether the locally cached Document objects are returned or a remote request is made to retrieve Document objects from the remote database. Defaults to True. Returns: Iterable of Document and/or DesignDocument objects
-
admin_party
¶ Returns the CouchDB Admin Party status.
True
if using Admin PartyFalse
otherwise.Returns: CouchDB Admin Party mode status
-
all_docs
(**kwargs)¶ Wraps the _all_docs primary index on the database, and returns the results by value. This can be used as a direct query to the _all_docs endpoint. More convenient/efficient access using keys, slicing and iteration can be done through the
result
attribute.Keyword arguments supported are those of the view/index access API.
Parameters: - descending (bool) – Return documents in descending key order.
- endkey – Stop returning records at this specified key.
- endkey_docid (str) – Stop returning records when the specified document id is reached.
- include_docs (bool) – Include the full content of the documents.
- inclusive_end (bool) – Include rows with the specified endkey.
- key – Return only documents that match the specified key.
- keys (list) – Return only documents that match the specified keys.
- limit (int) – Limit the number of returned documents to the specified count.
- skip (int) – Skip this number of rows from the start.
- startkey – Return records starting with the specified key.
- startkey_docid (str) – Return records starting with the specified document ID.
Returns: Raw JSON response content from
_all_docs
endpoint
-
bulk_docs
(docs)¶ Performs multiple document inserts and/or updates through a single request. Each document must either be or extend a dict as is the case with Document and DesignDocument objects. A document must contain the
_id
and_rev
fields if the document is meant to be updated.Parameters: docs (list) – List of Documents to be created/updated. Returns: Bulk document creation/update status in JSON format
-
changes
(raw_data=False, **kwargs)¶ Returns the
_changes
feed iterator. The_changes
feed can be iterated over and once complete can also provide the last sequence identifier of the feed. If necessary, the iteration can be stopped by issuing a call to thestop()
method on the returned iterator object.For example:
# Iterate over a "normal" _changes feed changes = db.changes() for change in changes: print(change) print(changes.last_seq) # Iterate over a "continuous" _changes feed with additional options changes = db.changes(feed='continuous', since='now', descending=True) for change in changes: if some_condition: changes.stop() print(change)
Parameters: - raw_data (bool) – If set to True then the raw response data will be streamed otherwise if set to False then JSON formatted data will be streamed. Default is False.
- conflicts (bool) – Can only be set if include_docs is True. Adds information about conflicts to each document. Default is False.
- descending (bool) – Changes appear in sequential order. Default is False.
- doc_ids (list) – To be used only when
filter
is set to_doc_ids
. Filters the feed so that only changes to the specified documents are sent. - feed (str) – Type of feed. Valid values are
continuous
,longpoll
, andnormal
. Default isnormal
. - filter (str) – Name of filter function from a design document to get updates. Default is no filter.
- heartbeat (int) – Time in milliseconds after which an empty line is
sent during
longpoll
orcontinuous
if there have been no changes. Must be a positive number. Default is no heartbeat. - include_docs (bool) – Include the document with the result. The
document will not be returned as a
Document
but instead will be returned as either formated JSON or as raw response content. Default is False. - limit (int) – Maximum number of rows to return. Must be a positive number. Default is no limit.
- since – Start the results from changes after the specified
sequence identifier. In other words, using since excludes from the
list all changes up to and including the specified sequence
identifier. If since is 0 (the default), or omitted, the request
returns all changes. If it is
now
, only changes made after the time of the request will be emitted. - style (str) – Specifies how many revisions are returned in the
changes array. The default,
main_only
, only returns the current “winning” revision;all_docs
returns all leaf revisions, including conflicts and deleted former conflicts. - timeout (int) – Number of milliseconds to wait for data before
terminating the response.
heartbeat
supersedestimeout
if both are supplied. - chunk_size (int) – The HTTP response stream chunk size. Defaults to 512.
Returns: Feed object that can be iterated over as a
_changes
feed.
-
create
(throw_on_exists=False)¶ Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op.
Parameters: throw_on_exists (bool) – Boolean flag dictating whether or not to throw a CloudantDatabaseException when attempting to create a database that already exists. Returns: The database object
-
create_document
(data, throw_on_exists=False)¶ Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a
Document
or aDesignDocument
object will be added to the locally cached database and returned by this method.Parameters: Returns: A
Document
orDesignDocument
instance corresponding to the new document in the database.
-
create_query_index
(design_document_id=None, index_name=None, index_type='json', partitioned=None, **kwargs)¶ Creates either a JSON or a text query index in the remote database.
Parameters: - index_type (str) – The type of the index to create. Can be either ‘text’ or ‘json’. Defaults to ‘json’.
- design_document_id (str) – Optional identifier of the design document in which the index will be created. If omitted the default is that each index will be created in its own design document. Indexes can be grouped into design documents for efficiency. However, a change to one index in a design document will invalidate all other indexes in the same document.
- index_name (str) – Optional name of the index. If omitted, a name will be generated automatically.
- fields (list) – A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
‘sort syntax’. For example
fields=['name', {'age': 'desc'}]
will create an index on the ‘name’ field in ascending order and the ‘age’ field in descending order. For text indexes, the fields parameter is optional. If it is included then each field element in the fields list must be a single element dictionary where the key is the field name and the value is the field type. For examplefields=[{'name': 'string'}, {'age': 'number'}]
. Valid field types are'string'
,'number'
, and'boolean'
. - default_field (dict) – Optional parameter that specifies how the
$text
operator can be used with the index. Only valid when creating a text index. - selector (dict) – Optional parameter that can be used to limit the index to a specific set of documents that match a query. It uses the same syntax used for selectors in queries. Only valid when creating a text index.
Returns: An Index object representing the index created in the remote database
-
creds
¶ Retrieves a dictionary of useful authentication information that can be used to authenticate against this database.
Returns: Dictionary containing authentication information
-
custom_result
(**options)¶ Provides a context manager that can be used to customize the
_all_docs
behavior and wrap the output as aResult
.Parameters: - descending (bool) – Return documents in descending key order.
- endkey – Stop returning records at this specified key.
Not valid when used with
Result
key access and key slicing. - endkey_docid (str) – Stop returning records when the specified document id is reached.
- include_docs (bool) – Include the full content of the documents.
- inclusive_end (bool) – Include rows with the specified endkey.
- key – Return only documents that match the specified key.
Not valid when used with
Result
key access and key slicing. - keys (list) – Return only documents that match the specified keys.
Not valid when used with
Result
key access and key slicing. - page_size (int) – Sets the page size for result iteration.
- startkey – Return records starting with the specified key.
Not valid when used with
Result
key access and key slicing. - startkey_docid (str) – Return records starting with the specified document ID.
For example:
with database.custom_result(include_docs=True) as rslt: data = rslt[100: 200]
-
database_partition_url
(partition_key)¶ Get the URL of the database partition.
Parameters: partition_key (str) – Partition key. Returns: URL of the database partition. Return type: str
-
database_url
¶ Constructs and returns the database URL.
Returns: Database URL
-
delete
()¶ Deletes the current database from the remote instance.
-
delete_query_index
(design_document_id, index_type, index_name)¶ Deletes the query index identified by the design document id, index type and index name from the remote database.
Parameters:
-
design_documents
()¶ Retrieve the JSON content for all design documents in this database. Performs a remote call to retrieve the content.
Returns: All design documents found in this database in JSON format
-
doc_count
()¶ Retrieves the number of documents in the remote database
Returns: Database document count
-
exists
()¶ Performs an existence check on the remote database.
Returns: Boolean True if the database exists, False otherwise
-
get
(key, remote=False)¶ Overrides dict’s get method. This gets an item from the database or cache like __getitem__, but instead of throwing an exception if the item is not found, it simply returns None.
Parameters: remote (bool) – Dictates whether a remote request is made to retrieve the doc, if it is not present in the local cache. Defaults to False.
-
get_design_document
(ddoc_id)¶ Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a “shell” DesignDocument object is returned.
Parameters: ddoc_id (str) – Design document id Returns: A DesignDocument instance, if exists remotely then it will be populated accordingly
-
get_list_function_result
(ddoc_id, list_name, view_name, **kwargs)¶ Retrieves a customized MapReduce view result from the specified database based on the list function provided. List functions are used, for example, when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML.
Note: All query parameters for View requests are supported. See
get_view_result
for all supported query parameters.For example:
# Assuming that 'view001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve documents where the list function is 'list1' resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10) for row in resp['rows']: # Process data (in text format).
For more detail on list functions, refer to the Cloudant list documentation.
Parameters: Returns: Formatted view result data in text format
-
get_partitioned_query_result
(partition_key, selector, fields=None, raw_result=False, **kwargs)¶ Retrieves the partitioned query result from the specified database based on the query parameters provided.
See
get_query_result()
method for further details.Parameters: - partition_key (str) – Partition key.
- selector (str) – Dictionary object describing criteria used to select documents.
- fields (list) – A list of fields to be returned by the query.
- raw_result (bool) – Dictates whether the query result is returned wrapped in a QueryResult or if the response JSON is returned. Defaults to False.
- kwargs – See
get_query_result()
method for available keyword arguments.
Returns: The result content either wrapped in a QueryResult or as the raw response JSON content.
Return type:
-
get_partitioned_view_result
(partition_key, ddoc_id, view_name, raw_result=False, **kwargs)¶ Retrieves the partitioned view result based on the design document and view name.
See
get_view_result()
method for further details.Parameters: - partition_key (str) – Partition key.
- ddoc_id (str) – Design document id used to get result.
- view_name (str) – Name of the view used to get result.
- raw_result (bool) – Dictates whether the view result is returned as a default Result object or a raw JSON response. Defaults to False.
- kwargs – See
get_view_result()
method for available keyword arguments.
Returns: The result content either wrapped in a QueryResult or as the raw response JSON content.
Return type:
-
get_query_indexes
(raw_result=False)¶ Retrieves query indexes from the remote database.
Parameters: raw_result (bool) – If set to True then the raw JSON content for the request is returned. Default is to return a list containing Index
,TextIndex
, andSpecialIndex
wrapped objects.Returns: The query indexes in the database
-
get_query_result
(selector, fields=None, raw_result=False, **kwargs)¶ Retrieves the query result from the specified database based on the query parameters provided. By default the result is returned as a
QueryResult
which uses theskip
andlimit
query parameters internally to handle slicing and iteration through the query result collection. Thereforeskip
andlimit
cannot be used as arguments to get the query result whenraw_result=False
. However, by settingraw_result=True
, the result will be returned as the raw JSON response content for the query requested. Using this setting requires the developer to manage their own slicing and iteration. Thereforeskip
andlimit
are valid arguments in this instance.For example:
# Retrieve documents where the name field is 'foo' selector = {'name': {'$eq': 'foo'}} docs = db.get_query_result(selector) for doc in docs: print doc # Retrieve documents sorted by the age field in ascending order docs = db.get_query_result(selector, sort=['name']) for doc in docs: print doc # Retrieve JSON response content, limiting response to 100 documents resp = db.get_query_result(selector, raw_result=True, limit=100) for doc in resp['docs']: print doc
For more detail on slicing and iteration, refer to the
QueryResult
documentation.Parameters: - selector (dict) – Dictionary object describing criteria used to select documents.
- fields (list) – A list of fields to be returned by the query.
- raw_result (bool) – Dictates whether the query result is returned wrapped in a QueryResult or if the response JSON is returned. Defaults to False.
- bookmark (str) – A string that enables you to specify which page of results you require.
- limit (int) – Maximum number of results returned. Only valid if
used with
raw_result=True
. - page_size (int) – Sets the page size for result iteration. Default
is 100. Only valid with
raw_result=False
. - r (int) – Read quorum needed for the result. Each document is read from at least ‘r’ number of replicas before it is returned in the results.
- skip (int) – Skip the first ‘n’ results, where ‘n’ is the value
specified. Only valid if used with
raw_result=True
. - sort (list) – A list of fields to sort by. Optionally the list can
contain elements that are single member dictionary structures that
specify sort direction. For example
sort=['name', {'age': 'desc'}]
means to sort the query results by the “name” field in ascending order and the “age” field in descending order. - use_index (str) – Identifies a specific index for the query to run against, rather than using the Cloudant Query algorithm which finds what it believes to be the best index.
Returns: The result content either wrapped in a QueryResult or as the raw response JSON content
-
get_revision_limit
()¶ Retrieves the limit of historical revisions to store for any single document in the current remote database.
Returns: Revision limit value for the current remote database
-
get_security_document
()¶ Retrieves the database security document as a SecurityDocument object. The returned object is useful for viewing as well as updating the the database’s security document.
Returns: A SecurityDocument instance representing the database security document
-
get_show_function_result
(ddoc_id, show_name, doc_id)¶ Retrieves a formatted document from the specified database based on the show function provided. Show functions, for example, are used when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML.
For example:
# Assuming that 'view001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve a formatted 'doc001' document where the show function is 'show001' resp = db.get_show_function_result('ddoc001', 'show001', 'doc001') for row in resp['rows']: # Process data (in text format).
For more detail on show functions, refer to the Cloudant show documentation.
Parameters: Returns: Formatted document result data in text format
-
get_view_result
(ddoc_id, view_name, raw_result=False, **kwargs)¶ Retrieves the view result based on the design document and view name. By default the result is returned as a
Result
object which provides a key accessible, sliceable, and iterable interface to the result collection. Depending on how you are accessing, slicing or iterating through your result collection certain query parameters are not permitted. SeeResult
for additional details.However, by setting
raw_result=True
, the result will be returned as the raw JSON response content for the view requested. With this setting there are no restrictions on the query parameters used but it also means that the result collection key access, slicing, and iteration is the responsibility of the developer.For example:
# get Result based on a design document view result = db.get_view_result('_design/ddoc_id_001', 'view_001') # get a customized Result based on a design document view result = db.get_view_result('_design/ddoc_id_001', 'view_001', include_docs=True, reduce=False) # get raw response content based on a design document view result = db.get_view_result('_design/ddoc_id_001', 'view_001', raw_result=True) # get customized raw response content for a design document view db.get_view_result('_design/ddoc_id_001', 'view_001', raw_result=True, include_docs=True, skip=100, limit=100)
For more detail on key access, slicing and iteration, refer to the
Result
documentation.Parameters: - ddoc_id (str) – Design document id used to get result.
- view_name (str) – Name of the view used to get result.
- raw_result (bool) – Dictates whether the view result is returned as a default Result object or a raw JSON response. Defaults to False.
- descending (bool) – Return documents in descending key order.
- endkey – Stop returning records at this specified key.
Not valid when used with
Result
key access and key slicing. - endkey_docid (str) – Stop returning records when the specified document id is reached.
- group (bool) – Using the reduce function, group the results to a group or single row.
- group_level – Only applicable if the view uses complex keys: keys that are lists. Groups reduce results for the specified number of list fields.
- include_docs (bool) – Include the full content of the documents.
- inclusive_end (bool) – Include rows with the specified endkey.
- key – Return only documents that match the specified key.
Not valid when used with
Result
key access and key slicing. - keys (list) – Return only documents that match the specified keys.
Not valid when used with
Result
key access and key slicing. - limit (int) – Limit the number of returned documents to the
specified count. Not valid when used with
Result
iteration. - page_size (int) – Sets the page size for result iteration.
Only valid if used with
raw_result=False
. - reduce (bool) – True to use the reduce function, false otherwise.
- skip (int) – Skip this number of rows from the start.
Not valid when used with
Result
iteration. - stable (bool) – Whether or not the view results should be returned from a “stable” set of shards.
- stale (str) – Allow the results from a stale view to be used. This makes the request return immediately, even if the view has not been completely built yet. If this parameter is not given, a response is returned only after the view has been built. Note that this parameter is deprecated and the appropriate combination of stable and update should be used instead.
- startkey – Return records starting with the specified key.
Not valid when used with
Result
key access and key slicing. - startkey_docid (str) – Return records starting with the specified document ID.
- update (str) – Determine whether the view in question should be updated prior to or after responding to the user. Valid values are: false: return results before updating the view; true: Return results after updating the view; lazy: Return the view results without waiting for an update, but update them immediately after the request.
Returns: The result content either wrapped in a QueryResult or as the raw response JSON content
-
infinite_changes
(**kwargs)¶ Returns an infinite (perpetually refreshed)
_changes
feed iterator. If necessary, the iteration can be stopped by issuing a call to thestop()
method on the returned iterator object.For example:
# Iterate over an infinite _changes feed changes = db.infinite_changes() for change in changes: if some_condition: changes.stop() print(change)
Parameters: - conflicts (bool) – Can only be set if include_docs is True. Adds information about conflicts to each document. Default is False.
- descending (bool) – Changes appear in sequential order. Default is False.
- doc_ids (list) – To be used only when
filter
is set to_doc_ids
. Filters the feed so that only changes to the specified documents are sent. - filter (str) – Name of filter function from a design document to get updates. Default is no filter.
- heartbeat (int) – Time in milliseconds after which an empty line is sent if there have been no changes. Must be a positive number. Default is no heartbeat.
- include_docs (bool) – Include the document with the result. The
document will not be returned as a
Document
but instead will be returned as either formated JSON or as raw response content. Default is False. - since – Start the results from changes after the specified
sequence identifier. In other words, using since excludes from the
list all changes up to and including the specified sequence
identifier. If since is 0 (the default), or omitted, the request
returns all changes. If it is
now
, only changes made after the time of the request will be emitted. - style (str) – Specifies how many revisions are returned in the
changes array. The default,
main_only
, only returns the current “winning” revision;all_docs
returns all leaf revisions, including conflicts and deleted former conflicts. - timeout (int) – Number of milliseconds to wait for data before
terminating the response.
heartbeat
supersedestimeout
if both are supplied. - chunk_size (int) – The HTTP response stream chunk size. Defaults to 512.
Returns: Feed object that can be iterated over as a
_changes
feed.
-
keys
(remote=False)¶ Retrieves the list of document ids in the database. Default is to return only the locally cached document ids, specify remote=True to make a remote request to include all document ids from the remote database instance.
Parameters: remote (bool) – Dictates whether the list of locally cached document ids are returned or a remote request is made to include an up to date list of document ids from the server. Defaults to False. Returns: List of document ids
-
list_design_documents
()¶ Retrieves a list of design document names in this database. Performs a remote call to retrieve the content.
Returns: List of names for all design documents in this database
-
metadata
()¶ Retrieves the remote database metadata dictionary.
Returns: Dictionary containing database metadata details
-
missing_revisions
(doc_id, *revisions)¶ Returns a list of document revision values that do not exist in the current remote database for the specified document id and specified list of revision values.
Parameters: Returns: List of missing document revision values
-
new_document
()¶ Creates a new, empty document in the remote and locally cached database, auto-generating the _id.
Returns: Document instance corresponding to the new document in the database
-
partition_metadata
(partition_key)¶ Retrieves the metadata dictionary for the remote database partition.
Parameters: partition_key (str) – Partition key. Returns: Metadata dictionary for the database partition. Return type: dict
-
partitioned_all_docs
(partition_key, **kwargs)¶ Wraps the _all_docs primary index on the database partition, and returns the results by value.
See
all_docs()
method for further details.Parameters: - partition_key (str) – Partition key.
- kwargs – See
all_docs()
method for available keyword arguments.
Returns: Raw JSON response content from
_all_docs
endpoint.Return type:
-
r_session
¶ Returns the
r_session
from the client instance used by the database.Returns: Client r_session
-
revisions_diff
(doc_id, *revisions)¶ Returns the differences in the current remote database for the specified document id and specified list of revision values.
Parameters: Returns: The revision differences in JSON format
-
set_revision_limit
(limit)¶ Sets the limit of historical revisions to store for any single document in the current remote database.
Parameters: limit (int) – Number of revisions to store for any single document in the current remote database. Returns: Revision limit set operation status in JSON format
-
update_handler_result
(ddoc_id, handler_name, doc_id=None, data=None, **params)¶ Creates or updates a document from the specified database based on the update handler function provided. Update handlers are used, for example, to provide server-side modification timestamps, and document updates to individual fields without the latest revision. You can provide query parameters needed by the update handler function using the
params
argument.Create a document with a generated ID:
# Assuming that 'update001' update handler exists as part of the # 'ddoc001' design document in the remote database... # Execute 'update001' to create a new document resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John', 'message': 'hello'})
Create or update a document with the specified ID:
# Assuming that 'update001' update handler exists as part of the # 'ddoc001' design document in the remote database... # Execute 'update001' to update document 'doc001' in the database resp = db.update_handler_result('ddoc001', 'update001', 'doc001', data={'month': 'July'})
For more details, see the update handlers documentation.
Parameters: Returns: Result of update handler function in text format
-
view_cleanup
()¶ Removes view files that are not used by any design document in the remote database.
Returns: View cleanup status in JSON format