Cloudant Fundamentals: Querying
Using the Cloudant Query library for simple questions (part 7 of 10)
In previous posts we’ve looked at adding and retrieving documents from a Cloudant database by their key fields — the _id
field. There's a good chance that you want your database to be able to do more, which is where querying comes in.
Making a query
A Cloudant Query allows questions to be asked of your Cloudant data, questions such as:
- get me all the documents where the
dob
field is less than1970-01-01
- get me all the documents where the
dob
field is less than1970-01-01
and theactor
field isMarlon Brando
- get the first fifty films starring Matthew Broderick in date order
- get the next 50 films matching the previous query
Queries are expressed as JSON documents such as:
The selector
object is the equivalent of the "WHERE" part of relational database query. It defines the values or ranges of fields that you are looking for. In this case, the $lt
("less than") operator is used to perform our first query (other operators are available).
To perform the query we simply POST the JSON to the /db/_find
endpoint:
The returned data will have the following form:
docs
is an array of matching documentsbookmark
unlocks access to the next page of matcheswarning
is cautioning us that we are performing a query that forces Cloudant to scan the whole database to answer. We can improve performance with an index, a feature we'll meet later.
More complex clauses
Our second query needs to use the $and
operator which is fed an array of clauses. The first clause is the same as our first query, and we add on a second clause to match by actor name.
Only documents matching all of the $and
clauses will make it to the result set.
Sorting
The third query adds a sort
attribute to the query object:
We can sort by one or more fields in ascending (asc) or descending (desc) order.
Next time
In the next post we’ll do all this again, but programmatically in Node.js and introduce the prospect of expressing our queries in SQL.