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
答案 0 :(得分:1)
一个很好但非常普遍的问题。
您可以通过多种方式实现这一目标。最经典的CouchDB方法是创建一个map-reduce视图(二级索引),键入您希望能够查询的字段,例如:
function (doc) {
if (doc && doc.surname) {
emit(doc.surname, 1);
}
}
您现在可以查询具有特定姓氏的所有文件:
curl 'https://ACCOUNT.cloudant.com/examples/_design/example/_view/by_surname?limit=100&reduce=false&include_docs=true&startkey="kruger"&endkey="kruger0"'
如果您希望能够查询字段组合,可以创建矢量值键:
function (doc) {
if (doc && doc.surname && doc.firstname) {
emit([doc.surname, doc.firstname], 1);
}
}
被查询为:
curl 'https://ACCOUNT.cloudant.com/examples/_design/example/_view/by_name?limit=100&reduce=false&include_docs=true&startkey=\["kruger", "stefan"\]&endkey=\["kruger","stefan0"\]'
如果您是Cloudant的新手,另一种查询方式是使用适当命名的Cloudant Query(a.k.a. Mango),这是一种基于json的声明性查询语言。
它有详细记录(https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html),但它的要点是类型的查询:
{
"selector": {
"year": {
"$gt": 2010
}
},
"fields": ["_id", "_rev", "year", "title"],
"sort": [{"year": "asc"}],
"limit": 10,
"skip": 0
}