GroupDocumentSource.js 16 KB

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