The primary index is the fastest way to retrieve data from your database.
If you learn better by seeing a demonstration, watch these videos first:
Enhance this tutorial with live data from a sample database inside your Cloudant account.
The primary index is fast because it comes with every Cloudant database, which means you don't have to write any code before you can use it.
The primary index, often referred to as
_all_docs, returns an id, a key and a value for every document in the database. The id and key are the same (Cloudant makes an index keyed by doc id), while the value is the
_rev of the document.
_all_docs also reports on the total number of documents and any offset used to query the index.
Demo the Cloudant API right here. The server response (JSON) will appear directly below.
To demo the API here, replicate the sample database first.
All indexes are sorted by their key. The sort order is:
The full specification is documented in the CouchDB Wiki.
_all_docs request above returns all the documents in the database. That's fine for
this example database, but in a realistic scenario you'll probably want a more manageable result set. That's where API options come in.
limit parameter to keep your result set to a certain size. If you want to offset your result set (for example to
paginate through some rows) you can also pass in a
In this call, we
limit the result set to 2 rows and
skip the first 3 rows.
Use slicing to pull out row ranges from the index by using start and end keys in your query.
Here we are looking for animals with names that begin with letters greater than the
startkey up to and including the
If you don't want to include documents that match the end key, add the
inclusive_end parameter with a value of
View slicing with
endkey can be combined with
inclusive_end to further constrain your result set.
Cloudant's primary index automatically turns a document's
_id into its
key. If you want a document matching a single key, find it with the
include_docs=true when you want all of the contents of the document you're requesting (not just the id).
You can also query for a specific set of keys by POSTing a JSON array of keys to the view.
As we've seen, the
_all_docs index can be a very useful view into your database, especially if your application has a natural unique identifier that you can use for your documents.
As your data grows, you'll want to explore secondary indexes, which allow you to build additional indexes over your database, defined by efficient MapReduce views.
Find more videos in the Learning Center.