design_document

API module/class for interacting with a design document in a database.

class cloudant.design_document.DesignDocument(database, document_id=None, partitioned=False)

Bases: cloudant.document.Document

Encapsulates a specialized version of a Document. A DesignDocument object is instantiated with a reference to a database and provides an API to view management, index management, list and show functions, etc. When instantiating a DesignDocument or when setting the document id (_id) field, the value must start with _design/. If it does not, then _design/ will be prepended to the provided document id value.

Note: Currently only the view management and search index management API exists. Remaining design document functionality will be added later.

Parameters:
  • database – A database instance used by the DesignDocument. Can be either a CouchDatabase or CloudantDatabase instance.
  • document_id (str) – Optional document id. If provided and does not start with _design/, it will be prepended with _design/.
  • partitioned (bool) – Optional. Create as a partitioned design document. Defaults to False for both partitioned and non-partitioned databases.
add_list_function(list_name, list_func)

Appends a list function to the locally cached DesignDocument indexes dictionary.

Parameters:
  • list_name (str) – Name used to identify the list function.
  • list_func (str) – Javascript list function.
add_search_index(index_name, search_func, analyzer=None)

Appends a Cloudant search index to the locally cached DesignDocument indexes dictionary.

Parameters:
  • index_name (str) – Name used to identify the search index.
  • search_func (str) – Javascript search index function.
  • analyzer – Optional analyzer for this search index.
add_show_function(show_name, show_func)

Appends a show function to the locally cached DesignDocument shows dictionary.

Parameters:
  • show_name – Name used to identify the show function.
  • show_func – Javascript show function.
add_view(view_name, map_func, reduce_func=None, **kwargs)

Appends a MapReduce view to the locally cached DesignDocument View dictionary. To create a JSON query index use create_query_index() instead. A CloudantException is raised if an attempt to add a QueryIndexView (JSON query index) using this method is made.

Parameters:
  • view_name (str) – Name used to identify the View.
  • map_func (str) – Javascript map function.
  • reduce_func (str) – Optional Javascript reduce function.
delete_index(index_name)

Removes an existing index in the locally cached DesignDocument indexes dictionary.

Parameters:index_name (str) – Name used to identify the index.
delete_list_function(list_name)

Removes an existing list function in the locally cached DesignDocument lists dictionary.

Parameters:list_name (str) – Name used to identify the list.
delete_show_function(show_name)

Removes an existing show function in the locally cached DesignDocument shows dictionary.

Parameters:show_name – Name used to identify the list.
delete_view(view_name)

Removes an existing MapReduce view definition from the locally cached DesignDocument View dictionary. To delete a JSON query index use delete_query_index() instead. A CloudantException is raised if an attempt to delete a QueryIndexView (JSON query index) using this method is made.

Parameters:view_name (str) – Name used to identify the View.
document_partition_url(partition_key)

Retrieve the design document partition URL.

Parameters:partition_key (str) – Partition key.
Returns:Design document partition URL.
Return type:str
fetch()

Retrieves the remote design document content and populates the locally cached DesignDocument dictionary. View content is stored either as View or QueryIndexView objects which are extensions of the dict type. All other design document data are stored directly as dict types.

filters

Provides an accessor property to the filters dictionary in the locally cached DesignDocument. Filter functions enable you to add tests for filtering each of the objects included in the changes feed. If any of the function tests fail, the object is filtered from the feed. If the function returns a true result when applied to a change, the change remains in the feed.

Filter functions require two arguments: doc and req. The doc argument represents the document being tested for filtering. The req argument contains additional information about the HTTP request.

Filter function example:

# Add the filter function to ``filters`` and save the design document
ddoc = DesignDocument(self.db, '_design/ddoc001')
# Filter and remove documents that are not of ``type`` mail
ddoc['filters'] = {
    'filter001': 'function(doc, req){if (doc.type != 'mail'){return false;} '
                 'return true;} '
}
ddoc.save()

To execute filter functions on a changes feed, see the database API changes()

For more details, see the Filter functions documentation.

Returns:Dictionary containing filter function names and functions as key/value
get_index(index_name)

Retrieves a specific index from the locally cached DesignDocument indexes dictionary by name.

Parameters:index_name (str) – Name used to identify the index.
Returns:Index dictionary for the specified index name
get_list_function(list_name)

Retrieves a specific list function from the locally cached DesignDocument lists dictionary by name.

Parameters:list_name (str) – Name used to identify the list function.
Returns:String form of the specified list function
get_show_function(show_name)

Retrieves a specific show function from the locally cached DesignDocument shows dictionary by name.

Parameters:show_name (str) – Name used to identify the show function.
Returns:String form of the specified show function
get_view(view_name)

Retrieves a specific View from the locally cached DesignDocument by name.

Parameters:view_name (str) – Name used to identify the View.
Returns:View object for the specified view_name
indexes

Provides an accessor property to the indexes dictionary in the locally cached DesignDocument.

Returns:Dictionary containing index names and index objects as key/value
iterindexes()

Provides a way to iterate over the locally cached DesignDocument indexes dictionary.

For example:

for index_name, search_func in ddoc.iterindexes():
    # Perform search index processing
Returns:Iterable containing index name and associated index object
iterlists()

Provides a way to iterate over the locally cached DesignDocument lists dictionary.

Returns:Iterable containing list function name and associated list function
itershows()

Provides a way to iterate over the locally cached DesignDocument shows dictionary.

Returns:Iterable containing show function name and associated show function
iterviews()

Provides a way to iterate over the locally cached DesignDocument View dictionary.

For example:

for view_name, view in ddoc.iterviews():
    # Perform view processing
Returns:Iterable containing view name and associated View object
list_indexes()

Retrieves a list of available indexes in the locally cached DesignDocument.

Returns:List of index names
list_list_functions()

Retrieves a list of available list functions in the locally cached DesignDocument lists dictionary.

Returns:List of list function names
list_show_functions()

Retrieves a list of available show functions in the locally cached DesignDocument shows dictionary.

Returns:List of show function names
list_views()

Retrieves a list of available View objects in the locally cached DesignDocument.

Returns:List of view names
lists

Provides an accessor property to the lists dictionary in the locally cached DesignDocument.

Returns:Dictionary containing list names and objects as key/value
rewrites

Provides an accessor property to a list of dictionaries with rewrite rules in the locally cached DesignDocument. Each rule for URL rewriting is a JSON object with four fields: from, to, method, and query.

Note: Requests that match the rewrite rules must have a URL path that starts with /$DATABASE/_design/doc/_rewrite.

Rewrite rule example:

# Add the rule to ``rewrites`` and save the design document
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc['rewrites'] = [
    {"from": "/old/topic",
     "to": "/new/",
     "method": "GET",
     "query": {}
     }
]
ddoc.save()

Once the rewrite rule is saved to the remote database, the GET request URL /$DATABASE/_design/doc/_rewrite/old/topic?k=v would be rewritten as /$DATABASE/_design/doc/_rewrite/new?k=v.

For more details on URL rewriting, see the rewrite rules documentation.

Returns:List of dictionaries containing rewrite rules as key/value
save()

Saves changes made to the locally cached DesignDocument object’s data structures to the remote database. If the design document does not exist remotely then it is created in the remote database. If the object does exist remotely then the design document is updated remotely. In either case the locally cached DesignDocument object is also updated accordingly based on the successful response of the operation.

search_disk_size(search_index)

Retrieves disk size information about a specified search index within the design document, returns dictionary

GET databasename/_design/{ddoc}/_search_disk_size/{search_index}

search_info(search_index)

Retrieves information about a specified search index within the design document, returns dictionary

GET databasename/_design/{ddoc}/_search_info/{search_index}

shows

Provides an accessor property to the shows dictionary in the locally cached DesignDocument.

Returns:Dictionary containing show names and functions as key/value
st_indexes

Provides an accessor property to the Cloudant Geospatial (a.k.a. Cloudant Geo) indexes dictionary in the locally cached DesignDocument. Each Cloudant Geo index is a JSON object within the st_indexes containing an index name and a javascript function.

Note: To make it easier to work with Cloudant Geo documents, it is best practice to create a separate design document specifically for Cloudant Geo indexes.

Geospatial index example:

# Add the Cloudant Geo index to ``st_indexes`` and save the design document
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc['st_indexes'] = {
    'geoidx': {
        'index': 'function(doc) { '
                 'if (doc.geometry && doc.geometry.coordinates) { '
                 'st_index(doc.geometry);}} '
    }
}
ddoc.save()

Once the Cloudant Geo index is saved to the remote database, you can query the index with a GET request. To issue a request against the _geo endpoint, see the steps outlined in the endpoint access section.

For more details, see the Cloudant Geospatial documentation.

Returns:Dictionary containing Cloudant Geo names and index objects as key/value
update_list_function(list_name, list_func)

Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary.

Parameters:
  • list_name (str) – Name used to identify the list function.
  • list_func (str) – Javascript list function.
update_search_index(index_name, search_func, analyzer=None)

Modifies/overwrites an existing Cloudant search index in the locally cached DesignDocument indexes dictionary.

Parameters:
  • index_name (str) – Name used to identify the search index.
  • search_func (str) – Javascript search index function.
  • analyzer – Optional analyzer for this search index.
update_show_function(show_name, show_func)

Modifies/overwrites an existing show function in the locally cached DesignDocument shows dictionary.

Parameters:
  • show_name – Name used to identify the show function.
  • show_func – Javascript show function.
update_view(view_name, map_func, reduce_func=None, **kwargs)

Modifies/overwrites an existing MapReduce view definition in the locally cached DesignDocument View dictionary. To update a JSON query index use delete_query_index() followed by create_query_index() instead. A CloudantException is raised if an attempt to update a QueryIndexView (JSON query index) using this method is made.

Parameters:
  • view_name (str) – Name used to identify the View.
  • map_func (str) – Javascript map function.
  • reduce_func (str) – Optional Javascript reduce function.
updates

Provides an accessor property to the updates dictionary in the locally cached DesignDocument. Update handlers are custom functions stored on Cloudant’s server that will create or update a document. To execute the update handler function, see update_handler_result().

Update handlers receive two arguments: doc and req. If a document ID is provided in the request to the update handler, then doc will be the document corresponding with that ID. If no ID was provided, doc will be null.

Update handler example:

# Add the update handler to ``updates`` and save the design document
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc001['updates'] = {
    'update001': 'function(doc, req) { if (!doc) '
                 '{ if ('id' in req && req.id){ return [{_id: req.id}, '
                 '"New World"] } return [null, "Empty World"] } '
                 'doc.world = 'hello'; '
                 'return [doc, "Added world.hello!"]} '
}
ddoc.save()

Note: Update handler functions must return an array of two elements, the first being the document to save (or null, if you don’t want to save anything), and the second being the response body.

Returns:Dictionary containing update handler names and objects as key/value
validate_doc_update

Provides an accessor property to the update validators dictionary in the locally cached DesignDocument. Update validators evaluate whether a document should be written to disk when insertions and updates are attempted.

Update validator example:

# Add the update validator to ``validate_doc_update`` and save the design document
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc['validate_doc_update'] = (
    'function(newDoc, oldDoc, userCtx, secObj) { '
    'if (newDoc.address === undefined) { '
    'throw({forbidden: 'Document must have an address.'}); }}')
ddoc.save()

For more details, see the Update Validators documentation.

Returns:Dictionary containing update validator functions
views

Provides an accessor property to the View dictionary in the locally cached DesignDocument.

Returns:Dictionary containing view names and View objects as key/value