summaryrefslogtreecommitdiff
path: root/jstests/core/timeseries/timeseries_special_indexes_metadata.js
blob: 9e5ef2f5c0dfcb915cd33acdf8e1aa7f6e680897 (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
/**
 * Tests sparse, multikey, wildcard, 2d and 2dsphere indexes on time-series collections
 *
 * Tests index creation, index drops, list indexes, hide/unhide index on a time-series collection.
 *
 * @tags: [
 *   # The shardCollection implicitly creates an index on time field.
 *   assumes_unsharded_collection,
 *   does_not_support_stepdowns,
 *   does_not_support_transactions,
 *   requires_fcv_51,
 *   requires_getmore,
 *   requires_pipeline_optimization,
 * ]
 */

(function() {
"use strict";

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

TimeseriesTest.run((insert) => {
    const testdb = db.getSiblingDB("timeseries_special_indexes_db");
    const timeseriescoll = testdb.getCollection("timeseries_special_indexes_coll");
    const bucketscoll = testdb.getCollection('system.buckets.' + timeseriescoll.getName());

    const timeFieldName = 'tm';
    const metaFieldName = 'mm';

    /**
     * Sets up an empty time-series collection on namespace 'timeseriescoll' using 'timeFieldName'
     * and 'metaFieldName'. Checks that the buckets collection is created, as well.
     */
    function resetCollections() {
        timeseriescoll.drop();  // implicitly drops bucketscoll.

        assert.commandWorked(testdb.createCollection(
            timeseriescoll.getName(),
            {timeseries: {timeField: timeFieldName, metaField: metaFieldName}}));

        const dbCollNames = testdb.getCollectionNames();
        assert.contains(bucketscoll.getName(),
                        dbCollNames,
                        "Failed to find namespace '" + bucketscoll.getName() +
                            "' amongst: " + tojson(dbCollNames));
    }

    /**
     * Runs the find cmd on the time-series and buckets collections using 'bucketsIndexSpec' as an
     * index hint. Tests that hide() and unhide() of the index allows find to use or fail to use the
     * index, respectively. Tests that the listIndexes cmd returns the expected results from the
     * time-series and buckets collections.
     *
     * Some indexes (e.g. wildcard) need queries specified to use an index: the
     * 'timeseriesFindQuery' and 'bucketsFindQuery' can be used for this purpose.
     */
    function hideUnhideListIndexes(
        timeseriesIndexSpec, bucketsIndexSpec, timeseriesFindQuery = {}, bucketsFindQuery = {}) {
        jsTestLog("Testing index spec, time-series: " + tojson(timeseriesIndexSpec) +
                  ", buckets: " + tojson(bucketsIndexSpec));

        // Check that the index is usable.
        assert.gt(timeseriescoll.find(timeseriesFindQuery).hint(bucketsIndexSpec).toArray().length,
                  0);
        assert.gt(bucketscoll.find(bucketsFindQuery).hint(bucketsIndexSpec).toArray().length, 0);

        // Check that listIndexes returns expected results.
        listIndexesHasIndex(timeseriesIndexSpec);

        // Hide the index and check that the find cmd no longer works with the 'bucketsIndexSpec'
        // hint.
        assert.commandWorked(timeseriescoll.hideIndex(timeseriesIndexSpec));
        assert.commandFailedWithCode(
            assert.throws(() => timeseriescoll.find().hint(bucketsIndexSpec).toArray()),
                         ErrorCodes.BadValue);
        assert.commandFailedWithCode(
            assert.throws(() => bucketscoll.find().hint(bucketsIndexSpec).toArray()),
                         ErrorCodes.BadValue);

        // Check that the index can still be found via listIndexes even if hidden.
        listIndexesHasIndex(timeseriesIndexSpec);

        // Unhide the index and check that the find cmd with 'bucketsIndexSpec' works again.
        assert.commandWorked(timeseriescoll.unhideIndex(timeseriesIndexSpec));
        assert.gt(timeseriescoll.find(timeseriesFindQuery).hint(bucketsIndexSpec).toArray().length,
                  0);
        assert.gt(bucketscoll.find(bucketsFindQuery).hint(bucketsIndexSpec).toArray().length, 0);
    }

    /**
     * Checks that listIndexes against the time-series collection returns the 'timeseriesIndexSpec'
     * index. Expects only the 'timeseriesIndexSpec' index to exist.
     */
    function listIndexesHasIndex(timeseriesIndexSpec) {
        const timeseriesListIndexesCursor =
            assert.commandWorked(testdb.runCommand({listIndexes: timeseriescoll.getName()})).cursor;

        // Check the ns is OK.
        assert.eq(timeseriescoll.getFullName(),
                  timeseriesListIndexesCursor.ns,
                  "Found unexpected namespace: " + tojson(timeseriesListIndexesCursor));

        // Check for the index.
        assert.eq(
            1, timeseriesListIndexesCursor.firstBatch.length, tojson(timeseriesListIndexesCursor));
        assert.docEq(timeseriesIndexSpec,
                     timeseriesListIndexesCursor.firstBatch[0].key,
                     "Found unexpected index spec: " + tojson(timeseriesListIndexesCursor));
    }

    /**
     * Test sparse index on time-series collection.
     */

    jsTestLog("Testing sparse index on time-series collection.");
    resetCollections();

    // Create a sparse index on the 'mm.tag2' field of the time-series collection.
    const sparseTimeseriesIndexSpec = {[metaFieldName + '.tag2']: 1};
    const sparseBucketsIndexSpec = {['meta.tag2']: 1};
    assert.commandWorked(
        timeseriescoll.createIndex(sparseTimeseriesIndexSpec, {sparse: true}),
        'Failed to create a sparse index with: ' + tojson(sparseTimeseriesIndexSpec));

    // Only 1 of these 2 documents will be returned by a sparse index on 'mm.tag2'.
    const sparseDocIndexed =
        {_id: 0, [timeFieldName]: ISODate(), [metaFieldName]: {'tag1': 'a', 'tag2': 'b'}};
    const sparseDocNotIndexed =
        {_id: 1, [timeFieldName]: ISODate(), [metaFieldName]: {'tag1': 'c'}};
    assert.commandWorked(insert(timeseriescoll, sparseDocIndexed),
                         'Failed to insert sparseDocIndexed: ' + tojson(sparseDocIndexed));
    assert.commandWorked(insert(timeseriescoll, sparseDocNotIndexed),
                         'Failed to insert sparseDocNotIndexed: ' + tojson(sparseDocNotIndexed));

    hideUnhideListIndexes(sparseTimeseriesIndexSpec, sparseBucketsIndexSpec);

    // Check that only 1 of the 2 entries are returned. Note: index hints on a time-series
    // collection only work with the underlying buckets collection's index spec.
    assert.eq(1,
              timeseriescoll.find().hint(sparseBucketsIndexSpec).toArray().length,
              "Failed to use index: " + tojson(sparseBucketsIndexSpec));
    assert.eq(1,
              bucketscoll.find().hint(sparseBucketsIndexSpec).toArray().length,
              "Failed to use index: " + tojson(sparseBucketsIndexSpec));
    assert.commandFailedWithCode(
        assert.throws(() => timeseriescoll.find().hint(sparseTimeseriesIndexSpec).toArray()),
                     ErrorCodes.BadValue);
    assert.eq(2, timeseriescoll.find().toArray().length, "Failed to see all time-series documents");

    /**
     * Test multikey index on time-series collection.
     */

    jsTestLog("Testing multikey index on time-series collection.");
    resetCollections();

    // Create a multikey index on the time-series collection.
    const multikeyTimeseriesIndexSpec = {[metaFieldName + '.a']: 1};
    const multikeyBucketsIndexSpec = {['meta.a']: 1};
    assert.commandWorked(
        timeseriescoll.createIndex(multikeyTimeseriesIndexSpec),
        'Failed to create a multikey index with: ' + tojson(multikeyTimeseriesIndexSpec));

    // An index on {a: 1}, where 'a' is an array, will produce a multikey index 'a.zip' and
    // 'a.town'.
    const multikeyDoc = {
        _id: 0,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {'a': [{zip: '01234', town: 'nyc'}, {zip: '43210', town: 'sf'}]}
    };
    assert.commandWorked(insert(timeseriescoll, multikeyDoc),
                         'Failed to insert multikeyDoc: ' + tojson(multikeyDoc));

    const bucketsFindExplain =
        assert.commandWorked(bucketscoll.find().hint(multikeyBucketsIndexSpec).explain());
    const planStage = getPlanStage(getWinningPlan(bucketsFindExplain.queryPlanner), "IXSCAN");
    assert.eq(true,
              planStage.isMultiKey,
              "Index should have been marked as multikey: " + tojson(planStage));
    assert.eq({"meta.a": ["meta.a"]},
              planStage.multiKeyPaths,
              "Index has wrong multikey paths after insert; plan: " + tojson(planStage));

    hideUnhideListIndexes(multikeyTimeseriesIndexSpec, multikeyBucketsIndexSpec);

    /**
     * Test 2d index on time-series collection.
     */

    jsTestLog("Testing 2d index on time-series collection.");
    resetCollections();

    // Create a 2d index on the time-series collection.
    const twoDTimeseriesIndexSpec = {[metaFieldName]: "2d"};
    const twoDBucketsIndexSpec = {'meta': "2d"};
    assert.commandWorked(timeseriescoll.createIndex(twoDTimeseriesIndexSpec),
                         'Failed to create a 2d index with: ' + tojson(twoDTimeseriesIndexSpec));

    // Insert a 2d index usable document.
    const twoDDoc = {_id: 0, [timeFieldName]: ISODate(), [metaFieldName]: [40, 40]};
    assert.commandWorked(insert(timeseriescoll, twoDDoc),
                         'Failed to insert twoDDoc: ' + tojson(twoDDoc));

    assert.eq(1,
              bucketscoll.find({'meta': {$near: [0, 0]}}).toArray().length,
              "Failed to use index: " + tojson(twoDBucketsIndexSpec));

    assert.eq(1,
              bucketscoll
                  .aggregate([
                      {$geoNear: {near: [40.4, -70.4], distanceField: "dist", spherical: true}},
                      {$limit: 1}
                  ])
                  .toArray()
                  .length,
              "Failed to use 2d index: " + tojson(twoDBucketsIndexSpec));

    assert.eq(1,
              timeseriescoll
                  .aggregate([
                      {
                          $geoNear: {
                              near: [40.4, -70.4],
                              key: metaFieldName,
                              distanceField: "dist",
                              spherical: true
                          }
                      },
                      {$limit: 1}
                  ])
                  .toArray()
                  .length,
              "Failed to use 2d index: " + tojson(twoDBucketsIndexSpec));

    hideUnhideListIndexes(twoDTimeseriesIndexSpec, twoDBucketsIndexSpec);

    /**
     * Test 2dsphere index on time-series collection.
     */

    jsTestLog("Testing 2dsphere index on time-series collection.");
    resetCollections();

    // Create a 2dsphere index on the time-series collection.
    const twoDSphereTimeseriesIndexSpec = {[metaFieldName]: "2dsphere"};
    const twoDSphereBucketsIndexSpec = {['meta']: "2dsphere"};
    assert.commandWorked(
        timeseriescoll.createIndex(twoDSphereTimeseriesIndexSpec),
        'Failed to create a 2dsphere index with: ' + tojson(twoDSphereTimeseriesIndexSpec));

    // Insert a 2dsphere index usable document.
    const twoDSphereDoc = {
        _id: 0,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {type: "Point", coordinates: [40, -70]}
    };
    assert.commandWorked(insert(timeseriescoll, twoDSphereDoc),
                         'Failed to insert twoDSphereDoc: ' + tojson(twoDSphereDoc));

    assert.eq(1,
              bucketscoll
                  .aggregate([
                      {
                          $geoNear: {
                              near: {type: "Point", coordinates: [40.4, -70.4]},
                              distanceField: "dist",
                              spherical: true
                          }
                      },
                      {$limit: 1}
                  ])
                  .toArray()
                  .length,
              "Failed to use 2dsphere index: " + tojson(twoDSphereBucketsIndexSpec));

    assert.eq(1,
              timeseriescoll
                  .aggregate([
                      {
                          $geoNear: {
                              near: {type: "Point", coordinates: [40.4, -70.4]},
                              key: metaFieldName,
                              distanceField: "dist",
                              spherical: true
                          }
                      },
                      {$limit: 1}
                  ])
                  .toArray()
                  .length,
              "Failed to use 2dsphere index: " + tojson(twoDSphereBucketsIndexSpec));

    hideUnhideListIndexes(twoDSphereTimeseriesIndexSpec, twoDSphereBucketsIndexSpec);

    /**
     * Test wildcard index on time-series collection.
     */

    jsTestLog("Testing wildcard index on time-series collection.");
    resetCollections();

    // Create a wildcard index on the time-series collection.
    const wildcardTimeseriesIndexSpec = {[metaFieldName + '.$**']: 1};
    const wildcardBucketsIndexSpec = {['meta.$**']: 1};
    assert.commandWorked(
        timeseriescoll.createIndex(wildcardTimeseriesIndexSpec),
        'Failed to create a wildcard index with: ' + tojson(wildcardTimeseriesIndexSpec));

    const wildcard1Doc = {
        _id: 0,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {a: 1, b: 1, c: {d: 1, e: 1}},
    };
    const wildcard2Doc = {
        _id: 1,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {a: 2, b: 2, c: {d: 1, e: 2}},
    };
    const wildcard3Doc = {
        _id: 0,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {a: 3, b: 3, c: {d: 3, e: 3}},
    };
    assert.commandWorked(insert(timeseriescoll, wildcard1Doc));
    assert.commandWorked(insert(timeseriescoll, wildcard2Doc));
    assert.commandWorked(insert(timeseriescoll, wildcard3Doc));

    // Queries on 'metaFieldName' subfields should be able to use the wildcard index hint.
    const wildcardBucketsResults =
        bucketscoll.find({'meta.c.d': 1}).hint(wildcardBucketsIndexSpec).toArray();
    assert.eq(2, wildcardBucketsResults.length, "Query results: " + tojson(wildcardBucketsResults));
    const wildcardTimeseriesResults =
        timeseriescoll.find({[metaFieldName + '.c.d']: 1}).hint(wildcardBucketsIndexSpec).toArray();
    assert.eq(
        2, wildcardTimeseriesResults.length, "Query results: " + tojson(wildcardTimeseriesResults));

    // The time-series index spec does not work as a hint.
    assert.commandFailedWithCode(
        assert.throws(() => timeseriescoll.find({[metaFieldName + '.c.d']: 1})
                                .hint(wildcardTimeseriesIndexSpec)
                                .toArray()),
                     ErrorCodes.BadValue);

    hideUnhideListIndexes(wildcardTimeseriesIndexSpec,
                          wildcardBucketsIndexSpec,
                          {[metaFieldName + '.c.d']: 1} /* timeseriesFindQuery */,
                          {'meta.c.d': 1} /* bucketsFindQuery */);

    // Test multikey with a wildcard index on the time-series collection.
    // Wildcard indexes have special handling for multikey.

    jsTestLog("Testing multikey with wildcard index on time-series collection.");

    const wildcardMultikeyDoc = {
        _id: 0,
        [timeFieldName]: ISODate(),
        [metaFieldName]: {
            a: 3,
            b: 3,
            c: {d: 3, e: 3},
            d: [{zip: '01234', town: 'nyc'}, {zip: '43210', town: 'sf'}]
        },
    };
    assert.commandWorked(timeseriescoll.insert(wildcardMultikeyDoc));

    assert.eq(1,
              timeseriescoll.find({'mm.d.zip': '01234'}).hint(wildcardBucketsIndexSpec).itcount());
    const wildcardFindExplain = assert.commandWorked(
        bucketscoll.find({'meta.d.zip': '01234'}).hint(wildcardBucketsIndexSpec).explain());
    const planWildcardStage =
        getPlanStage(getWinningPlan(wildcardFindExplain.queryPlanner), "IXSCAN");
    assert(planWildcardStage.isMultiKey,
           "Index should have been marked as multikey: " + tojson(planWildcardStage));
    assert(planWildcardStage.multiKeyPaths.hasOwnProperty("meta.d.zip"),
           "Index has wrong multikey paths after insert; plan: " + tojson(planWildcardStage));
});
})();