Skip to content

Adds ability to set hint on Parse.Query #6322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions spec/ParseQuery.hint.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
'use strict';

const Config = require('../lib/Config');
const TestUtils = require('../lib/TestUtils');
const request = require('../lib/request');

let config;

const masterKeyHeaders = {
'X-Parse-Application-Id': 'test',
'X-Parse-Rest-API-Key': 'rest',
'X-Parse-Master-Key': 'test',
'Content-Type': 'application/json',
};

const masterKeyOptions = {
headers: masterKeyHeaders,
json: true,
};

describe_only_db('mongo')('Parse.Query hint', () => {
beforeEach(() => {
config = Config.get('test');
});

afterEach(async () => {
await config.database.schemaCache.clear();
await TestUtils.destroyAllDataPermanently(false);
});

it('query find with hint string', async () => {
const object = new TestObject();
await object.save();

const collection = await config.database.adapter._adaptiveCollection(
'TestObject'
);
let explain = await collection._rawFind(
{ _id: object.id },
{ explain: true }
);
expect(explain.queryPlanner.winningPlan.stage).toBe('IDHACK');
explain = await collection._rawFind(
{ _id: object.id },
{ hint: '_id_', explain: true }
);
expect(explain.queryPlanner.winningPlan.stage).toBe('FETCH');
expect(explain.queryPlanner.winningPlan.inputStage.indexName).toBe('_id_');
});

it('query find with hint object', async () => {
const object = new TestObject();
await object.save();

const collection = await config.database.adapter._adaptiveCollection(
'TestObject'
);
let explain = await collection._rawFind(
{ _id: object.id },
{ explain: true }
);
expect(explain.queryPlanner.winningPlan.stage).toBe('IDHACK');
explain = await collection._rawFind(
{ _id: object.id },
{ hint: { _id: 1 }, explain: true }
);
expect(explain.queryPlanner.winningPlan.stage).toBe('FETCH');
expect(explain.queryPlanner.winningPlan.inputStage.keyPattern).toEqual({
_id: 1,
});
});

it('query aggregate with hint string', async () => {
const object = new TestObject({ foo: 'bar' });
await object.save();

const collection = await config.database.adapter._adaptiveCollection(
'TestObject'
);
let result = await collection.aggregate([{ $group: { _id: '$foo' } }], {
explain: true,
});
let { queryPlanner } = result[0].stages[0].$cursor;
expect(queryPlanner.winningPlan.stage).toBe('COLLSCAN');

result = await collection.aggregate([{ $group: { _id: '$foo' } }], {
hint: '_id_',
explain: true,
});
queryPlanner = result[0].stages[0].$cursor.queryPlanner;
expect(queryPlanner.winningPlan.stage).toBe('FETCH');
expect(queryPlanner.winningPlan.inputStage.indexName).toBe('_id_');
});

it('query aggregate with hint object', async () => {
const object = new TestObject({ foo: 'bar' });
await object.save();

const collection = await config.database.adapter._adaptiveCollection(
'TestObject'
);
let result = await collection.aggregate([{ $group: { _id: '$foo' } }], {
explain: true,
});
let { queryPlanner } = result[0].stages[0].$cursor;
expect(queryPlanner.winningPlan.stage).toBe('COLLSCAN');

result = await collection.aggregate([{ $group: { _id: '$foo' } }], {
hint: { _id: 1 },
explain: true,
});
queryPlanner = result[0].stages[0].$cursor.queryPlanner;
expect(queryPlanner.winningPlan.stage).toBe('FETCH');
expect(queryPlanner.winningPlan.inputStage.keyPattern).toEqual({ _id: 1 });
});

it('query find with hint (rest)', async () => {
const object = new TestObject();
await object.save();
let options = Object.assign({}, masterKeyOptions, {
url: Parse.serverURL + '/classes/TestObject',
qs: {
explain: true,
},
});
let response = await request(options);
let explain = response.data.results;
expect(explain.queryPlanner.winningPlan.inputStage.stage).toBe('COLLSCAN');

options = Object.assign({}, masterKeyOptions, {
url: Parse.serverURL + '/classes/TestObject',
qs: {
explain: true,
hint: '_id_',
},
});
response = await request(options);
explain = response.data.results;
expect(
explain.queryPlanner.winningPlan.inputStage.inputStage.indexName
).toBe('_id_');
});

it('query aggregate with hint (rest)', async () => {
const object = new TestObject({ foo: 'bar' });
await object.save();
let options = Object.assign({}, masterKeyOptions, {
url: Parse.serverURL + '/aggregate/TestObject',
qs: {
explain: true,
group: JSON.stringify({ objectId: '$foo' }),
},
});
let response = await request(options);
let { queryPlanner } = response.data.results[0].stages[0].$cursor;
expect(queryPlanner.winningPlan.stage).toBe('COLLSCAN');

options = Object.assign({}, masterKeyOptions, {
url: Parse.serverURL + '/aggregate/TestObject',
qs: {
explain: true,
hint: '_id_',
group: JSON.stringify({ objectId: '$foo' }),
},
});
response = await request(options);
queryPlanner = response.data.results[0].stages[0].$cursor.queryPlanner;
expect(queryPlanner.winningPlan.inputStage.keyPattern).toEqual({ _id: 1 });
});
});
24 changes: 18 additions & 6 deletions src/Adapters/Storage/Mongo/MongoCollection.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ export default class MongoCollection {
// none, then build the geoindex.
// This could be improved a lot but it's not clear if that's a good
// idea. Or even if this behavior is a good idea.
find(query, { skip, limit, sort, keys, maxTimeMS, readPreference } = {}) {
find(
query,
{ skip, limit, sort, keys, maxTimeMS, readPreference, hint, explain } = {}
) {
// Support for Full Text Search - $text
if (keys && keys.$score) {
delete keys.$score;
Expand All @@ -26,6 +29,8 @@ export default class MongoCollection {
keys,
maxTimeMS,
readPreference,
hint,
explain,
}).catch(error => {
// Check for "no geoindex" error
if (
Expand Down Expand Up @@ -54,18 +59,24 @@ export default class MongoCollection {
keys,
maxTimeMS,
readPreference,
hint,
explain,
})
)
);
});
}

_rawFind(query, { skip, limit, sort, keys, maxTimeMS, readPreference } = {}) {
_rawFind(
query,
{ skip, limit, sort, keys, maxTimeMS, readPreference, hint, explain } = {}
) {
let findOperation = this._mongoCollection.find(query, {
skip,
limit,
sort,
readPreference,
hint,
});

if (keys) {
Expand All @@ -76,10 +87,10 @@ export default class MongoCollection {
findOperation = findOperation.maxTimeMS(maxTimeMS);
}

return findOperation.toArray();
return explain ? findOperation.explain(explain) : findOperation.toArray();
}

count(query, { skip, limit, sort, maxTimeMS, readPreference } = {}) {
count(query, { skip, limit, sort, maxTimeMS, readPreference, hint } = {}) {
// If query is empty, then use estimatedDocumentCount instead.
// This is due to countDocuments performing a scan,
// which greatly increases execution time when being run on large collections.
Expand All @@ -96,6 +107,7 @@ export default class MongoCollection {
sort,
maxTimeMS,
readPreference,
hint,
});

return countOperation;
Expand All @@ -105,9 +117,9 @@ export default class MongoCollection {
return this._mongoCollection.distinct(field, query);
}

aggregate(pipeline, { maxTimeMS, readPreference } = {}) {
aggregate(pipeline, { maxTimeMS, readPreference, hint, explain } = {}) {
return this._mongoCollection
.aggregate(pipeline, { maxTimeMS, readPreference })
.aggregate(pipeline, { maxTimeMS, readPreference, hint, explain })
.toArray();
}

Expand Down
25 changes: 18 additions & 7 deletions src/Adapters/Storage/Mongo/MongoStorageAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ export class MongoStorageAdapter implements StorageAdapter {
className: string,
schema: SchemaType,
query: QueryType,
{ skip, limit, sort, keys, readPreference }: QueryOptions
{ skip, limit, sort, keys, readPreference, hint, explain }: QueryOptions
): Promise<any> {
schema = convertParseSchemaToMongoSchema(schema);
const mongoWhere = transformWhere(className, query, schema);
Expand Down Expand Up @@ -652,13 +652,18 @@ export class MongoStorageAdapter implements StorageAdapter {
keys: mongoKeys,
maxTimeMS: this._maxTimeMS,
readPreference,
hint,
explain,
})
)
.then(objects =>
objects.map(object =>
.then(objects => {
if (explain) {
return objects;
}
return objects.map(object =>
mongoObjectToParseObject(className, object, schema)
)
)
);
})
.catch(err => this.handleError(err));
}

Expand Down Expand Up @@ -712,7 +717,8 @@ export class MongoStorageAdapter implements StorageAdapter {
className: string,
schema: SchemaType,
query: QueryType,
readPreference: ?string
readPreference: ?string,
hint: ?mixed
) {
schema = convertParseSchemaToMongoSchema(schema);
readPreference = this._parseReadPreference(readPreference);
Expand All @@ -721,6 +727,7 @@ export class MongoStorageAdapter implements StorageAdapter {
collection.count(transformWhere(className, query, schema, true), {
maxTimeMS: this._maxTimeMS,
readPreference,
hint,
})
)
.catch(err => this.handleError(err));
Expand Down Expand Up @@ -760,7 +767,9 @@ export class MongoStorageAdapter implements StorageAdapter {
className: string,
schema: any,
pipeline: any,
readPreference: ?string
readPreference: ?string,
hint: ?mixed,
explain?: boolean
) {
let isPointerField = false;
pipeline = pipeline.map(stage => {
Expand Down Expand Up @@ -791,6 +800,8 @@ export class MongoStorageAdapter implements StorageAdapter {
collection.aggregate(pipeline, {
readPreference,
maxTimeMS: this._maxTimeMS,
hint,
explain,
})
)
.then(results => {
Expand Down
9 changes: 7 additions & 2 deletions src/Adapters/Storage/StorageAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export type QueryOptions = {
distinct?: boolean,
pipeline?: any,
readPreference?: ?string,
hint?: ?mixed,
explain?: Boolean,
};

export type UpdateQueryOptions = {
Expand Down Expand Up @@ -92,7 +94,8 @@ export interface StorageAdapter {
schema: SchemaType,
query: QueryType,
readPreference?: string,
estimate?: boolean
estimate?: boolean,
hint?: mixed
): Promise<number>;
distinct(
className: string,
Expand All @@ -104,7 +107,9 @@ export interface StorageAdapter {
className: string,
schema: any,
pipeline: any,
readPreference: ?string
readPreference: ?string,
hint: ?mixed,
explain?: boolean
): Promise<any>;
performInitialization(options: ?any): Promise<void>;

Expand Down
Loading