注意:以下翻译的准确性尚未经过验证。这是使用 AIP ↗ 从原始英文文本进行的机器翻译。
函数可以被用于在Ontology中计算自定义聚合,然后可以在Workshop中的图表微件中展示。本指南将逐步介绍如何编写自定义聚合逻辑,加载来自Ontology的聚合数据,操作结果以创建未来结果的预测,并返回修改后的结果。
在处理本节内容时,这些参考资料可能会有所帮助:
在这个例子中,假设我们有一个由expenses
组成的Ontology,每个expenses
包括一个组织的部门名称、一个date
和一个支出amount
。我们希望估算未来六个月内各部门的月支出。我们可以从加载月支出的聚合数据开始:
Copied!1 2 3 4 5
const result = await Objects.search() .expenses() .groupBy(expense => expense.departmentName.topValues()) // 根据部门名称的前几个值对支出进行分组 .segmentBy(expense => expense.date.byMonth()) // 根据支出日期按月进行分段 .sum(expense => expense.amount); // 计算每个分组和分段的支出总和
接下来,我们可以推算出各部门未来六个月的支出。为了举例说明,我们采用一种非常简单的方法,即使用最后一个月的值作为未来六个月的估算。
Copied!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
const modifiedBuckets = result.buckets.map(bucket => { // 找到对应于最近一个月的bucket const lastBucket = bucket.value[bucket.value.length - 1]; let nextSixMonths: IBaseBucket<IRange<Timestamp>, Double>[] = []; let currentMonth = lastBucket.key.max!; // 循环六次 for (let i = 0; i < 6; i++) { // 找到这个范围的结束(下一个月) const nextMonth = currentMonth.plusMonths(1); // 添加一个新的bucket,该bucket使用下一个月作为日期范围 // 并使用最近一个月作为值 nextSixMonths.push({ key: { min: currentMonth, max: nextMonth, }, value: lastBucket.value, }); currentMonth = nextMonth; } // 返回修改后的结果 return { key: bucket.key, value: nextSixMonths }; });
现在我们已经创建了未来六个月的估算,我们可以直接返回这些估算值:
Copied!1
return { buckets: modifiedBuckets }; // 返回一个对象,包含修改后的桶数组
总之,这里是此函数的完整示例代码:
Copied!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
@Function() public async estimatedDepartmentExpenses(): Promise<ThreeDimensionalAggregation<string, IRange<Timestamp>>> { const result = await Objects.search() .expenses() .groupBy(expense => expense.departmentName.topValues()) .segmentBy(expense => expense.date.byMonths()) .sum(expense => expense.amount); const modifiedBuckets = result.buckets.map(bucket => { // 找到对应于最近一个月的桶 const lastBucket = bucket.value[bucket.value.length - 1]; let nextSixMonths: IBaseBucket<IRange<Timestamp>, Double>[] = []; let currentMonth = lastBucket.key.max!; // 循环六次 for (let i = 0; i < 6; i++) { // 找到这个范围的结束时间(下一个月) const nextMonth = currentMonth.plusMonths(1); // 添加一个新的桶,使用下一个月作为日期范围 // 并使用最近一个月作为值 nextSixMonths.push({ key: { min: currentMonth, max: nextMonth, }, value: lastBucket.value, }); currentMonth = nextMonth; } // 返回修改后的结果 return { key: bucket.key, value: nextSixMonths }; }); return { buckets: modifiedBuckets }; }
所得的聚合结果可以在Workshop图表中被用于在显示未来六个月的月度支出估算。