Skip to content
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

feat: _useEstimate parameter in count requests #261

Merged
merged 7 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

### Added

- Includes query paramater `_useEstimate` on `GET \count` requests to execute the MongoDB `estimatedDocumentCount`

### Fixed

- [#237](https://github.com/mia-platform/crud-service/issues/237): casting values in `_q` queries are now even if case of nested fields
Expand Down
8 changes: 8 additions & 0 deletions docs/10_Overview_and_Usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,14 @@ This will return:
Filters can be applied to the count. By default, only PUBLIC documents are counted.
:::

You can add the parameter `_useEstimate`, to be set to true, to execute the count request using the collection metadata instead of scanning the entire collection. This method drastically improves speed of the request, but it does not allow to use any filter (any other parameter included will be ignored).

```shell
curl -X GET https://your-url/v2/plates/count?_useEstimate=true -H "accept: application/json" -H "content-type: application/json" -H "client-key: client-key"
```

The result will be the total of every document in the collection, regarding the `__STATE__`.
ThisIsDemetrio marked this conversation as resolved.
Show resolved Hide resolved

#### Geospatial Queries

On CRUD service, it is possible to filter data also for proximity, using MongoDB Geospatial Queries.
Expand Down
5 changes: 5 additions & 0 deletions lib/CrudService.js
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,11 @@ class CrudService {
return this._mongoCollection.countDocuments(searchQuery, options)
}

async estimatedDocumentCount(context) {
context.log.debug({}, 'estimatedDocumentCount operation requested')
return this._mongoCollection.estimatedDocumentCount()
}

async deleteAll(context, query, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
Expand Down
15 changes: 12 additions & 3 deletions lib/JSONSchemaGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const {
UPDATEDAT,
CREATORID,
CREATEDAT,
USE_ESTIMATE,
} = require('./consts')
const {
stateCreateValidationSchema,
Expand Down Expand Up @@ -118,7 +119,7 @@ module.exports = class JSONSchemaGenerator {
pathFieldsRawSchema
)
const deleteProperties = propertiesDeleteValidation(structuredClone(validationGetProperties))
const countAndQueryValidation = {
const mongoIdAndDeleteProperties = {
[MONGOID]: { ...mongoIdTypeValidator[idType]() },
...structuredClone(deleteProperties),
}
Expand Down Expand Up @@ -156,8 +157,16 @@ module.exports = class JSONSchemaGenerator {
}
this._propertiesPatchQueryValidation = deleteProperties
this._propertiesFilterChangeStateMany = changeStateProperties
this._propertiesCountValidation = { ...countAndQueryValidation }
this._propertiesPatchManyQueryValidation = { ...countAndQueryValidation }
this._propertiesCountValidation = {
...mongoIdAndDeleteProperties,
[USE_ESTIMATE]: {
type: 'boolean',
enum: [true, false],
description: 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
default: false,
},
}
this._propertiesPatchManyQueryValidation = { ...mongoIdAndDeleteProperties }
}

getSchemaDetail(operationName) {
Expand Down
1 change: 1 addition & 0 deletions lib/consts.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ module.exports = Object.freeze({
STATE: '_st',
MONGOID: '_id',
RAW_PROJECTION: '_rawp',
USE_ESTIMATE: '_useEstimate',

// Patch commands
SETCMD: '$set',
Expand Down
7 changes: 7 additions & 0 deletions lib/httpInterface.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const {
__STATE__,
SCHEMA_CUSTOM_KEYWORDS,
rawProjectionDictionary,
USE_ESTIMATE,
} = require('./consts')

const getAccept = require('./acceptHeaderParser')
Expand Down Expand Up @@ -692,10 +693,16 @@ async function handleCount(request) {
const {
[QUERY]: clientQueryString,
[STATE]: state,
[USE_ESTIMATE]: useEstimate,
...otherParams
} = query

const { acl_rows } = headers

if (useEstimate) {
return this.crudService.estimatedDocumentCount(crudContext)
}

const mongoQuery = resolveMongoQuery(this.queryParser, clientQueryString, acl_rows, otherParams, false)

const stateArr = state.split(',')
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/booksCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
'signature.name': {
'type': 'string',
},
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/booksNewCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
'signature.name': {
'type': 'string',
},
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/carsCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
},
'additionalProperties': false,
},
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/carsNewCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
},
'additionalProperties': false,
},
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/stationsCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
},
'additionalProperties': false,
},
Expand Down
9 changes: 9 additions & 0 deletions tests/expectedSchemas/stationsNewCountSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,15 @@ module.exports = {
'type': 'string',
'description': 'Additional raw stringified projection for MongoDB',
},
'_useEstimate': {
'type': 'boolean',
'enum': [
true,
false,
],
'description': 'If "true", returns the count of all documents in the collection based on the metadata of the collection. It works only there are no other query parameters.',
'default': false,
},
},
'additionalProperties': false,
},
Expand Down
14 changes: 14 additions & 0 deletions tests/httpInterface.countList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,20 @@ tap.test('HTTP GET /count', async t => {
acl_rows: undefined,
count: 0,
},
{
name: 'query with _useEstimate parameter',
method: 'GET',
url: `${prefix}/count?_useEstimate=true`,
count: fixtures.length,
acl_rows: undefined,
},
{
name: 'query with _useEstimate parameter should ignore other query parameters',
method: 'GET',
url: `${prefix}/count?_useEstimate=true&_q=${JSON.stringify({ price: { $gt: Infinity } })}`,
count: fixtures.length,
acl_rows: undefined,
},
]

t.plan(tests.length)
Expand Down
Loading