GroupDocumentSource.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. "use strict";
  2. var DocumentSource = require("./DocumentSource"),
  3. Accumulators = require("../accumulators/"),
  4. Document = require("../Document"),
  5. Expression = require("../expressions/Expression"),
  6. ConstantExpression = require("../expressions/ConstantExpression"),
  7. FieldPathExpression = require("../expressions/FieldPathExpression"),
  8. Variables = require("../expressions/Variables"),
  9. VariablesIdGenerator = require("../expressions/VariablesIdGenerator"),
  10. VariablesParseState = require("../expressions/VariablesParseState"),
  11. async = require("async");
  12. /**
  13. * A class for grouping documents together
  14. *
  15. * @class GroupDocumentSource
  16. * @namespace mungedb-aggregate.pipeline.documentSources
  17. * @module mungedb-aggregate
  18. * @constructor
  19. * @param [expCtx] {ExpressionContext}
  20. **/
  21. var GroupDocumentSource = module.exports = function GroupDocumentSource(expCtx) {
  22. if (arguments.length > 1) throw new Error("up to one arg expected");
  23. expCtx = !expCtx ? {} : expCtx;
  24. base.call(this, expCtx);
  25. this.populated = false;
  26. this.doingMerge = false;
  27. this.spilled = false;
  28. this.extSortAllowed = expCtx.extSortAllowed && !expCtx.inRouter;
  29. this.accumulatorFactories = [];
  30. this.currentAccumulators = [];
  31. this.groups = {}; // GroupsType Value -> Accumulators[]
  32. this.groupsKeys = []; // This is to faciliate easier look up of groups
  33. this.variables = null;
  34. this.fieldNames = [];
  35. this.idFieldNames = [];
  36. this.expressions = [];
  37. this.idExpressions = [];
  38. this.currentGroupsKeysIndex = 0;
  39. }, klass = GroupDocumentSource, base = DocumentSource, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  40. // TODO: Do we need this?
  41. klass.groupOps = {
  42. "$addToSet": Accumulators.AddToSet,
  43. "$avg": Accumulators.Avg,
  44. "$first": Accumulators.First,
  45. "$last": Accumulators.Last,
  46. "$max": Accumulators.MinMax.createMax, // $min and $max have special constructors because they share base features
  47. "$min": Accumulators.MinMax.createMin,
  48. "$push": Accumulators.Push,
  49. "$sum": Accumulators.Sum
  50. };
  51. klass.groupName = "$group";
  52. /**
  53. * Factory for making GroupDocumentSources
  54. *
  55. * @method create
  56. * @static
  57. * @param [expCtx] {ExpressionContext}
  58. **/
  59. klass.create = function create(expCtx) {
  60. return new GroupDocumentSource(expCtx);
  61. };
  62. /**
  63. * Factory for making GroupDocumentSources
  64. *
  65. * @method getSourceName
  66. * @return {GroupDocumentSource}
  67. **/
  68. proto.getSourceName = function getSourceName() {
  69. return klass.groupName;
  70. };
  71. /**
  72. * Gets the next document or DocumentSource.EOF if none
  73. *
  74. * @method getNext
  75. * @return {Object}
  76. **/
  77. proto.getNext = function getNext(callback) {
  78. if (!callback) throw new Error(this.getSourceName() + ' #getNext() requires callback.');
  79. if (this.expCtx.checkForInterrupt && this.expCtx.checkForInterrupt() === false)
  80. return callback(new Error("Interrupted"));
  81. var self = this;
  82. async.series([
  83. function(next) {
  84. if (!self.populated)
  85. self.populate(function(err) {
  86. return next(err);
  87. });
  88. else
  89. return next();
  90. },
  91. function(next) {
  92. // NOTE: Skipped the spilled functionality
  93. if (self.spilled) {
  94. throw new Error("Spilled is not implemented.");
  95. } else {
  96. if(self.currentGroupsKeysIndex === self.groupsKeys.length) {
  97. return next(null, DocumentSource.EOF);
  98. }
  99. var id = self.groupsKeys[self.currentGroupsKeysIndex],
  100. accumulators = self.groups[id],
  101. out = self.makeDocument(JSON.parse(id), accumulators, self.expCtx.inShard);
  102. if(++self.currentGroupsKeysIndex === self.groupsKeys.length) {
  103. self.dispose();
  104. }
  105. return next(null, out);
  106. }
  107. }
  108. ], function(err, results) {
  109. callback(err, results[1]);
  110. });
  111. };
  112. /**
  113. * Sets this source as apparently empty
  114. *
  115. * @method dispose
  116. **/
  117. proto.dispose = function dispose() {
  118. //NOTE: Skipped 'freeing' our resources; at best we could remove some references to things, but our parent will probably forget us anyways!
  119. // make us look done
  120. this.currentGroupsKeysIndex = this.groupsKeys.length;
  121. // free our source's resources
  122. this.source.dispose();
  123. };
  124. /**
  125. * Optimizes the expressions in the group
  126. * @method optimize
  127. **/
  128. proto.optimize = function optimize() {
  129. // TODO if all _idExpressions are ExpressionConstants after optimization, then we know there
  130. // will only be one group. We should take advantage of that to avoid going through the hash
  131. // table.
  132. var self = this;
  133. self.idExpressions.forEach(function(expression, i) {
  134. self.idExpressions[i] = expression.optimize();
  135. });
  136. self.expressions.forEach(function(expression, i) {
  137. self.expressions[i] = expression.optimize();
  138. });
  139. };
  140. /**
  141. * Create an object that represents the document source. The object
  142. * will have a single field whose name is the source's name.
  143. *
  144. * @method serialize
  145. * @param explain {Boolean} Create explain output
  146. **/
  147. proto.serialize = function serialize(explain) {
  148. var self = this,
  149. insides = {};
  150. // add the _id
  151. if (self.idFieldNames.length === 0) {
  152. if (self.idExpressions.length !== 1) throw new Error("Should only have one _id field");
  153. insides._id = self.idExpressions[0].serialize(explain);
  154. } else {
  155. if (self.idExpressions.length !== self.idFieldNames.length)
  156. throw new Error("Should have the same number of idExpressions and idFieldNames.");
  157. var md = {};
  158. self.idExpressions.forEach(function(expression, i) {
  159. md[self.idFieldNames[i]] = expression.serialize(explain);
  160. });
  161. insides._id = md;
  162. }
  163. //add the remaining fields
  164. var aFacs = self.accumulatorFactories,
  165. aFacLen = aFacs.length;
  166. for(var i=0; i < aFacLen; i++) {
  167. var aFac = new aFacs[i](),
  168. serialExpression = self.expressions[i].serialize(explain), //Get the accumulator's expression
  169. serialAccumulator = {}; //Where we'll put the expression
  170. serialAccumulator[aFac.getOpName()] = serialExpression;
  171. insides[self.fieldNames[i]] = serialAccumulator;
  172. }
  173. var serialSource = {};
  174. serialSource[self.getSourceName()] = insides;
  175. return serialSource;
  176. };
  177. /**
  178. * Creates a GroupDocumentSource from the given elem
  179. *
  180. * @method createFromJson
  181. * @param elem {Object} The group specification object; the right hand side of the $group
  182. **/
  183. klass.createFromJson = function createFromJson(elem, expCtx) {
  184. if (!(elem instanceof Object && elem.constructor === Object)) throw new Error("a group's fields must be specified in an object");
  185. var group = GroupDocumentSource.create(expCtx),
  186. idSet = false;
  187. var groupObj = elem,
  188. idGenerator = new VariablesIdGenerator(),
  189. vps = new VariablesParseState(idGenerator);
  190. for (var groupFieldName in groupObj) {
  191. if (groupObj.hasOwnProperty(groupFieldName)) {
  192. var groupField = groupObj[groupFieldName];
  193. if (groupFieldName === "_id") {
  194. if(idSet) throw new Error("15948 a group's _id may only be specified once");
  195. group.parseIdExpression(groupField, vps);
  196. idSet = true;
  197. } else if (groupFieldName === '$doingMerge' && groupField) {
  198. throw new Error("17030 $doingMerge should be true if present");
  199. } else {
  200. /*
  201. Treat as a projection field with the additional ability to
  202. add aggregation operators.
  203. */
  204. if (groupFieldName.indexOf(".") !== -1) throw new Error("16414 the group aggregate field name '" + groupFieldName + "' cannot contain '.'");
  205. if (groupFieldName[0] === "$") throw new Error("15950 the group aggregate field name '" + groupFieldName + "' cannot be an operator name");
  206. if (group._getTypeStr(groupFieldName) === "Object") throw new Error("15951 the group aggregate field '" + groupFieldName + "' must be defined as an expression inside an object");
  207. var subElementCount = 0;
  208. for (var subElementName in groupField) {
  209. if (groupField.hasOwnProperty(subElementName)) {
  210. var subElement = groupField[subElementName],
  211. op = klass.groupOps[subElementName];
  212. if (!op) throw new Error("15952 unknown group operator '" + subElementName + "'");
  213. var groupExpression,
  214. subElementTypeStr = group._getTypeStr(subElement);
  215. if (subElementTypeStr === "Object") {
  216. var subElementObjCtx = new Expression.ObjectCtx({isDocumentOk:true});
  217. groupExpression = Expression.parseObject(subElement, subElementObjCtx, vps);
  218. } else if (subElementTypeStr === "Array") {
  219. throw new Error("15953 aggregating group operators are unary (" + subElementName + ")");
  220. } else { /* assume its an atomic single operand */
  221. groupExpression = Expression.parseOperand(subElement, vps);
  222. }
  223. group.addAccumulator(groupFieldName, op, groupExpression);
  224. ++subElementCount;
  225. }
  226. }
  227. if (subElementCount !== 1) throw new Error("15954 the computed aggregate '" + groupFieldName + "' must specify exactly one operator");
  228. }
  229. }
  230. }
  231. if (!idSet) throw new Error("15955 a group specification must include an _id");
  232. group.variables = new Variables(idGenerator.getIdCount());
  233. return group;
  234. };
  235. /**
  236. * Populates the GroupDocumentSource by grouping all of the input documents at once.
  237. *
  238. * @method populate
  239. * @param callback {Function} Required. callback(err) when done populating.
  240. * @async
  241. **/
  242. proto.populate = function populate(callback) {
  243. var numAccumulators = this.accumulatorFactories.length;
  244. // NOTE: this is not in mongo, does it belong here?
  245. if(numAccumulators !== this.expressions.length) {
  246. callback(new Error("Must have equal number of accumulators and expressions"));
  247. }
  248. var input,
  249. self = this;
  250. async.whilst(
  251. function() {
  252. return input !== DocumentSource.EOF;
  253. },
  254. function(cb) {
  255. self.source.getNext(function(err, doc) {
  256. if(err) return cb(err);
  257. if(doc === DocumentSource.EOF) {
  258. input = doc;
  259. return cb(); //Need to stop now, no new input
  260. }
  261. input = doc;
  262. self.variables.setRoot(input);
  263. /* get the _id value */
  264. var id = self.computeId(self.variables);
  265. if(undefined === id) id = null;
  266. var groupKey = JSON.stringify(id),
  267. group = self.groups[groupKey];
  268. if(!group) {
  269. self.groupsKeys.push(groupKey);
  270. group = [];
  271. self.groups[groupKey] = group;
  272. // Add the accumulators
  273. for(var afi = 0; afi<self.accumulatorFactories.length; afi++) {
  274. group.push(new self.accumulatorFactories[afi]());
  275. }
  276. }
  277. //NOTE: Skipped memory usage stuff for case when group already existed
  278. if(numAccumulators !== group.length) {
  279. throw new Error('Group must have one of each accumulator');
  280. }
  281. //NOTE: passing the input to each accumulator
  282. for(var gi=0; gi<group.length; gi++) {
  283. group[gi].process(self.expressions[gi].evaluate(self.variables, self.doingMerge));
  284. }
  285. // We are done with the ROOT document so release it.
  286. self.variables.clearRoot();
  287. //NOTE: Skipped the part about sorted files
  288. return cb();
  289. });
  290. },
  291. function(err) {
  292. if(err) return callback(err);
  293. self.populated = true;
  294. return callback();
  295. }
  296. );
  297. };
  298. /**
  299. * Get the dependencies of the group
  300. *
  301. * @method getDependencies
  302. * @param deps {Object} The
  303. * @return {DocumentSource.getDepsReturn} An enum value specifying that these dependencies are exhaustive
  304. * @async
  305. **/
  306. proto.getDependencies = function getDependencies(deps) {
  307. var self = this;
  308. // add _id
  309. this.idExpressions.forEach(function(expression, i) {
  310. expression.addDependencies(deps);
  311. });
  312. // add the rest
  313. this.fieldNames.forEach(function (field, i) {
  314. self.expressions[i].addDependencies(deps);
  315. });
  316. return DocumentSource.GetDepsReturn.EXHAUSTIVE;
  317. };
  318. /**
  319. * Called internally only. Adds an accumulator for each matching group.
  320. *
  321. * @method addAccumulator
  322. * @param fieldName {String} The name of the field where the accumulated value will be placed
  323. * @param accumulatorFactory {Accumulator} The constructor for creating accumulators
  324. * @param epxression {Expression} The expression to be evaluated on incoming documents before they are accumulated
  325. **/
  326. proto.addAccumulator = function addAccumulator(fieldName, accumulatorFactory, expression) {
  327. this.fieldNames.push(fieldName);
  328. this.accumulatorFactories.push(accumulatorFactory);
  329. this.expressions.push(expression);
  330. };
  331. /**
  332. * Makes a document with the given id and accumulators
  333. *
  334. * @method makeDocument
  335. * @param fieldName {String} The name of the field where the accumulated value will be placed
  336. * @param accums {Array} An array of accumulators
  337. * @param epxression {Expression} The expression to be evaluated on incoming documents before they are accumulated
  338. **/
  339. proto.makeDocument = function makeDocument(id, accums, mergeableOutput) {
  340. var out = {};
  341. /* add the _id field */
  342. out._id = this.expandId(id);
  343. /* add the rest of the fields */
  344. this.fieldNames.forEach(function(fieldName, i) {
  345. var val = accums[i].getValue(mergeableOutput);
  346. if (!val) {
  347. out[fieldName] = null;
  348. } else {
  349. out[fieldName] = val;
  350. }
  351. });
  352. return out;
  353. };
  354. /**
  355. * Computes the internal representation of the group key.
  356. */
  357. proto.computeId = function computeId(vars) {
  358. var self = this;
  359. // If only one expression return result directly
  360. if (self.idExpressions.length === 1)
  361. return self.idExpressions[0].evaluate(vars); // NOTE: self will probably need to be async soon
  362. // Multiple expressions get results wrapped in an array
  363. var vals = [];
  364. self.idExpressions.forEach(function(expression, i) {
  365. vals.push(expression.evaluate(vars));
  366. });
  367. return vals;
  368. };
  369. /**
  370. * Converts the internal representation of the group key to the _id shape specified by the
  371. * user.
  372. */
  373. proto.expandId = function expandId(val) {
  374. var self = this;
  375. // _id doesn't get wrapped in a document
  376. if (self.idFieldNames.length === 0)
  377. return val;
  378. var doc = {};
  379. // _id is a single-field document containing val
  380. if (self.idFieldNames.length === 1) {
  381. doc[self.idFieldNames[0]] = val;
  382. return doc;
  383. }
  384. // _id is a multi-field document containing the elements of val
  385. val.forEach(function(v, i) {
  386. doc[self.idFieldNames[i]] = v;
  387. });
  388. return doc;
  389. };
  390. proto.parseIdExpression = function parseIdExpression(groupField, vps) {
  391. var self = this;
  392. if (self._getTypeStr(groupField) === 'Object' && Object.keys(groupField).length !== 0) {
  393. // {_id: {}} is treated as grouping on a constant, not an expression
  394. var idKeyObj = groupField;
  395. if (Object.keys(idKeyObj)[0][0] == '$') {
  396. var objCtx = new Expression.ObjectCtx({});
  397. self.idExpressions.push(Expression.parseObject(idKeyObj, objCtx, vps));
  398. } else {
  399. Object.keys(idKeyObj).forEach(function(key, i) {
  400. var field = {}; //idKeyObj[key];
  401. field[key] = idKeyObj[key];
  402. self.idFieldNames.push(key);
  403. self.idExpressions.push(Expression.parseOperand(field[key], vps));
  404. });
  405. }
  406. } else if (self._getTypeStr(groupField) === 'string' && groupField[0] === '$') {
  407. self.idExpressions.push(FieldPathExpression.parse(groupField, vps));
  408. } else {
  409. self.idExpressions.push(ConstantExpression.create(groupField));
  410. }
  411. };
  412. /**
  413. * Get the type of something. Handles objects specially to return their true type; i.e. their constructor
  414. *
  415. * @method _getTypeStr
  416. * @param obj {Object} The object to get the type of
  417. * @return {String} The type of the object as a string
  418. * @async
  419. **/
  420. proto._getTypeStr = function _getTypeStr(obj) {
  421. var typeofStr = typeof obj,
  422. typeStr = (typeofStr == "object" && obj !== null) ? obj.constructor.name : typeofStr;
  423. return typeStr;
  424. };