summaryrefslogtreecommitdiff
path: root/jstests/core/index_stats.js
blob: 8561cbd2029f30a1d305db13772f3afb069e3c5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// The test runs commands that are not allowed with security token: mapReduce.
// @tags: [
//   not_allowed_with_security_token,
//   # This test attempts to perform write operations and get index usage statistics using the
//   # $indexStats stage. The former operation must be routed to the primary in a replica set,
//   # whereas the latter may be routed to a secondary.
//   assumes_read_preference_unchanged,
//   # Cannot implicitly shard accessed collections because of following errmsg: A single
//   # update/delete on a sharded collection must contain an exact match on _id or contain the shard
//   # key.
//   assumes_unsharded_collection,
//   does_not_support_stepdowns,
//   does_not_support_repeated_reads,
//   requires_non_retryable_writes,
//   # Tenant migrations passthrough suites automatically retry operations on TenantMigrationAborted
//   # errors.
//   tenant_migration_incompatible,
//   # TODO SERVER-67639: Verify $indexStats works for queries that are eligible for CQF.
//   cqf_incompatible,
// ]

(function() {
"use strict";

load("jstests/libs/analyze_plan.js");
load("jstests/libs/sbe_util.js");  // For checkSBEEnabled.

var colName = "jstests_index_stats";
var col = db[colName];
col.drop();

var getUsageCount = function(indexName, collection) {
    collection = collection || col;
    var cursor = collection.aggregate([{$indexStats: {}}]);
    while (cursor.hasNext()) {
        var doc = cursor.next();

        if (doc.name === indexName) {
            return doc.accesses.ops;
        }
    }

    return undefined;
};

var getIndexKey = function(indexName) {
    var cursor = col.aggregate([{$indexStats: {}}]);
    while (cursor.hasNext()) {
        var doc = cursor.next();

        if (doc.name === indexName) {
            return doc.key;
        }
    }

    return undefined;
};

var getIndexNamesForWinningPlan = function(explain) {
    var indexNameList = [];
    var winningStages = getPlanStages(explain.queryPlanner.winningPlan, "IXSCAN");
    for (var i = 0; i < winningStages.length; ++i) {
        indexNameList.push(winningStages[i].indexName);
    }

    return indexNameList;
};

assert.commandWorked(col.insert({a: 1, b: 1, c: 1}));
assert.commandWorked(col.insert({a: 2, b: 2, c: 2}));
assert.commandWorked(col.insert({a: 3, b: 3, c: 3}));

//
// Confirm no index stats object exists prior to index creation.
//
col.findOne({a: 1});
assert.eq(undefined, getUsageCount("a_1"));

//
// Create indexes.
//
assert.commandWorked(col.createIndex({a: 1}, {name: "a_1"}));
assert.commandWorked(col.createIndex({b: 1, c: 1}, {name: "b_1_c_1"}));
var countA = 0;  // Tracks expected index access for "a_1".
var countB = 0;  // Tracks expected index access for "b_1_c_1".

//
// Confirm a stats object exists post index creation (with 0 count).
//
assert.eq(countA, getUsageCount("a_1"));
assert.eq({a: 1}, getIndexKey("a_1"));

//
// Confirm index stats tick on find().
//
col.findOne({a: 1});
countA++;

assert.eq(countA, getUsageCount("a_1"));

//
// Confirm index stats tick on findAndModify() update.
//
var res =
    db.runCommand({findAndModify: colName, query: {a: 1}, update: {$set: {d: 1}}, 'new': true});
assert.commandWorked(res);
countA++;
assert.eq(countA, getUsageCount("a_1"));

//
// Confirm index stats tick on findAndModify() delete.
//
res = db.runCommand({findAndModify: colName, query: {a: 2}, remove: true});
assert.commandWorked(res);
countA++;
assert.eq(countA, getUsageCount("a_1"));
assert.commandWorked(col.insert(res.value));

//
// Confirm $and operation ticks indexes for winning plan, but not rejected plans.
//

// We cannot use explain() to determine which indexes would be used for this query, since
// 1) explain() will not bump the access counters
// 2) explain() always runs the multi planner, and the multi planner may choose a different
// index each run. We therefore run the query, and check that only one of the indexes has its
// counter bumped (assuming we never choose an index intersection plan).
const results = col.find({a: 2, b: 2}).itcount();
if (countA + 1 == getUsageCount("a_1")) {
    // Plan using index A was chosen. Index B should not have been used (assuming no index
    // intersection plans are used).
    countA++;
} else {
    // Plan using index B was chosen. Index A should not have been used (assuming no index
    // intersection plans are used).
    assert.eq(++countB, getUsageCount("b_1_c_1"));
}
assert.eq(countA, getUsageCount("a_1"));
assert.eq(countB, getUsageCount("b_1_c_1"));
assert.eq(0, getUsageCount("_id_"));

//
// Confirm index stats tick on distinct().
//
res = db.runCommand({distinct: colName, key: "b", query: {b: 1}});
assert.commandWorked(res);
countB++;
assert.eq(countB, getUsageCount("b_1_c_1"));

//
// Confirm index stats tick on aggregate w/ match.
//
res = db.runCommand({aggregate: colName, pipeline: [{$match: {b: 1}}], cursor: {}});
assert.commandWorked(res);
countB++;
assert.eq(countB, getUsageCount("b_1_c_1"));

//
// Confirm index stats tick on mapReduce with query.
//
res = db.runCommand({
    mapReduce: colName,
    map: function() {
        emit(this.b, this.c);
    },
    reduce: function(key, val) {
        return val;
    },
    query: {b: 2},
    out: {inline: 1}
});
assert.commandWorked(res);
countB++;
assert.eq(countB, getUsageCount("b_1_c_1"));

//
// Confirm index stats tick on update().
//
assert.commandWorked(col.update({a: 2}, {$set: {d: 2}}));
countA++;
assert.eq(countA, getUsageCount("a_1"));

//
// Confirm index stats tick on remove().
//
assert.commandWorked(col.remove({a: 2}));
countA++;
assert.eq(countA, getUsageCount("a_1"));

//
// Confirm multiple index $or operation ticks all involved indexes.
//
col.findOne({$or: [{a: 1}, {b: 1, c: 1}]});
countA++;
countB++;
assert.eq(countA, getUsageCount("a_1"));
assert.eq(countB, getUsageCount("b_1_c_1"));

//
// Confirm index stats object does not exist post index drop.
//
assert.commandWorked(col.dropIndex("b_1_c_1"));
countB = 0;
assert.eq(undefined, getUsageCount("b_1_c_1"));

//
// Confirm index stats object exists with count 0 once index is recreated.
//
assert.commandWorked(col.createIndex({b: 1, c: 1}, {name: "b_1_c_1"}));
assert.eq(countB, getUsageCount("b_1_c_1"));

//
// Confirm that retrieval fails if $indexStats is not in the first pipeline position.
//
assert.throws(function() {
    col.aggregate([{$match: {}}, {$indexStats: {}}]);
});

//
// Confirm index use is recorded for $lookup.
//
const foreignCollection = db[colName + "_foreign"];
foreignCollection.drop();
assert.commandWorked(foreignCollection.insert([{_id: 0}, {_id: 1}, {_id: 2}]));
assert(col.drop());
assert.commandWorked(col.insert([{_id: 0, foreignId: 1}, {_id: 1, foreignId: 2}]));
assert.eq(0, getUsageCount("_id_"));
assert.eq(2,
              col.aggregate([
                     {$match: {_id: {$in: [0, 1]}}},
                     {
                       $lookup: {
                           from: foreignCollection.getName(),
                           localField: 'foreignId',
                           foreignField: '_id',
                           as: 'results'
                       }
                     }
                 ])
                  .itcount());
assert.eq(1, getUsageCount("_id_", col), "Expected aggregation to use _id index");
if (!checkSBEEnabled(db)) {
    assert.eq(2,
              getUsageCount("_id_", foreignCollection),
              "Expected each lookup to be tracked as an index use");
} else {
    assert.eq(1,
              getUsageCount("_id_", foreignCollection),
              "Expected the index join lookup to be tracked as a single index use");
}

//
// Confirm index use is recorded for partially pushed down pipelines with a $lookup stage
//
assert.eq(true, foreignCollection.drop());
assert.commandWorked(foreignCollection.insert([{_id: 0}, {_id: 1}, {_id: 2}]));
assert(col.drop());
assert.commandWorked(col.insert([{_id: 0, foreignId: 1}, {_id: 1, foreignId: 2}]));
assert.eq(0, getUsageCount("_id_"));
const pipeline = [
    {$match: {_id: {$in: [0, 1]}}},
    {
        $lookup: {
            from: foreignCollection.getName(),
            localField: 'foreignId',
            foreignField: '_id',
            as: 'results'
        }
    },
    {
        $project: {
            foreignId: 1,
            results: 1,
            matches: {$size: "$results"},
        }
    }
];
assert.eq(2, col.aggregate(pipeline).itcount());
assert.eq(1, getUsageCount("_id_", col), "Expected aggregation to use _id index");
if (!checkSBEEnabled(db)) {
    assert.eq(2,
              getUsageCount("_id_", foreignCollection),
              "Expected each lookup to be tracked as an index use");
} else {
    assert.eq(1,
              getUsageCount("_id_", foreignCollection),
              "Expected the index join lookup to be tracked as a single index use");
}
const explain = col.explain().aggregate(pipeline);
assert(getAggPlanStage(explain, "$cursor"),
       "Expected a $cursor stage for a partially pushed down pipeline");

//
// Confirm index use is recorded for $graphLookup.
//
foreignCollection.drop();
assert.commandWorked(foreignCollection.insert([
    {_id: 0, connectedTo: 1},
    {_id: 1, connectedTo: "X"},
    {_id: 2, connectedTo: 3},
    {_id: 3, connectedTo: "Y"},  // Be sure to use a different value here to make sure
                                 // $graphLookup doesn't cache the query.
]));
assert(col.drop());
assert.commandWorked(col.insert([{_id: 0, foreignId: 0}, {_id: 1, foreignId: 2}]));
assert.eq(0, getUsageCount("_id_"));
assert.eq(2,
              col.aggregate([
                     {$match: {_id: {$in: [0, 1]}}},
                     {
                       $graphLookup: {
                           from: foreignCollection.getName(),
                           startWith: '$foreignId',
                           connectToField: '_id',
                           connectFromField: 'connectedTo',
                           as: 'results'
                       }
                     }
                 ])
                  .itcount());
assert.eq(1, getUsageCount("_id_", col), "Expected aggregation to use _id index");
assert.eq(2 * 3,
          getUsageCount("_id_", foreignCollection),
          "Expected each of two graph searches to issue 3 queries, each using the _id index");

//
// Confirm that index 'hidden' status can be found in '$indexStats'.
//
assert(col.drop());
assert.commandWorked(col.createIndex({a: 1}, {hidden: true}));
const hiddenIndexStats =
    col.aggregate([{$indexStats: {}}, {$match: {"name": "a_1", "spec.hidden": true}}]).toArray();
assert.eq(hiddenIndexStats.length, 1);

//
// Confirm the index usage stats will be reset on hiding and unhiding the index.
//
assert(col.drop());
assert.commandWorked(col.insert({a: 1}));
assert.commandWorked(col.createIndex({a: 1}));

// When the index is not hidden, the stats keep counting.
res = col.findOne({a: 1});
assert(1, res);
assert.eq(1, getUsageCount("a_1"));

// On modifying an index's definition (i.e. hiding or unhiding an index), the usage stats of the
// index will be reset to zero.
assert.commandWorked(col.hideIndex("a_1"));
assert.eq(0, getUsageCount("a_1"));

// Confirm that the stats don't tick after the index is hidden.
res = col.findOne({a: 1});
assert(1, res);
assert.eq(0, getUsageCount("a_1"));

assert.commandWorked(col.unhideIndex("a_1"));
res = col.findOne({a: 1});
assert(1, res);
assert.eq(1, getUsageCount("a_1"));
})();