Cache Metrics
Evaluating a metric can be computationally expensive, in which case the metric can take a while to be evaluated.
You can improve the user experience and save compute resources by caching a Simple Metric result.
The first time the metric is evaluated, the result is stored in a cache. After that, the cached value is returned; thus, avoiding computing the metric again. For the cache to be automatically invalidated upon arrival of changes of the underlying metric's data, MetricDependency must include this metric as an entry.
See the cache field on the SimpleMetric Type for more info on updating MetricDependency.
Define a metric with cache
To cache a Simple Metric, add the cache field to the metric definition:
{
"id": "AveragePower_SmartBulb",
"name": "AveragePower",
"srcType": "SmartBulb",
"description": "Average power over time of the smart bulb",
"path": "bulbMeasurements",
"expression": "avg(avg(normalized.data.power))",
"cache": {
"intervals": ["DAY", "MONTH"],
"monthsInPast": 4,
"monthsInFuture": 1
}
}In this example, the metric is cached at both the day and month intervals for the past four months, and one month in the future. Refer to the SimpleMetricCacheSpec Type to learn more about the cache configuration.
You cannot pass a timeZone other than NONE, see TimeInfo. The default timezone is NONE. If it were not NONE, the platform would need to cache at different intervals, which would be computationally expensive. The metrics must be cached in UTC.
Check if a metric is cached
You can check if a specific interval has been cached or not:
metric = SimpleMetric.forId("exampleMetricId");
metric.cacheRange("exampleInstanceId", Interval.HOUR)Invalidate a cached metric
You can also invalidate a cached metric result:
mis = MetricInvalidationSpec.make({
metricName: "exampleMetric",
objId: "exampleInstanceId",
timeRanges: [{
start: "2021-01-01T00:00:00",
end: "2021-02-01T00:00:00"
}],
typeId: TypeId.fetch({filter: "typeName == 'exampleType'"}).objs[0]
});
specAry = MetricInvalidationSpec.array();
specAry.push(mis)
// see doc on invalidateCache for more details
SimpleMetric.invalidateCache(specAry);For more information about the invalidateCache on a SimpleMetric visit SimpleMetric.
An alternative to using metric caching is the feature store. More information about the C3 AI Feature Store can be found in the Feature Store document.