TypeScript v1 사용자 지정 집계
함수는 온톨로지에서 집계한 값을 가공하여 Workshop 차트가 읽는 집계 타입으로 반환할 수 있습니다. 이 예제는 부서별 마지막 월 지출을 같은 부서의 다음 여섯 달에 반복하여 간단한 전망을 만듭니다.
입력 데이터와 집계
가상의 Expense는 String departmentName, Timestamp date와 Double amount를 가지며 세 속성을 Searchable로 설정합니다. 생성 검색 메서드는 expenses라고 가정합니다.
groupBy의 departmentName.topValues()로 부서를 나누고 segmentBy의 date.byMonth()로 월을 나눈 뒤 amount를 합합니다. 부서 버킷 아래에 월별 값이 있는 ThreeDimensionalAggregation을 얻습니다.
topValues는 상위 1,000값을 대상으로 하며 고유 값이 더 많으면 근사 결과입니다. 더 많은 부서를 고려하려면 exactValues를 사용할 수 있으나 최대 10,000버킷을 고려하고 비용이 증가합니다. 전체 집계 버킷 한도도 객체 집합 API를 따릅니다.
다음 여섯 달 계산
월 버킷의 키는 IRange<Timestamp>이며 min을 포함하고 max를 제외합니다. 다음 달은 최신 월의 max부터 시작합니다. 월을 더할 때는 고정 30일이 아니라 plusMonths를 사용합니다.
배열의 마지막 원소가 최신 월이라고 가정하지 않고 실제 월 끝을 비교합니다. 빈 월 목록은 빈 전망을 반환하며, 월 끝이 없는 범위는 전망 시작을 정할 수 없어 오류로 처리합니다.
import {
Double, Function, IBaseBucket, IRange, ThreeDimensionalAggregation,
Timestamp, UserFacingError
} from "@foundry/functions-api";
import { Objects } from "@foundry/ontology-api";
export class ExpenseFunctions {
@Function()
public async estimatedDepartmentExpenses(): Promise<ThreeDimensionalAggregation<string, IRange<Timestamp>, Double>> {
const result = await Objects.search().expenses()
.groupBy(expense => expense.departmentName.topValues())
.segmentBy(expense => expense.date.byMonth())
.sum(expense => expense.amount);
const modifiedBuckets = result.buckets.map(department => {
let latest: IBaseBucket<IRange<Timestamp>, Double> | undefined;
let latestEnd: Timestamp | undefined;
for (const month of department.value) {
const end = month.key.max;
if (end === undefined) throw new UserFacingError("월 버킷의 끝 날짜가 필요합니다.");
if (latestEnd === undefined || end.getTime() > latestEnd.getTime()) {
latest = month;
latestEnd = end;
}
}
const forecast: IBaseBucket<IRange<Timestamp>, Double>[] = [];
if (latest !== undefined && latestEnd !== undefined) {
let currentMonth = latestEnd;
for (let index = 0; index < 6; index++) {
const nextMonth = currentMonth.plusMonths(1);
forecast.push({
key: { min: currentMonth, max: nextMonth },
value: latest.value,
});
currentMonth = nextMonth;
}
}
return { key: department.key, value: forecast };
});
return { buckets: modifiedBuckets };
}
}
클래스를 index.ts에서 내보내고 게시하면 Workshop 차트에서 부서와 월을 축으로 소비할 수 있습니다. 예측 값은 마지막 관측 월의 합계 그대로이며 추세, 계절성이나 미완료 월을 보정하는 통계 모델은 아닙니다. 마지막 월에 일부 날짜만 들어 있다면 그 부분 합계를 여섯 달에 반복하므로 업무상 사용할 기준 기간을 정해야 합니다.
언어별 결과 구조
TSv1은 바깥 buckets와 안쪽 value로 중첩을 나타냅니다. TSv2 aggregate는 평평한 행을 반환하므로 같은 의미의 집계를 반환하려면 안쪽 groups 구조로 묶어야 합니다. Python은 NestedBucket과 SingleBucket을 사용하며 Python 월별 집계에서 날짜별 집계를 월합계로 묶는 과정을 설명합니다.