Skip to content

Node.js based forum software built for the modern web

refactor: add hint to force usage of zset indexes

Barış Soner Uşaklı687e1a5d2627
diff --git a/src/database/mongo/sets.js b/src/database/mongo/sets.js
index 32e81f37b1..8f79a520bd 100644
--- a/src/database/mongo/sets.js
+++ b/src/database/mongo/sets.js
@@ -129,6 +129,7 @@ module.exports = function (module) {
_key: key, members: value,
}, {
projection: { _id: 0, _key: 1 },
+ hint: { members: 1, _key: 1 },
});
return item !== null && item !== undefined;
@@ -161,7 +162,11 @@ module.exports = function (module) {
},
];
- const [doc] = await module.client.collection('objects').aggregate(pipeline).toArray();
+ const [doc] = await module.client.collection('objects')
+ .aggregate(
+ pipeline,
+ { hint: { members: 1, _key: 1 } }
+ ).toArray();
return doc ? doc.results : values.map(() => false);
};
@@ -175,6 +180,7 @@ module.exports = function (module) {
_key: { $in: sets }, members: value,
}, {
projection: { _id: 0, _key: 1 },
+ hint: { members: 1, _key: 1 },
}).toArray();
const foundMembers = new Set(result.map(item => item._key));
@@ -190,6 +196,7 @@ module.exports = function (module) {
_key: key,
}, {
projection: { _id: 0, members: 1 },
+ hint: { _key:1, score: -1 },
});
return data ? data.members : [];
};
@@ -202,6 +209,7 @@ module.exports = function (module) {
_key: { $in: keys },
}, {
projection: { _id: 0 },
+ hint: { _key: 1, score: -1 },
}).toArray();
const sets = Object.create(null);
@@ -219,7 +227,7 @@ module.exports = function (module) {
const data = await module.client.collection('objects').aggregate([
{ $match: { _key: key } },
{ $project: { _id: 0, count: { $size: '$members' } } },
- ]).toArray();
+ ], { hint: { _key: 1, score: -1 } }).toArray();
return Array.isArray(data) && data.length ? data[0].count : 0;
};
@@ -227,7 +235,7 @@ module.exports = function (module) {
const data = await module.client.collection('objects').aggregate([
{ $match: { _key: { $in: keys } } },
{ $project: { _id: 0, _key: 1, count: { $size: '$members' } } },
- ]).toArray();
+ ], { hint: { _key: 1, score: -1 } }).toArray();
const map = _.keyBy(data, '_key');
return keys.map(key => (map.hasOwnProperty(key) ? map[key].count : 0));
};
diff --git a/src/database/mongo/sorted.js b/src/database/mongo/sorted.js
index b5de27ef6b..dcf317e57a 100644
--- a/src/database/mongo/sorted.js
+++ b/src/database/mongo/sorted.js
@@ -9,6 +9,9 @@ module.exports = function (module) {
const util = require('util');
const sleep = util.promisify(setTimeout);
+ const hintKeyScore = { _key: 1, score: -1 };
+ const hintKeyValue = { _key: 1, value: -1 };
+
require('./sorted/add')(module);
require('./sorted/remove')(module);
require('./sorted/union')(module);
@@ -89,6 +92,7 @@ module.exports = function (module) {
.sort({ score: sort })
.skip(skip)
.limit(limit)
+ .hint(hintKeyScore)
.toArray();
}
@@ -156,14 +160,18 @@ module.exports = function (module) {
query.score.$lte = max;
}
- return await module.client.collection('objects').countDocuments(query);
+ return await module.client.collection('objects').countDocuments(query, {
+ hint: hintKeyScore,
+ });
};
module.sortedSetCard = async function (key) {
if (!key) {
return 0;
}
- return await module.client.collection('objects').countDocuments({ _key: key });
+ return await module.client.collection('objects').countDocuments({ _key: key }, {
+ hint: hintKeyScore,
+ });
};
module.sortedSetsCard = async function (keys) {
@@ -188,7 +196,9 @@ module.exports = function (module) {
query.score.$lte = max;
}
- return await module.client.collection('objects').countDocuments(query);
+ return await module.client.collection('objects').countDocuments(query, {
+ hint: hintKeyScore,
+ });
};
module.sortedSetRank = async function (key, value) {
@@ -273,7 +283,10 @@ module.exports = function (module) {
value = helpers.valueToString(value);
const result = await module.client.collection('objects').findOne(
{ _key: key, value: value },
- { projection: { _id: 0, _key: 0, value: 0 } }
+ {
+ projection: { _id: 0, _key: 0, value: 0 },
+ hint: hintKeyValue,
+ }
);
return result ? result.score : null;
};
@@ -285,7 +298,10 @@ module.exports = function (module) {
value = helpers.valueToString(value);
const result = await module.client.collection('objects').find(
{ _key: { $in: keys }, value: value },
- { projection: { _id: 0, value: 0 } }
+ {
+ projection: { _id: 0, value: 0 },
+ hint: hintKeyValue,
+ }
).toArray();
const scoreMap = Object.create(null);
result.forEach((item) => {
@@ -304,7 +320,10 @@ module.exports = function (module) {
values = values.map(helpers.valueToString);
const result = await module.client.collection('objects').find(
{ _key: key, value: { $in: values } },
- { projection: { _id: 0, _key: 0 } }
+ {
+ projection: { _id: 0, _key: 0 },
+ hint: hintKeyValue,
+ }
).toArray();
const valueToScore = Object.create(null);
@@ -324,6 +343,7 @@ module.exports = function (module) {
_key: key, value: value,
}, {
projection: { _id: 0, value: 1 },
+ hint: hintKeyValue,
});
return !!result;
};
@@ -340,6 +360,7 @@ module.exports = function (module) {
_key: key, value: { $in: values },
}, {
projection: { _id: 0, value: 1 },
+ hint: hintKeyValue,
}).toArray();
const foundMembers = new Set(results.map(item => item.value));
@@ -355,6 +376,7 @@ module.exports = function (module) {
_key: { $in: keys }, value: value,
}, {
projection: { _id: 0, _key: 1, value: 1 },
+ hint: hintKeyValue,
}).toArray();
const keysWithMember = new Set(results.map(item => item._key));
@@ -395,6 +417,7 @@ module.exports = function (module) {
_key: arrayOfKeys ? { $in: keys } : keys[0],
}, { projection: projection })
.sort({ score: 1 })
+ .hint(hintKeyScore)
.toArray();
if (!arrayOfKeys) {
@@ -434,6 +457,7 @@ module.exports = function (module) {
returnDocument: 'after',
includeResultMetadata: true,
upsert: true,
+ hint: hintKeyValue,
});
return result && result.value ? result.value.score : null;
} catch (err) {
@@ -456,17 +480,21 @@ module.exports = function (module) {
const aggregated = dbHelpers.aggregateIncrByBulk(data);
const findQuery = { $or: [] };
- const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
- aggregated.forEach(([key, incr, value]) => {
+ const operations = aggregated.map(([key, incr, value]) => {
const query = { _key: key, value: value };
findQuery.$or.push(query);
- bulk.find(query)
- .upsert()
- .update({ $inc: { score: parseFloat(incr) } });
+ return {
+ updateOne: {
+ filter: query,
+ update: { $inc: { score: parseFloat(incr) } },
+ upsert: true,
+ hint: hintKeyValue,
+ },
+ };
});
try {
- await bulk.execute();
+ await module.client.collection('objects').bulkWrite(operations);
} catch (err) {
// retry failed e11000 operations
if (err.code === 11000 || (err.writeErrors && err.writeErrors.some(e => e.code === 11000))) {
@@ -482,7 +510,10 @@ module.exports = function (module) {
const result = await module.client.collection('objects').find(
findQuery,
- { projection: { _id: 0, _key: 1, value: 1, score: 1 } },
+ {
+ projection: { _id: 0, _key: 1, value: 1, score: 1 },
+ hint: hintKeyValue,
+ },
).toArray();
const map = Object.create(null);
@@ -514,8 +545,10 @@ module.exports = function (module) {
count = count !== undefined ? count : 0;
buildLexQuery(query, min, max);
- const data = await module.client.collection('objects').find(query, { projection: { _id: 0, value: 1 } })
- .sort({ value: sort })
+ const data = await module.client.collection('objects').find(query, {
+ projection: { _id: 0, value: 1 },
+ hint: hintKeyValue,
+ }).sort({ value: sort })
.skip(start)
.limit(count === -1 ? 0 : count)
.toArray();
@@ -527,7 +560,9 @@ module.exports = function (module) {
const query = { _key: key };
buildLexQuery(query, min, max);
- await module.client.collection('objects').deleteMany(query);
+ await module.client.collection('objects').deleteMany(query, {
+ hint: hintKeyValue,
+ });
};
function buildLexQuery(query, min, max) {
@@ -568,7 +603,10 @@ module.exports = function (module) {
const cursor = module.client.collection('objects').find({
_key: params.key, value: { $regex: regex },
- }, { projection: project });
+ }, {
+ projection: project,
+ hint: hintKeyValue,
+ });
if (params.limit) {
cursor.limit(params.limit);
@@ -601,6 +639,7 @@ module.exports = function (module) {
const cursor = await module.client.collection('objects')
.find(query, { projection: project })
.sort({ score: sort })
+ .hint(hintKeyScore)
.batchSize(options.batch);
if (processFn && processFn.constructor && processFn.constructor.name !== 'AsyncFunction') {
diff --git a/src/database/mongo/sorted/intersect.js b/src/database/mongo/sorted/intersect.js
index a91388539c..dd6ccea581 100644
--- a/src/database/mongo/sorted/intersect.js
+++ b/src/database/mongo/sorted/intersect.js
@@ -12,6 +12,7 @@ module.exports = function (module) {
}
let items = await objects.find({ _key: counts.smallestSet }, {
projection: { _id: 0, value: 1 },
+ hint: { _key: 1, value: -1 },
}).batchSize(counts.minCount + 1).toArray();
const otherSets = keys.filter(s => s !== counts.smallestSet);
@@ -19,9 +20,14 @@ module.exports = function (module) {
/* eslint-disable no-await-in-loop */
const query = { _key: otherSets[i], value: { $in: items.map(i => i.value) } };
if (i === otherSets.length - 1) {
- return await objects.countDocuments(query);
+ return await objects.countDocuments(query, {
+ hint: { _key: 1, value: -1 },
+ });
}
- items = await objects.find(query, { projection: { _id: 0, value: 1 } }).batchSize(items.length + 1).toArray();
+ items = await objects.find(query, {
+ projection: { _id: 0, value: 1 },
+ hint: { _key: 1, value: -1 },
+ }).batchSize(items.length + 1).toArray();
}
};
@@ -30,6 +36,7 @@ module.exports = function (module) {
const counts = await Promise.all(
sets.map(s => objects.countDocuments({ _key: s }, {
limit: limit || 25000,
+ hint: { _key: 1, value: -1 },
}))
);
const minCount = Math.min(...counts);
@@ -97,7 +104,9 @@ module.exports = function (module) {
otherSets.push(otherSets.splice(otherSets.indexOf(sortSet), 1)[0]);
for (let i = 0; i < otherSets.length; i++) {
/* eslint-disable no-await-in-loop */
- const cursor = objects.find({ _key: otherSets[i], value: { $in: items.map(i => i.value) } });
+ const cursor = objects.find({ _key: otherSets[i], value: { $in: items.map(i => i.value) } }, {
+ hint: { _key: 1, value: -1 },
+ });
cursor.batchSize(items.length + 1);
// at the last step sort by sortSet
if (i === otherSets.length - 1) {
@@ -123,6 +132,7 @@ module.exports = function (module) {
const cursor = await module.client.collection('objects')
.find({ _key: sortSet }, { projection: project })
.sort({ score: params.sort })
+ .hint({ _key: 1, score: -1 })
.batchSize(batchSize);
const otherSets = params.sets.filter(s => s !== sortSet);
@@ -145,6 +155,7 @@ module.exports = function (module) {
_key: s, value: { $in: items.map(i => i.value) },
}, {
projection: { _id: 0, value: 1 },
+ hint: { _key: 1, value: -1 },
}).batchSize(items.length + 1).toArray();
return new Set(data.map(i => i.value));
}));
diff --git a/src/database/mongo/sorted/remove.js b/src/database/mongo/sorted/remove.js
index 80545d56fe..37fc0aa6f7 100644
--- a/src/database/mongo/sorted/remove.js
+++ b/src/database/mongo/sorted/remove.js
@@ -21,6 +21,8 @@ module.exports = function (module) {
await module.client.collection('objects').deleteMany({
_key: Array.isArray(key) ? { $in: key } : key,
value: isValueArray ? { $in: value } : value,
+ }, {
+ hint: { _key: 1, value: -1 },
});
};
@@ -30,7 +32,11 @@ module.exports = function (module) {
}
value = helpers.valueToString(value);
- await module.client.collection('objects').deleteMany({ _key: { $in: keys }, value: value });
+ await module.client.collection('objects').deleteMany({
+ _key: { $in: keys }, value: value,
+ }, {
+ hint: { _key: 1, value: -1 },
+ });
};
module.sortedSetsRemoveRangeByScore = async function (keys, min, max) {
@@ -49,7 +55,9 @@ module.exports = function (module) {
query.score.$lte = parseFloat(max);
}
- await module.client.collection('objects').deleteMany(query);
+ await module.client.collection('objects').deleteMany(query, {
+ hint: { _key: 1, score: -1 },
+ });
};
module.sortedSetRemoveBulk = async function (data) {
@@ -58,6 +66,8 @@ module.exports = function (module) {
}
await module.client.collection('objects').deleteMany({
$or: data.map(([key, value]) => ({ _key: key, value: String(value) })),
+ }, {
+ hint: { _key: 1, value: -1 },
});
};
};
diff --git a/src/database/mongo/sorted/union.js b/src/database/mongo/sorted/union.js
index d70deab889..a50c220bc7 100644
--- a/src/database/mongo/sorted/union.js
+++ b/src/database/mongo/sorted/union.js
@@ -10,7 +10,9 @@ module.exports = function (module) {
{ $match: { _key: { $in: keys } } },
{ $group: { _id: { value: '$value' } } },
{ $group: { _id: null, count: { $sum: 1 } } },
- ]).toArray();
+ ], {
+ hint: { _key: 1, value: -1 },
+ }).toArray();
return Array.isArray(data) && data.length ? data[0].count : 0;
};
@@ -60,7 +62,9 @@ module.exports = function (module) {
}
pipeline.push({ $project: project });
- let data = await module.client.collection('objects').aggregate(pipeline).toArray();
+ let data = await module.client.collection('objects').aggregate(pipeline, {
+ hint: { _key: 1, value: -1 },
+ }).toArray();
if (!params.withScores) {
data = data.map(item => item.value);
}