summaryrefslogtreecommitdiff
path: root/jstests/sharding/timeseries_query.js
blob: dd2a6ba8c55d5660ea5e33d16131e2090e3c34be (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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
 * Tests the queries on sharded time-series collection with various combination of shard key
 * patterns.
 *
 * @tags: [
 *   requires_fcv_51,
 *   requires_find_command,
 * ]
 */

(function() {
load("jstests/core/timeseries/libs/timeseries.js");
load("jstests/libs/analyze_plan.js");

Random.setRandomSeed();

const dbName = 'testDB';
const collName = 'testColl';
const unshardedColl = "unsharded";
const timeField = 'time';
const metaField = 'hostid';

const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
const sDB = st.s.getDB(dbName);
const shard0DB = st.shard0.getDB(dbName);
const shard1DB = st.shard1.getDB(dbName);

if (!TimeseriesTest.timeseriesCollectionsEnabled(st.shard0)) {
    jsTestLog("Skipping test because the time-series collection feature flag is disabled");
    st.stop();
    return;
}

if (!TimeseriesTest.shardedtimeseriesCollectionsEnabled(st.shard0)) {
    jsTestLog("Skipping test because the sharded time-series collection feature flag is disabled");
    st.stop();
    return;
}

// Helpers.
let currentId = 0;
function generateId() {
    return currentId++;
}

function generateDoc(time, metaValue) {
    return TimeseriesTest.generateHosts(1).map((host, index) => Object.assign(host, {
        _id: generateId(),
        [metaField]: metaValue,
        [timeField]: ISODate(time),
    }))[0];
}

function runQueryOnTimeField({date, matchOperator, expectedDocs, expectedShards}) {
    runQuery({query: {time: {[matchOperator]: ISODate(date)}}, expectedDocs, expectedShards});
}

function runInsert(timestamp, metaValue) {
    const doc = generateDoc(timestamp, metaValue);
    assert.commandWorked(sDB.getCollection(collName).insert(doc));
    assert.commandWorked(sDB.getCollection(unshardedColl).insert(doc));
}

function runQuery(
    {query, expectedDocs, expectedShards, expectQueryRewrite = true, expectCollScan = false}) {
    // Restart profiler.
    for (let shardDB of [shard0DB, shard1DB]) {
        shardDB.setProfilingLevel(0);
        shardDB.system.profile.drop();
        shardDB.setProfilingLevel(2);
    }

    // Run the query with both find and aggregate commands. Both should return same number of
    // entries.
    const coll = sDB.getCollection(collName);
    const findOutput = coll.find(query).toArray();
    assert.eq(findOutput.length, expectedDocs, findOutput);

    const unshardedOutput = sDB.getCollection(unshardedColl).find(query).toArray();
    assert.sameMembers(unshardedOutput, findOutput);

    const aggOutput = coll.aggregate([{$match: query}]).toArray();
    assert.sameMembers(unshardedOutput, aggOutput);

    if (expectedShards) {
        let filter = {
            "command.aggregate": `system.buckets.${collName}`,
        };

        // If the query was rewritten to be a match expression on the buckets collection, we should
        // expect a $match stage at the beginning of the pipeline.
        if (expectQueryRewrite) {
            filter["command.pipeline.0.$match"] = {$exists: true};
        } else {
            filter["command.pipeline.0.$_internalUnpackBucket"] = {$exists: true};
        }

        const shard0Entries = shard0DB.system.profile.find(filter).toArray();
        const shard1Entries = shard1DB.system.profile.find(filter).toArray();

        const primaryShard = st.getPrimaryShard(dbName);
        if (expectedShards.includes(primaryShard.shardName)) {
            // There should one profiler entry for each of the find and aggregate commands.
            assert.eq(shard0Entries.length, 2, shard0Entries);
        } else {
            assert.eq(shard0Entries.length, 0, shard0Entries);
        }

        const otherShard = st.getOther(primaryShard);
        if (expectedShards.includes(otherShard.shardName)) {
            // There should one profiler entry for each of the find and aggregate commands.
            assert.eq(shard1Entries.length, 2, shard1Entries);
        } else {
            assert.eq(shard1Entries.length, 0, shard1Entries);
        }

        // Test the explain plans from all of the expected shards.
        const plans = [
            coll.find(query).explain(),
            coll.explain().aggregate([{$match: query}]),
            coll.aggregate([{$match: query}], {explain: true})
        ];
        plans.forEach(plan => {
            assert.eq(expectedShards.sort(), Object.keys(plan.shards).sort());
            expectedShards.forEach(shard => {
                const winningPlan = plan.shards[shard].stages[0].$cursor.queryPlanner.winningPlan;
                if (expectCollScan) {
                    assert(isCollscan(sDB, winningPlan));
                } else {
                    assert(isIxscan(sDB, winningPlan));
                }
            });
        });
    }
}

// Shard key on just the time field.
(function timeShardKey() {
    assert.commandWorked(sDB.adminCommand({enableSharding: dbName}));
    st.ensurePrimaryShard(dbName, st.shard0.shardName);

    // Shard time-series collection.
    const shardKey = {[timeField]: 1};
    assert.commandWorked(sDB.adminCommand({
        shardCollection: `${dbName}.${collName}`,
        key: shardKey,
        timeseries: {timeField, granularity: "hours"}
    }));

    // Split the chunks such that primary shard has chunk: [MinKey, 2020-01-01) and other shard has
    // chunk [2020-01-01, MaxKey].
    splitPoint = {[`control.min.${timeField}`]: ISODate(`2020-01-01`)};
    assert.commandWorked(
        sDB.adminCommand({split: `${dbName}.system.buckets.${collName}`, middle: splitPoint}));

    // Move one of the chunks into the second shard.
    const primaryShard = st.getPrimaryShard(dbName);
    const otherShard = st.getOther(primaryShard);
    assert.commandWorked(sDB.adminCommand({
        movechunk: `${dbName}.system.buckets.${collName}`,
        find: splitPoint,
        to: otherShard.name,
        _waitForDelete: true
    }));

    // Ensure that each shard owns one chunk.
    const counts = st.chunkCounts(`system.buckets.${collName}`, dbName);
    assert.eq(1, counts[primaryShard.shardName], counts);
    assert.eq(1, counts[otherShard.shardName], counts);

    const coll = sDB.getCollection(collName);
    for (let i = 0; i < 2; i++) {
        runInsert("2019-11-11");
        runInsert("2019-12-31");
        runInsert("2020-01-21");
        runInsert("2020-11-31");
    }

    // EQ.
    runQueryOnTimeField({
        date: "2019-11-11",
        matchOperator: "$eq",
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2019-12-31",
        matchOperator: "$eq",
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-01-21",
        matchOperator: "$eq",
        expectedDocs: 2,
        expectedShards: [otherShard.shardName, primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-11-31",
        matchOperator: "$eq",
        expectedDocs: 2,
        expectedShards: [otherShard.shardName]
    });

    // LTE.
    runQueryOnTimeField({
        date: "2019-11-11",
        matchOperator: "$lte",
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2019-12-31",
        matchOperator: "$lte",
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-02-11",
        matchOperator: "$lte",
        expectedDocs: 6,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2021-01-01",
        matchOperator: "$lte",
        expectedDocs: 8,
        expectedShards: [
            primaryShard.shardName,
            otherShard.shardName,
        ]
    });

    // LT.
    runQueryOnTimeField({
        date: "2019-11-11",
        matchOperator: "$lt",
        expectedDocs: 0,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2019-12-31",
        matchOperator: "$lte",
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-02-11",
        matchOperator: "$lt",
        expectedDocs: 6,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2021-01-01",
        matchOperator: "$lt",
        expectedDocs: 8,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });

    // GTE
    runQueryOnTimeField({
        date: "2019-11-11",
        matchOperator: "$gte",
        expectedDocs: 8,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-01-11",
        matchOperator: "$gte",
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2021-01-01",
        matchOperator: "$gte",
        expectedDocs: 0,
        expectedShards: [otherShard.shardName]
    });

    // GT
    runQueryOnTimeField({
        date: "2019-11-11",
        matchOperator: "$gt",
        expectedDocs: 6,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2020-01-11",
        matchOperator: "$gt",
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQueryOnTimeField({
        date: "2021-01-01",
        matchOperator: "$gt",
        expectedDocs: 0,
        expectedShards: [otherShard.shardName]
    });

    // OR queries are currently not re-written. So expect the query to be sent to both the shards,
    // and do a full collection scan on each shard.
    runQuery({
        query: {$or: [{time: ISODate("2019-11-11")}, {time: ISODate("2019-11-12")}]},
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName, otherShard.shardName],
        expectQueryRewrite: false,
        expectCollScan: true,
    });

    sDB.dropDatabase();
})();

// Shard key on the metadata field and time fields.
(function metaAndTimeShardKey() {
    assert.commandWorked(sDB.adminCommand({enableSharding: dbName}));
    st.ensurePrimaryShard(dbName, st.shard0.shardName);

    assert.commandWorked(sDB.adminCommand({
        shardCollection: `${dbName}.${collName}`,
        key: {[metaField]: 1, 'time': 1},
        timeseries: {timeField, metaField, granularity: "hours"}
    }));

    // Split the chunks such that primary shard has chunk: [{MinKey, MinKey}, {0, 2020-01-01}) and
    // other shard has chunk [{0, 2020-01-01}, {MaxKey, MaxKey}].
    assert.commandWorked(st.s.adminCommand({
        split: `${dbName}.system.buckets.${collName}`,
        middle: {meta: 0, 'control.min.time': ISODate(`2020-01-01`)}
    }));

    const primaryShard = st.getPrimaryShard(dbName);
    const otherShard = st.getOther(primaryShard);
    assert.commandWorked(st.s.adminCommand({
        movechunk: `${dbName}.system.buckets.${collName}`,
        find: {meta: 10, 'control.min.time': MinKey},
        to: otherShard.shardName,
        _waitForDelete: true
    }));

    const counts = st.chunkCounts(`system.buckets.${collName}`, dbName);
    assert.eq(1, counts[st.shard0.shardName]);
    assert.eq(1, counts[st.shard1.shardName]);

    const coll = sDB.getCollection(collName);

    for (let i = 0; i < 2; i++) {
        runInsert("2019-11-11", i);
        runInsert("2019-12-31", -i);
        runInsert("2020-01-21", i);
        runInsert("2020-11-31", -i);
    }
    runInsert("2020-11-31", {subField: 1});

    // EQ.
    runQuery({
        query: {[metaField]: 0},
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({query: {[metaField]: 1}, expectedDocs: 2, expectedShards: [otherShard.shardName]});

    // Query on sub-fields of shard key pattern will be routed to all shards.
    runQuery({
        query: {[`${metaField}.subField`]: 1},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName, otherShard.shardName],
        // Since the index cannot be used on the meta sub-field, expect a full collection scan.
        expectCollScan: true,
    });

    runQuery({
        query: {[metaField]: 0, [timeField]: ISODate("2019-12-31")},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: ISODate("2020-01-21")},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });

    // LTE.
    runQuery({
        query: {[metaField]: 0, [timeField]: {$lte: ISODate("2019-12-31")}},
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName]
    });
    runQuery({
        query: {[metaField]: 1, [timeField]: {$lte: ISODate("2020-11-11")}},
        expectedDocs: 2,
        expectedShards: [otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$lte: ISODate("2020-11-11")}},
        expectedDocs: 3,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: {$lte: 0}, [timeField]: {$lte: ISODate("2019-12-31")}},
        expectedDocs: 3,
        expectedShards: [primaryShard.shardName]
    });

    // LT.
    runQuery({
        query: {[metaField]: 0, [timeField]: {$lt: ISODate("2019-12-31")}},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName]
    });
    runQuery({
        query: {[metaField]: 1, [timeField]: {$lt: ISODate("2020-11-11")}},
        expectedDocs: 2,
        expectedShards: [otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$lt: ISODate("2020-11-11")}},
        expectedDocs: 3,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: {$lt: 0}, [timeField]: {$lt: ISODate("2019-12-31")}},
        expectedDocs: 0,
        expectedShards: [primaryShard.shardName]
    });

    // GTE.
    runQuery({
        query: {[metaField]: -1, [timeField]: {$gte: ISODate("2020-11-31")}},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$gte: ISODate("2020-11-11")}},
        expectedDocs: 1,
        expectedShards: [otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$gte: ISODate("2020-01-02")}},
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: {$gte: 0}, [timeField]: {$gte: ISODate("2020-02-01")}},
        expectedDocs: 1,
        expectedShards: [otherShard.shardName]
    });

    // GT.
    runQuery({
        query: {[metaField]: -1, [timeField]: {$gt: ISODate("2020-11-31")}},
        expectedDocs: 0,
        expectedShards: [primaryShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$gt: ISODate("2020-11-11")}},
        expectedDocs: 1,
        expectedShards: [otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: 0, [timeField]: {$gt: ISODate("2020-01-02")}},
        expectedDocs: 2,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({
        query: {[metaField]: {$gt: 0}, [timeField]: {$gt: ISODate("2020-02-01")}},
        expectedDocs: 0,
        expectedShards: [otherShard.shardName]
    });

    sDB.dropDatabase();
})();

// Shard key on the metadata fields.
(function metaFieldShardKey() {
    assert.commandWorked(sDB.adminCommand({enableSharding: dbName}));
    st.ensurePrimaryShard(dbName, st.shard0.shardName);

    // Shard timeseries collection.
    const metaPrefix = `${metaField}.prefix`;
    const metaSuffix = `${metaField}.suffix`;
    const shardKey = {[metaPrefix]: 1, [metaSuffix]: 1};
    assert.commandWorked(sDB.adminCommand({
        shardCollection: `${dbName}.${collName}`,
        key: shardKey,
        timeseries: {timeField, metaField}
    }));

    splitPoint = {'meta.prefix': 0, 'meta.suffix': 0};
    assert.commandWorked(
        sDB.adminCommand({split: `${dbName}.system.buckets.${collName}`, middle: splitPoint}));

    // Move one of the chunks into the second shard.
    const primaryShard = st.getPrimaryShard(dbName);
    const otherShard = st.getOther(primaryShard);
    assert.commandWorked(sDB.adminCommand({
        movechunk: `${dbName}.system.buckets.${collName}`,
        find: splitPoint,
        to: otherShard.name,
        _waitForDelete: true
    }));

    // Ensure that each shard owns one chunk.
    const counts = st.chunkCounts(`system.buckets.${collName}`, dbName);
    assert.eq(1, counts[primaryShard.shardName], counts);
    assert.eq(1, counts[otherShard.shardName], counts);

    const coll = sDB.getCollection(collName);

    for (let i = 0; i < 2; i++) {
        runInsert("2019-11-11", {prefix: -i, suffix: -i});
        runInsert("2019-12-31", {prefix: -i, suffix: i});
        runInsert("2020-01-21", {prefix: i, suffix: -i});
        runInsert("2020-11-31", {prefix: i, suffix: i});
    }

    // Equality queries on prefix and full shard key values.
    runQuery({
        query: {[metaPrefix]: 0},
        expectedDocs: 4,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });
    runQuery({
        query: {[metaPrefix]: 0, [metaSuffix]: 0},
        expectedDocs: 4,
        expectedShards: [otherShard.shardName]
    });
    runQuery({query: {[metaPrefix]: 1}, expectedDocs: 2, expectedShards: [otherShard.shardName]});

    runQuery({
        query: {[metaPrefix]: 0, [timeField]: ISODate("2019-12-31")},
        expectedDocs: 1,
        expectedShards: [primaryShard.shardName, otherShard.shardName]
    });

    sDB.dropDatabase();
})();

st.stop();
})();