RethinkDB grouping and defining output -
i have table contains documents similar this:
{ "title": "title 2", "content": "this far, no further!", "category": "fiction" }
this query i'm using:
r.table('posts').group('title').map(lambda item: {'items': item['title']} ).run())
this output:
{ "title 1" : [ { "items" : "title 1" }, { "items" : "title 1" } ], "title 2" : [ { "items" : "title 2" }, { "items" : "title 2" }, { "items" : "title 2" }, { "items" : "title 2" } ], "title 3" : [ { "items" : "title 3" } ] }
however output structure looks this:
{ "title 1" : { "item_count" : 3, "items" : [ { "items" : "title 1" }, { "items" : "title 1" }, { "items" : "title 1" } ] }, "title 2" : { "item_count" : 2, "items" : [ { "items" : "title 2" }, { "items" : "title 2" } ] }, "title 3" : { "item_count" : 1, "items" : [ { "items" : "title 3" } ] } }
how create query result.
in order that, need map
query after executing ungroup
in it.
first, output of first query looks incorrect. rethinkdb doesn't wouldn't return object/dictionary after map
operation, return array. output got query following:
[ { "group": "title 1" , "reduction": [ { "items": "title 1" } , { "items": "title 1" } ] } , { "group": "title 2" , "reduction": [ { "items": "title 2" } , { "items": "title 2" } ] } , ... ]
if want property called items
along count of how many items items
property has, can following:
// javascript r.table('posts') .group('title') .map(function (item) { return { items: item('title') } }) .ungroup() .map(function (row) { return { 'title': row('group'), 'items': row('reduction'), 'count': row('reduction').count() } })
the result of query following:
[ { "count": 2 , "items": [ { "items": "title 1" }, { "items": "title 1" } ], "title": "title 1" }, { "count": 2 , "items": [ { "items": "title 2" } , { "items": "title 2" } ] , "title": "title 2" }, ... ]
if want turn query object/dictionary can call post it's title, can turn array of posts object, using r.object
along r.args
. complete query this:
// javascript r.table('posts') .group('title') .map(function (item) { return { items: item('title') } }) .ungroup() .map(function (row) { return { 'title': row('group'), 'items': row('reduction'), 'count': row('reduction').count() } }) .do(function (rows) { return r.object(r.args(rows.concatmap(function (row) { return [row('title'), row]; }))); })
the result of query this:
{ "title 1": { "count": 2 , "items": [ { "items": "title 1" } , { "items": "title 1" } ] , "title": "title 1" } , "title 2": { "count": 2 , "items": [ { "items": "title 2" } , { "items": "title 2" } ] , "title": "title 2" } , ... }
Comments
Post a Comment