I have this document in couchdb, I wish to write a view which can emit key combination of original "_id" and the id within "Body" with the value as the body itself.
basically if "doc" is the json:
key [ _id, "key in Body" ]
value [ doc['_id']['Body'][key in Body]
json Document
CouchDB has a detailed guide to views.
A views map function can emit multiple key-value pairs per document, so in your case you would emit each doc.Body entry.
function(doc) {
if (doc.Body) {
// get an array of own property names in doc.Body
var bodies = Object.keys(doc.Body);
// loop over all the Body entries
bodies.forEach(function (body) {
// emit key-value for each entry
emit([doc._id, body], bodies[body].body);
});
}
}
To get all bodies from doc._id = "123":
http://my.couch.host/my-db/_design/docname/_view/viewname?startkey=["123"]&endkey=["123",{}]
To get the body of doc.Body.abc from doc._id = "123":
http://my.couch.host/my-db/_design/docname/_view/viewname?startkey=["123","abc"]&endkey=["123","abc"]
See views collation and complex keys for more information.
Related
I am trying to do a "keys-only query" with Google Datastore API for Node.js, as exemplified in the documentation here.
I do that after having saved a number of records like this:
datastore.save(
records.map(
(record) => {
return {
key: datastore.key([kind, record.id]),
data: record,
};
}
)
The constant kind is a string. Each record has a valid unique id property (a number), which, as shown here, should also serve as the datastore key identifier.
The records are stored correctly. I can retrieve them all without problems through
datastore.runQuery(datastore.createQuery(kind))
.then( (results) => {
// whatever...
}
All the saved records are returned correctly.
But when I do a "keys-only query" like this (and as exemplified in the documentation):
const query = datastore.createQuery(kind)
.select('__key__');
datastore.runQuery(query)
.then( (results) => {
// whatever...
}
my results[0] return value is simply an array of empty objects like this:
results[0]: [ {}, {}, {}, {}, {}, ..., {}]
The number of empty objects returned here is the correct number of records of the given kind. But the problem is that they are empty objects. I expected to get the datastore key for each record here.
If, on the other hand, I do a "normal" projection query, on a "normal" property (like "id" - which should be identical with the datastore key, as far as I understand, after having defined the key through datastore.key[kind, record.id]), I retrieve the projected "id" properties correctly thus:
const query = datastore.createQuery(kind)
.select('id');
datastore.runQuery(query)
.then( (results) => {
// whatever...
}
Result:
results[0]: [
{ id: 5289385927 },
{ id: 5483575687 },
{ id: 5540575111 },
{ id: 5540622279 },
// ... and so on
]
So what is wrong with my "keys-only-query"? I have done it exactly in the way the documentation describes. But I get only empty results.
NOTE: I have tested this only in Datastore emulator. Same result in Datastore Emulator as in AppEngine.
The objects are not empty but contain only datastore keys, which are stored under a symbol property: datastore.KEY. In javascript, symbol properties might not output by default.
You can get entity key using symbol datastore.KEY
var keys = results.map(function(res) {
return res[datastore.KEY];
});
I'm building an API using node express and mongodb, with mongoose.
I have a post resource that handles user posts, and would like to be able to perform various queries on the post resource.
For instance I have a functions as that returns all posts as follows:
// Gets a list of Posts
exports.index = function(req, res) {
console.log(req.query);
Post.findAsync()
.then(mUtil.responseWithResult(res))
.catch(mUtil.handleError(res));
};
I looking for a good way of processing any additional query params that might come with the request.
/posts will return all posts, but /posts?user=12 will return posts by user with id 12 and /posts?likes=12 will return posts with 12 or more likes.
How can I check for and apply the these query params to filter and return the results since they may or may not be present.
Thanks ;)
If user=12 means "users with id 12", how does likes=12 mean "likes greater than 12"? You need to be more descriptive with your queries. You can do that by passing an array of objects. Send your query in a way that can be interpreted like this:
var filters = [
{
param: "likes",
type: "greater"
value: 12
},
{
param: "user",
type: "equal",
value: "12"
}]
var query = Post.find();
filters.forEach(function(filter) {
if (filter.type === "equal") {
query.where(filter.param).equals(filter.value);
}
else if (filter.type === "greater") {
query.where(filter.param).gt(filter.value);
}
// etc,,,
})
query.exec(callback);
"myview": {
"map": "function(doc) {if(doc.type == 'call') {emit([doc.from_user, doc.to_user], doc.type);} }",
"reduce": "function (key, values) {return values;}"
}
POST request with group = true
{
"keys":[["123456"], ["123456"]]
}
How can I get unique doc based on value exists in either in from_user or to_user?
Emit the values of doc.from_user and doc.to_user as single keys.
e.g.
emit(doc.from_user, doc.type);
emit(doc.to_user, doc.type);
Every row of the view result includes the doc._id and you can also get the doc in the view result by using the query param include_docs=true.
Finally you request your view with the query param ?key="your_value" and you will get every row with that value as key.
If you want to know whether the value is from doc.from_user or doc.to_user just emit that information as part of the value or build as multi key like
emit([doc.from_user, 'from_user'], doc.type);
emit([doc.to_user, 'to_user'], doc.type);
Then you can request
?startkey=["your_value","from_user"]&endkey=["your_value","to_user"]
I need to create a view that lists the values for an attribute of a doc field.
Sample Doc:
{
"_id": "003e5a9742e04ce7a6791aa845405c17",
"title", "testdoc",
"samples": [
{
"confidence": "high",
"handle": "joetest"
}
]
}
Example using that doc, I want a view that will return the values for "handle"
I found this example with the heading - Get contents of an object with specific attributes e.g. doc.objects.[0].attribute. But when I fill in the attribute name, e.g. "handle" and replace doc.objects with doc.samples, I get no results:
Toggle line numbers
// map
function(doc) {
for (var idx in doc.objects) {
emit(doc.objects[idx], attribute)
}
}
That will create an array of key-value-pairs where the key is alway the value of handle. Replace null with a value you want e.g. doc.title. If you want to get the doc attached to every row use the query parameter ?include_docs=true while requesting the view.
// map
function (doc) {
var samples = doc.samples
for(var i = 0, sample; sample = samples[i++];) {
emit(sample.handle, null)
}
}
Like this ->
function(doc) {
for (var i in doc.samples) {
emit(doc._id, doc.samples[i].handle)
}
}
It will produce a result based on the doc._id field as the key. Or, if you want your key to be based on the .handle field you reverse the parameters in emit so you can search by startKey=, endKey=.
I am looking for a CouchDB equivalent to "SQL joins".
In my example there are CouchDB documents that are list elements:
{ "type" : "el", "id" : "1", "content" : "first" }
{ "type" : "el", "id" : "2", "content" : "second" }
{ "type" : "el", "id" : "3", "content" : "third" }
There is one document that defines the list:
{ "type" : "list", "elements" : ["2","1"] , "id" : "abc123" }
As you can see the third element was deleted, it is no longer part of the list. So it must not be part of the result. Now I want a view that returns the content elements including the right order.
The result could be:
{ "content" : ["second", "first"] }
In this case the order of the elements is already as it should be. Another possible result:
{ "content" : [{"content" : "first", "order" : 2},{"content" : "second", "order" : 1}] }
I started writing the map function:
map = function (doc) {
if (doc.type === 'el') {
emit(doc.id, {"content" : doc.content}); //emit the id and the content
exit;
}
if (doc.type === 'list') {
for ( var i=0, l=doc.elements.length; i<l; ++i ){
emit(doc.elements[i], { "order" : i }); //emit the id and the order
}
}
}
This is as far as I can get. Can you correct my mistakes and write a reduce function? Remember that the third document must not be part of the result.
Of course you can write a different map function also. But the structure of the documents (one definig element document and an entry document for each entry) cannot be changed.
EDIT: Do not miss JasonSmith's comment to his answer, where he describes how to do this shorter.
Thank you! This is a great example to show off CouchDB 0.11's new
features!
You must use the fetch-related-data feature to reference documents
in the view. Optionally, for more convenient JSON, use a _list function to
clean up the results. See Couchio's writeup on "JOIN"s for details.
Here is the plan:
Firstly, you have a uniqueness contstraint on your el documents. If two of
them have id=2, that's a problem. It is necessary to use
the _id field instead if id. CouchDB will guarantee uniqueness, but also,
the rest of this plan requires _id in order to fetch documents by ID.
{ "type" : "el", "_id" : "1", "content" : "first" }
{ "type" : "el", "_id" : "2", "content" : "second" }
{ "type" : "el", "_id" : "3", "content" : "third" }
If changing the documents to use _id is absolutely impossible, you can
create a simple view to emit(doc.id, doc) and then re-insert that into a
temporary database. This converts id to _id but adds some complexity.
The view emits {"_id": content_id} data keyed on
[list_id, sort_number], to "clump" the lists with their content.
function(doc) {
if(doc.type == 'list') {
for (var i in doc.elements) {
// Link to the el document's id.
var id = doc.elements[i];
emit([doc.id, i], {'_id': id});
}
}
}
Now there is a simple list of el documents, in the correct order. You can
use startkey and endkey if you want to see only a particular list.
curl localhost:5984/x/_design/myapp/_view/els
{"total_rows":2,"offset":0,"rows":[
{"id":"036f3614aeee05344cdfb66fa1002db6","key":["abc123","0"],"value":{"_id":"2"}},
{"id":"036f3614aeee05344cdfb66fa1002db6","key":["abc123","1"],"value":{"_id":"1"}}
]}
To get the el content, query with include_docs=true. Through the magic of
_id, the el documents will load.
curl localhost:5984/x/_design/myapp/_view/els?include_docs=true
{"total_rows":2,"offset":0,"rows":[
{"id":"036f3614aeee05344cdfb66fa1002db6","key":["abc123","0"],"value":{"_id":"2"},"doc":{"_id":"2","_rev":"1-4530dc6946d78f1e97f56568de5a85d9","type":"el","content":"second"}},
{"id":"036f3614aeee05344cdfb66fa1002db6","key":["abc123","1"],"value":{"_id":"1"},"doc":{"_id":"1","_rev":"1-852badd683f22ad4705ed9fcdea5b814","type":"el","content":"first"}}
]}
Notice, this is already all the information you need. If your client is
flexible, you can parse the information out of this JSON. The next optional
step simply reformats it to match what you need.
Use a _list function, which simply reformats the view output. People use them to output XML or HTML however we will make
the JSON more convenient.
function(head, req) {
var headers = {'Content-Type': 'application/json'};
var result;
if(req.query.include_docs != 'true') {
start({'code': 400, headers: headers});
result = {'error': 'I require include_docs=true'};
} else {
start({'headers': headers});
result = {'content': []};
while(row = getRow()) {
result.content.push(row.doc.content);
}
}
send(JSON.stringify(result));
}
The results match. Of course in production you will need startkey and endkey to specify the list you want.
curl -g 'localhost:5984/x/_design/myapp/_list/pretty/els?include_docs=true&startkey=["abc123",""]&endkey=["abc123",{}]'
{"content":["second","first"]}