GroupDocumentSource.js 15 KB

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