g_tech
g_tech

Reputation: 251

cloudant - getting all the docs which match specific conditions/fields

I am using Cloudant database and I would like to retrieve all the documents within the db that match specific fields. I mean - I'd want to get only those documents which have some fields with specific values that I put.

Could you please help me with an example of code I can test? Thanks in advance

Upvotes: 0

Views: 1022

Answers (1)

xpqz
xpqz

Reputation: 3737

A good, but quite general question.

You can achieve this in several ways. The most canonical CouchDB way would be to create a map-reduce view (secondary index) keyed on the field you wish to be able to query on, for example:

function (doc) {
    if (doc && doc.surname) {
        emit(doc.surname, 1);
    }
}

You can create such views using the Cloudant dashboard:Creating a view in the Cloudant dashboard

You can now query this for all documents with a particular surname:

curl 'https://ACCOUNT.cloudant.com/examples/_design/example/_view/by_surname?limit=100&reduce=false&include_docs=true&startkey="kruger"&endkey="kruger0"'

If you want to be able to query on a combination of fields, you can create a vector-valued key:

function (doc) {
    if (doc && doc.surname && doc.firstname) {
        emit([doc.surname, doc.firstname], 1);
    }
}

which is queried as this:

curl 'https://ACCOUNT.cloudant.com/examples/_design/example/_view/by_name?limit=100&reduce=false&include_docs=true&startkey=\["kruger", "stefan"\]&endkey=\["kruger","stefan0"\]'

If you're new to Cloudant, another way to query is by using the aptly named Cloudant Query (a.k.a. Mango), which is a json-based declarative query language.

It is well documented (https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html), but the gist of it is queries of the type:

{
"selector": {
    "year": {
        "$gt": 2010
    }
},
"fields": ["_id", "_rev", "year", "title"],
"sort": [{"year": "asc"}],
"limit": 10,
"skip": 0
}

Upvotes: 1

Related Questions