Last active
March 23, 2020 20:13
-
-
Save alexbevi/c2cbcc63d8554f0fdded32e74e17aebf to your computer and use it in GitHub Desktop.
Measure the index utilization for all collections in a database before/after an operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* measureIndexUsage(block) | |
* | |
* Measure the index utilization before/after a block is run. The block can contain | |
* one to many operations, however the index utilization will only measure the collections | |
* associated with the current `db` instance. | |
* | |
* NOTE: this script does not "isolate" the operation(s) run so if running in a busy | |
* environment the results may represent other operations index utilization. | |
* | |
* @sample | |
* MEASURE_INDEX_USAGE(function() { | |
* /////////////////////////////////////////////////// | |
* db.users.aggregate([ | |
* { $match: { name: "Alex" } }, | |
* { $lookup: { | |
* from: "orders", | |
* localField: "orders", | |
* foreignField: "order_id", | |
* as: "orders" | |
* }} | |
* ]); | |
* //////////////////////////////////////////////////// | |
* }); | |
* | |
* The output will be an object with the collection names as keys and the indexes | |
* with counters (number of times used) before/after the block was executed. | |
* | |
* { | |
* "orders" : { | |
* "order_id_1" : "1 (14 total)" | |
* }, | |
* "users" : { | |
* "name_1_orders_1" : "1 (19 total)" | |
* } | |
* } | |
* | |
* @created 2020-03-20 | |
* @author Alex Bevilacqua <[email protected]> | |
*/ | |
function MEASURE_INDEX_USAGE(block) { | |
var statsCmd = [ { $indexStats: { } } ]; | |
// measure index usage | |
var statsBefore = {}; | |
db.getCollectionNames().forEach(function(c) { | |
statsBefore[c] = {}; | |
db.getCollection(c).aggregate(statsCmd).forEach(function(d) { | |
statsBefore[c][d.name] = d.accesses.ops * 1.0; | |
}); | |
}); | |
block(); | |
// measure index usage again | |
var stats = {}; | |
db.getCollectionNames().forEach(function(c) { | |
stats[c] = {}; | |
db.getCollection(c).aggregate(statsCmd).forEach(function(d) { | |
if (!statsBefore[c].hasOwnProperty(d.name)) { | |
stats[c][d.name] = d.accesses.ops; | |
} else if (statsBefore[c][d.name] != d.accesses.ops) { | |
stats[c][d.name] = (d.accesses.ops - statsBefore[c][d.name]) + " (" + d.accesses.ops + " total)"; | |
} | |
}); | |
}); | |
printjson(stats); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example: