result

API module for interacting with result collections.

class cloudant.result.QueryResult(query, **options)

Bases: cloudant.result.Result

Provides a index key accessible, sliceable and iterable interface to query result collections by extending the Result class. A QueryResult object is constructed with a raw data callable reference to the Query __call__() callable, which is used to retrieve data. A QueryResult object can also use optional extra arguments for result customization and supports efficient, paged iteration over the result collection to avoid large result data from adversely affecting memory.

In Python, slicing returns by value, whereas iteration will yield elements of the sequence. This means that index key access and slicing will perform better for smaller data collections, whereas iteration will be more efficient for larger data collections.

For example:

# Key access:

# Access by index value:
query_result = QueryResult(query)
query_result[9]        # skip first 9 documents and get 10th

# Slice access:

# Access by index slices:
query_result = QueryResult(query)
query_result[100: 200] # get documents after the 100th and up to and including the 200th
query_result[ :200]    # get documents up to and including the 200th
query_result[100: ]    # get all documents after the 100th
query_result[: ]       # get all documents

# Iteration:

# Iterate over the entire result collection
query_result = QueryResult(query)
for doc in query_result:
    print doc

# Iterate over the result collection, with an overriding query sort
query_result = QueryResult(query, sort=[{'name': 'desc'}])
for doc in query_result:
    print doc

# Iterate over the entire result collection,
# explicitly setting the index and in batches of 1000.
query_result = QueryResult(query, use_index='my_index', page_size=1000)
for doc in query_result:
    print doc

Note: Only access by index value, slicing by index values and iteration are supported by QueryResult. Also, since QueryResult object iteration uses the skip and limit query parameters to handle its processing, skip and limit are not permitted to be part of the query callable or be included as part of the QueryResult customized parameters.

Parameters:
  • query – A reference to the query callable that returns the JSON content result to be wrapped.
  • bookmark (str) – A string that enables you to specify which page of results you require.
  • fields (list) – A list of fields to be returned by the query.
  • page_size (int) – Sets the page size for result iteration. Default is 100.
  • 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.
  • selector (dict) – Dictionary object describing criteria used to select documents.
  • 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.
__getitem__(arg)

Provides QueryResult index access and index slicing support.

An int argument will be interpreted as a skip and then a get of the next document. For example [100] means skip the first 100 documents and then get the next document.

An int slice argument will be interpreted as a skip:limit-skip style pair. For example [100: 200] means skip the first 100 documents then get up to and including the 200th document so that you get the range between the supplied slice values.

See QueryResult for more detailed index access and index slicing examples.

Parameters:arg – A single value representing a key or a pair of values representing a slice. The argument value(s) must be int.
Returns:Document data as a list in JSON format
class cloudant.result.Result(method_ref, **options)

Bases: object

Provides a key accessible, sliceable, and iterable interface to result collections. A Result object is constructed with a raw data callable reference such as the database API convenience method all_docs() or the View __call__() callable, used to retrieve data. A Result object can also use optional extra arguments for result customization and supports efficient, paged iteration over the result collection to avoid large result data from adversely affecting memory.

In Python, slicing returns by value, whereas iteration will yield elements of the sequence. This means that individual key access and slicing will perform better for smaller data collections, whereas iteration will be more efficient for larger data collections.

For example:

# Key access:

# Access by index value:
result = Result(callable)
result[9]                 # skip first 9 records and get 10th

# Access by key value:
result = Result(callable)
result['foo']             # get records matching 'foo'
result[ResultByKey(9)]    # get records matching 9

# Slice access:

# Access by index slices:
result = Result(callable)
result[100: 200]          # get records after the 100th and up to and including the 200th
result[: 200]             # get records up to and including the 200th
result[100: ]             # get all records after the 100th
result[: ]                # get all records

# Access by key slices:
result = Result(callable)
result['bar':'foo']       # get records between and including 'bar' and 'foo'
result['foo':]            # get records after and including 'foo'
result[:'foo']            # get records up to and including 'foo'

result[['foo', 10]:
       ['foo', 11]]       # Complex key access and slicing works the same as simple keys

result[ResultByKey(5):
       ResultByKey(10)]   # key slice access of integer keys

# Iteration:

# Iterate over the entire result collection
result = Result(callable)
for i in result:
    print i

# Iterate over the result collection between startkey and endkey
result = Result(callable, startkey='2013', endkey='2014')
for i in result:
    print i

# Iterate over the entire result collection in batches of 1000, including documents.
result = Result(callable, include_docs=True, page_size=1000)
for i in result:
    print i

Note: Since Result object key access, slicing, and iteration use query parameters behind the scenes to handle their processing, some query parameters are not permitted as part of a Result customization, depending on whether key access, slicing, or iteration is being performed.

Such as:

Access/Slicing by index value No restrictions
Access/Slicing by key value key, keys, startkey, endkey not permitted
Iteration limit, skip not permitted
Parameters:
  • method_ref (str) – A reference to the method or callable that returns the JSON content result to be wrapped as a Result.
  • descending (bool) – Return documents in descending key order.
  • endkey – Stop returning records at this specified key. Not valid when used with 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 JSON arrays. Groups reduce results for the specified number of array 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 key access and key slicing.
  • keys (list) – Return only documents that match the specified keys. Not valid when used with key access and key slicing.
  • limit (int) – Limit the number of returned documents to the specified count. Not valid when used with key iteration.
  • page_size (int) – Sets the page size for result iteration.
  • 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 key 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 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.
__getitem__(arg)

Provides Result key access and slicing support.

An int argument will be interpreted as a skip and then a get of the next record. For example [100] means skip the first 100 records and then get the next record.

A str, list or ResultByKey argument will be interpreted as a key and then get all records that match the given key. For example ['foo'] will get all records that match the key ‘foo’.

An int slice argument will be interpreted as a skip:limit-skip style pair. For example [100: 200] means skip the first 100 records then get up to and including the 200th record so that you get the range between the supplied slice values.

A slice argument that contains str, list, or ResultByKey will be interpreted as a startkey: endkey style pair. For example ['bar': 'foo'] means get the range of records where the keys are between and including ‘bar’ and ‘foo’.

See Result for more detailed key access and slicing examples.

Parameters:arg – A single value representing a key or a pair of values representing a slice. The argument value(s) can be int, str, list (in the case of complex keys), or ResultByKey.
Returns:Rows data as a list in JSON format
__iter__()

Provides iteration support, primarily for large data collections. The iterator uses the startkey, startkey_docid, and limit options to consume data in chunks controlled by the page_size option. It retrieves a batch of data from the result collection and then yields each element.

See Result for Result iteration examples.

Returns:Iterable data sequence
all()

Retrieve all results.

Specifying a limit parameter in the Result constructor will limit the number of documents returned. Be aware that the page_size parameter is not honoured.

Returns:results data as list in JSON format.
class cloudant.result.ResultByKey(value)

Bases: object

Provides a wrapper for a value used to retrieve records from a result collection based on an actual document key value. This comes in handy when the document key value is an int.

For example:

result = Result(callable)
result[ResultByKey(9)]   # gets records where the key matches 9
# as opposed to:
result[9]                # gets the 10th record of the result collection

:param value: A value representing a Result key.