GroupDocumentSource.js 15 KB

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