mirror of
https://github.com/FerretDB/documentdb.git
synced 2026-11-25 19:59:54 -05:00
Merged PR 1479858: $percentile & $median for $group accumulator
### Does this PR have any customer impact? ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) ### Are you introducing any new config? If yes, do you have tests with and without them being set? ### Release Note (Refer [Template](../docs/release_notes/pgmongo_template.md)) ### Description draft ---- #### AI description (iteration 1) #### PR Classification New feature #### PR Summary This pull request introduces new aggregation functions and support for t-digest in the project. - Added `bson_tdigest.c` to implement t-digest helper functions. - Created new SQL aggregate functions in `group_aggregates--1.23-0.sql` and `group_aggregates_support--1.23-0.sql`. - Updated `bson_aggregation_pipeline.c` to handle the new `$percentile` accumulator. - Modified `metadata_cache.c` and `metadata_cache.h` to include OID for the new `BsonPercentileAggregateFunction`. - Updated migration scripts `pg_helio_api--1.22-0--1.23-0.sql` and `pgmongo--1.22-0--1.23-0.sql` to include new SQL files.
This commit is contained in:
1 parent
eed060110b
commit
722ef60784
23 files changed
+2689
-14
No files matched your search
@@ -79,6 +79,9 @@ extern bool EnableCollation;
|
||||
extern bool EnableFastPathPointLookupPlanner;
|
||||
extern bool DefaultInlineWriteOperations;
|
||||
|
||||
/* GUC to config tdigest compression */
|
||||
extern int TdigestCompressionAccuracy;
|
||||
|
||||
/*
|
||||
* The mutation function that modifies a given query with a pipeline stage's value.
|
||||
*/
|
||||
@@ -1267,8 +1270,13 @@ GenerateAggregationQuery(Datum database, pgbson *aggregationSpec, QueryData *que
|
||||
}
|
||||
else if (StringViewEqualsCString(&keyView, "let"))
|
||||
{
|
||||
EnsureTopLevelFieldType("let", &aggregationIterator, BSON_TYPE_DOCUMENT);
|
||||
let = *value;
|
||||
bool hasValue = EnsureTopLevelFieldTypeNullOkUndefinedOK("let",
|
||||
&aggregationIterator,
|
||||
BSON_TYPE_DOCUMENT);
|
||||
if (hasValue)
|
||||
{
|
||||
let = *value;
|
||||
}
|
||||
}
|
||||
else if (StringViewEqualsCString(&keyView, "collectionUUID"))
|
||||
{
|
||||
@@ -2388,6 +2396,94 @@ ParseInputDocumentForTopAndBottom(const bson_value_t *inputDocument, bson_value_
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parses the input document for $median and $percentile accumulator operator, extracts input, p and methods.
|
||||
* @param inputDocument: input document for the operator
|
||||
* @param input: this is a pointer which after parsing will hold input expression
|
||||
* @param p: this is a pointer which after parsing will hold the p, i.e. the percentile array value
|
||||
* @param method: this is a pointer which after parsing will hold method
|
||||
* @param isMedianOp: this contains the name of the operator for error msg formatting purposes. This value is supposed to be $firstN/$lastN.
|
||||
*/
|
||||
void
|
||||
ParseInputDocumentForMedianAndPercentile(const bson_value_t *inputDocument,
|
||||
bson_value_t *input,
|
||||
bson_value_t *p, bson_value_t *method,
|
||||
bool isMedianOp)
|
||||
{
|
||||
const char *opName = isMedianOp ? "$median" : "$percentile";
|
||||
if (inputDocument->value_type != BSON_TYPE_DOCUMENT)
|
||||
{
|
||||
int errorcode = isMedianOp ? ERRCODE_DOCUMENTDB_LOCATION7436100 :
|
||||
ERRCODE_DOCUMENTDB_LOCATION7429703;
|
||||
ereport(ERROR, (errcode(errorcode),
|
||||
errmsg("specification must be an object; found %s type: %s",
|
||||
opName, BsonTypeName(inputDocument->value_type)),
|
||||
errdetail_log(
|
||||
"%s specification must be an object", opName)));
|
||||
}
|
||||
bson_iter_t docIter;
|
||||
BsonValueInitIterator(inputDocument, &docIter);
|
||||
|
||||
while (bson_iter_next(&docIter))
|
||||
{
|
||||
const char *key = bson_iter_key(&docIter);
|
||||
if (strcmp(key, "input") == 0)
|
||||
{
|
||||
*input = *bson_iter_value(&docIter);
|
||||
}
|
||||
else if (strcmp(key, "method") == 0)
|
||||
{
|
||||
*method = *bson_iter_value(&docIter);
|
||||
}
|
||||
/* only evaluate p for $percentile */
|
||||
else if (!isMedianOp && strcmp(key, "p") == 0)
|
||||
{
|
||||
*p = *bson_iter_value(&docIter);
|
||||
}
|
||||
else
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_UNKNOWNBSONFIELD), errmsg(
|
||||
"BSON field '$%s.%s' is an unknown field.", opName, key),
|
||||
errdetail_log("%s found an unknown argument", opName)));
|
||||
}
|
||||
}
|
||||
|
||||
/* check required fields are present */
|
||||
char *keyName;
|
||||
if (((input->value_type == BSON_TYPE_EOD) && (keyName = "input")) ||
|
||||
(!isMedianOp && (p->value_type == BSON_TYPE_EOD) && (keyName = "p")) ||
|
||||
((method->value_type == BSON_TYPE_EOD) && (keyName = "method")))
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION40414), errmsg(
|
||||
"BSON field '$%s.%s' is missing but is a required field",
|
||||
opName, keyName)));
|
||||
}
|
||||
|
||||
/* validate method: can only be 'approximate' for now */
|
||||
if (method->value_type != BSON_TYPE_UTF8)
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_TYPEMISMATCH), errmsg(
|
||||
"BSON field '$%s.method' is the wrong type %s, expected type 'string'",
|
||||
opName, BsonTypeName(method->value_type)),
|
||||
errdetail_log(
|
||||
"BSON field '$%s.method' expects type 'string'", opName)));
|
||||
}
|
||||
if (strcmp(method->value.v_utf8.str, "approximate") != 0)
|
||||
{
|
||||
/* Same error message for both $median and $percentile */
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg(
|
||||
"Currently only 'approximate' can be used as percentile 'method'")));
|
||||
}
|
||||
|
||||
/* set p for $median to 0.5 */
|
||||
if (isMedianOp)
|
||||
{
|
||||
p->value_type = BSON_TYPE_DOUBLE;
|
||||
p->value.v_double = 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function validates and throws error in case bson type is not a numeric > 0 and less than max value of int64 i.e. 9223372036854775807
|
||||
*/
|
||||
@@ -4931,6 +5027,92 @@ AddMaxMinNGroupAccumulator(Query *query, const bson_value_t *accumulatorValue,
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Function used to support percentile/median accumulator.
|
||||
*/
|
||||
inline static List *
|
||||
AddPercentileMedianGroupAccumulator(Query *query, const bson_value_t *accumulatorValue,
|
||||
List *repathArgs, Const *accumulatorText,
|
||||
ParseState *parseState, char *identifiers,
|
||||
Expr *documentExpr, StringView *accumulatorName,
|
||||
Expr *variableSpec, bool isMedianOp)
|
||||
{
|
||||
bson_value_t input = { 0 };
|
||||
bson_value_t p = { 0 };
|
||||
bson_value_t method = { 0 };
|
||||
|
||||
ParseInputDocumentForMedianAndPercentile(accumulatorValue, &input, &p, &method,
|
||||
isMedianOp);
|
||||
|
||||
/* construct expression to get input and p */
|
||||
List *inputFuncArgs;
|
||||
List *pFuncArgs;
|
||||
Oid bsonExpressionGetFunction;
|
||||
|
||||
Expr *inputConstValue = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(&input));
|
||||
Const *accuracyConstValue = makeConst(INT4OID, -1, InvalidOid, sizeof(int32_t),
|
||||
Int32GetDatum(TdigestCompressionAccuracy),
|
||||
false, true);
|
||||
Expr *pConstValue = (Expr *) MakeBsonConst(BsonValueToDocumentPgbson(&p));
|
||||
Const *trueConst = makeConst(BOOLOID, -1, InvalidOid, 1, BoolGetDatum(true), false,
|
||||
true);
|
||||
if (variableSpec != NULL)
|
||||
{
|
||||
bsonExpressionGetFunction = BsonExpressionGetWithLetFunctionOid();
|
||||
inputFuncArgs = list_make4(documentExpr, inputConstValue, trueConst,
|
||||
variableSpec);
|
||||
pFuncArgs = list_make4(documentExpr, pConstValue, trueConst, variableSpec);
|
||||
}
|
||||
else
|
||||
{
|
||||
bsonExpressionGetFunction = BsonExpressionGetFunctionOid();
|
||||
inputFuncArgs = list_make3(documentExpr, inputConstValue, trueConst);
|
||||
pFuncArgs = list_make3(documentExpr, pConstValue, trueConst);
|
||||
}
|
||||
|
||||
FuncExpr *inputAccumFunc = makeFuncExpr(bsonExpressionGetFunction, BsonTypeId(),
|
||||
inputFuncArgs, InvalidOid,
|
||||
InvalidOid, COERCE_EXPLICIT_CALL);
|
||||
FuncExpr *pAccumFunc = makeFuncExpr(bsonExpressionGetFunction, BsonTypeId(),
|
||||
pFuncArgs, InvalidOid,
|
||||
InvalidOid, COERCE_EXPLICIT_CALL);
|
||||
|
||||
if (EnableLetSupport && BsonTypeId() != DocumentDBCoreBsonTypeId() &&
|
||||
IsClusterVersionAtleast(DocDB_V0, 24, 0))
|
||||
{
|
||||
inputAccumFunc = makeFuncExpr(
|
||||
DocumentDBCoreBsonToBsonFunctionOId(), BsonTypeId(), list_make1(
|
||||
inputAccumFunc),
|
||||
InvalidOid,
|
||||
InvalidOid, COERCE_EXPLICIT_CALL);
|
||||
pAccumFunc = makeFuncExpr(
|
||||
DocumentDBCoreBsonToBsonFunctionOId(), BsonTypeId(), list_make1(pAccumFunc),
|
||||
InvalidOid,
|
||||
InvalidOid, COERCE_EXPLICIT_CALL);
|
||||
}
|
||||
|
||||
Oid aggregateFunctionOid = isMedianOp ? BsonMedianAggregateFunctionOid() :
|
||||
BsonPercentileAggregateFunctionOid();
|
||||
Aggref *aggref = CreateMultiArgAggregate(aggregateFunctionOid, list_make3(
|
||||
(Expr *) inputAccumFunc,
|
||||
accuracyConstValue, (Expr *) pAccumFunc),
|
||||
list_make3_oid(
|
||||
BsonTypeId(),
|
||||
accuracyConstValue->consttype,
|
||||
BsonTypeId()), parseState);
|
||||
|
||||
repathArgs = lappend(repathArgs, AddGroupExpression((Expr *) accumulatorText,
|
||||
parseState, identifiers, query,
|
||||
TEXTOID, NULL));
|
||||
|
||||
repathArgs = lappend(repathArgs, AddGroupExpression((Expr *) aggref, parseState,
|
||||
identifiers, query, BsonTypeId(),
|
||||
NULL));
|
||||
|
||||
return repathArgs;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Handles the $group stage.
|
||||
* Creates a subquery.
|
||||
@@ -5497,6 +5679,40 @@ HandleGroup(const bson_value_t *existingValue, Query *query,
|
||||
&accumulatorName,
|
||||
context->variableSpec);
|
||||
}
|
||||
else if (StringViewEqualsCString(&accumulatorName, "$median"))
|
||||
{
|
||||
if (!(IsClusterVersionAtleast(DocDB_V0, 24, 0)))
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED),
|
||||
errmsg("Accumulator $median is not supported yet")));
|
||||
}
|
||||
repathArgs = AddPercentileMedianGroupAccumulator(query,
|
||||
&accumulatorElement.bsonValue,
|
||||
repathArgs,
|
||||
accumulatorText, parseState,
|
||||
identifiers,
|
||||
origEntry->expr,
|
||||
&accumulatorName,
|
||||
context->variableSpec, true);
|
||||
}
|
||||
else if (StringViewEqualsCString(&accumulatorName, "$percentile"))
|
||||
{
|
||||
if (!(IsClusterVersionAtleast(DocDB_V0, 24, 0)))
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED),
|
||||
errmsg(
|
||||
"Accumulator $percentile is not supported yet")));
|
||||
}
|
||||
repathArgs = AddPercentileMedianGroupAccumulator(query,
|
||||
&accumulatorElement.bsonValue,
|
||||
repathArgs,
|
||||
accumulatorText, parseState,
|
||||
identifiers,
|
||||
origEntry->expr,
|
||||
&accumulatorName,
|
||||
context->variableSpec,
|
||||
false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_LOCATION15952),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -71,6 +71,9 @@ int ScramDefaultSaltLen = SCRAM_DEFAULT_SALT_LEN;
|
||||
#define MAX_USER_LIMIT 10
|
||||
int MaxUserLimit = MAX_USER_LIMIT;
|
||||
|
||||
#define DEFAULT_TDIGEST_COMPRESSION_ACCURACY 1500
|
||||
int TdigestCompressionAccuracy = DEFAULT_TDIGEST_COMPRESSION_ACCURACY;
|
||||
|
||||
#define DEFAULT_DOCUMENTDB_PG_READ_ONLY_FOR_DISK_FULL false
|
||||
bool DocumentDBPGReadOnlyForDiskFull = DEFAULT_DOCUMENTDB_PG_READ_ONLY_FOR_DISK_FULL;
|
||||
|
||||
@@ -263,4 +266,13 @@ InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix)
|
||||
PGC_SUSET,
|
||||
0,
|
||||
NULL, NULL, NULL);
|
||||
|
||||
DefineCustomIntVariable(
|
||||
psprintf("%s.tdigestCompressionAccuracy", newGucPrefix),
|
||||
gettext_noop("Accuracy parameter of the t-digest compression."),
|
||||
gettext_noop(
|
||||
"The number of maximum centroid to use in the t-digest. Range from 10 to 10000. The higher the number, the more accurate will be, but higher memory usage."),
|
||||
&TdigestCompressionAccuracy,
|
||||
DEFAULT_TDIGEST_COMPRESSION_ACCURACY, 10, 10000,
|
||||
PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
}
|
||||
@@ -270,6 +270,8 @@ static char FeatureMapping[MAX_FEATURE_COUNT][MAX_FEATURE_NAME_LENGTH] = {
|
||||
[FEATURE_STAGE_GROUP_ACC_FIRSTN_GT10] = "firstN_acc_GT10",
|
||||
[FEATURE_STAGE_GROUP_ACC_LASTN] = "lastN_acc",
|
||||
[FEATURE_STAGE_GROUP_ACC_LASTN_GT10] = "lastN_acc_GT10",
|
||||
[FEATURE_STAGE_GROUP_ACC_MEDIAN] = "median_acc",
|
||||
[FEATURE_STAGE_GROUP_ACC_PERCENTILE] = "percentile_acc",
|
||||
[FEATURE_STAGE_GROUP_ACC_TOPN] = "topN",
|
||||
[FEATURE_STAGE_INDEXSTATS] = "indexStats",
|
||||
[FEATURE_STAGE_INVERSEMATCH] = "inverseMatch",
|
||||
|
||||
@@ -799,6 +799,12 @@ typedef struct HelioApiOidCacheData
|
||||
/* OID of the BSONSTDDEVSAMP aggregate function */
|
||||
Oid ApiCatalogBsonStdDevSampAggregateFunctionOid;
|
||||
|
||||
/* OID of the BSONMEDIAN aggregate function */
|
||||
Oid ApiCatalogBsonMedianAggregateFunctionOid;
|
||||
|
||||
/* OID of the BSONPERCENTILE aggregate function */
|
||||
Oid ApiCatalogBsonPercentileAggregateFunctionOid;
|
||||
|
||||
/* OID of the pg_catalog.any_value aggregate */
|
||||
Oid PostgresAnyValueFunctionOid;
|
||||
|
||||
@@ -4036,6 +4042,24 @@ BsonStdDevSampAggregateFunctionOid(void)
|
||||
}
|
||||
|
||||
|
||||
Oid
|
||||
BsonMedianAggregateFunctionOid(void)
|
||||
{
|
||||
return GetAggregateFunctionByName(
|
||||
&Cache.ApiCatalogBsonMedianAggregateFunctionOid,
|
||||
DocumentDBApiInternalSchemaName, "bsonmedian");
|
||||
}
|
||||
|
||||
|
||||
Oid
|
||||
BsonPercentileAggregateFunctionOid(void)
|
||||
{
|
||||
return GetAggregateFunctionByName(
|
||||
&Cache.ApiCatalogBsonPercentileAggregateFunctionOid,
|
||||
DocumentDBApiInternalSchemaName, "bsonpercentile");
|
||||
}
|
||||
|
||||
|
||||
Oid
|
||||
BsonAddToSetAggregateFunctionOid(void)
|
||||
{
|
||||
|
||||
@@ -302,7 +302,9 @@
|
||||
documentdb_api_internal | bsonlastnonsorted | documentdb_core.bson | documentdb_core.bson, bigint, documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonlastonsorted | documentdb_core.bson | documentdb_core.bson, documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonmaxn | documentdb_core.bson | documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonmedian | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonminn | documentdb_core.bson | documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonpercentile | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonstddevpop | documentdb_core.bson | documentdb_core.bson | agg
|
||||
documentdb_api_internal | bsonstddevsamp | documentdb_core.bson | documentdb_core.bson | agg
|
||||
documentdb_api_internal | build_index_concurrently | | IN p_job_index integer | proc
|
||||
@@ -354,11 +356,18 @@
|
||||
documentdb_api_internal | rum_bson_text_path_options | void | internal | func
|
||||
documentdb_api_internal | schedule_background_index_build_workers | void | p_max_num_active_user_index_builds integer DEFAULT (current_setting(('documentdb'::text || '.maxNumActiveUsersIndexBuilds'::text)))::integer, p_user_index_build_schedule integer DEFAULT (current_setting(('documentdb'::text || '.indexBuildScheduleInSec'::text)))::integer | func
|
||||
documentdb_api_internal | schema_validation_against_update | boolean | p_eval_state bytea, p_target_document documentdb_core.bson, p_source_document documentdb_core.bson, p_is_moderate boolean | func
|
||||
documentdb_api_internal | tdigest_add_double | internal | internal, documentdb_core.bson, integer, documentdb_core.bson | func
|
||||
documentdb_api_internal | tdigest_add_double_array | internal | internal, documentdb_core.bson, integer, documentdb_core.bson | func
|
||||
documentdb_api_internal | tdigest_array_percentiles | documentdb_core.bson | internal | func
|
||||
documentdb_api_internal | tdigest_combine | internal | internal, internal | func
|
||||
documentdb_api_internal | tdigest_deserial | internal | bytea, internal | func
|
||||
documentdb_api_internal | tdigest_percentile | documentdb_core.bson | internal | func
|
||||
documentdb_api_internal | tdigest_serial | bytea | internal | func
|
||||
documentdb_api_internal | trigger_validate_dbname | trigger | | func
|
||||
documentdb_api_internal | update_one | record | p_collection_id bigint, p_shard_key_value bigint, p_query documentdb_core.bson, p_update documentdb_core.bson, p_shard_key documentdb_core.bson, p_is_upsert boolean, p_sort documentdb_core.bson, p_return_old_or_new boolean, p_return_fields documentdb_core.bson, p_array_filters documentdb_core.bson, p_transaction_id text, OUT o_is_row_updated boolean, OUT o_update_skipped boolean, OUT o_is_retry boolean, OUT o_reinsert_document documentdb_core.bson, OUT o_upserted_object_id bytea, OUT o_result_document documentdb_core.bson | func
|
||||
documentdb_api_internal | update_worker | documentdb_core.bson | p_collection_id bigint, p_shard_key_value bigint, p_shard_oid regclass, p_update_internal_spec documentdb_core.bson, p_update_internal_docs documentdb_core.bsonsequence, p_transaction_id text | func
|
||||
documentdb_api_internal | validate_dbname | void | dbname text | func
|
||||
(185 rows)
|
||||
(194 rows)
|
||||
|
||||
\df documentdb_data.*
|
||||
List of functions
|
||||
@@ -416,10 +425,12 @@
|
||||
documentdb_api_internal | bsonlastnonsorted | documentdb_core.bson | documentdb_core.bson, bigint, documentdb_core.bson |
|
||||
documentdb_api_internal | bsonlastonsorted | documentdb_core.bson | documentdb_core.bson, documentdb_core.bson |
|
||||
documentdb_api_internal | bsonmaxn | documentdb_core.bson | documentdb_core.bson |
|
||||
documentdb_api_internal | bsonmedian | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson |
|
||||
documentdb_api_internal | bsonminn | documentdb_core.bson | documentdb_core.bson |
|
||||
documentdb_api_internal | bsonpercentile | documentdb_core.bson | documentdb_core.bson, integer, documentdb_core.bson |
|
||||
documentdb_api_internal | bsonstddevpop | documentdb_core.bson | documentdb_core.bson |
|
||||
documentdb_api_internal | bsonstddevsamp | documentdb_core.bson | documentdb_core.bson |
|
||||
(19 rows)
|
||||
(21 rows)
|
||||
|
||||
\da+ documentdb_data.*
|
||||
List of aggregate functions
|
||||
|
||||
Reference in new issue
Block a user