From d507cfe820dc7b8fc5e54d18207bbc1bcdf83a37 Mon Sep 17 00:00:00 2001 From: Paul Yang Date: Tue, 1 Oct 2024 23:49:51 -0700 Subject: [PATCH] Cache `SemanticModelLookup.get_defined_time_granularity()` (#1437) The defined time granularity of a time dimension is frequently called during query resolution to figure out the time granularity for an ambiguous group-by item. --- .../model/semantics/semantic_model_lookup.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/metricflow-semantics/metricflow_semantics/model/semantics/semantic_model_lookup.py b/metricflow-semantics/metricflow_semantics/model/semantics/semantic_model_lookup.py index 2a843c9d03..91ec266172 100644 --- a/metricflow-semantics/metricflow_semantics/model/semantics/semantic_model_lookup.py +++ b/metricflow-semantics/metricflow_semantics/model/semantics/semantic_model_lookup.py @@ -64,6 +64,9 @@ def __init__(self, model: SemanticManifest, custom_granularities: Dict[str, Expa for semantic_model in sorted(model.semantic_models, key=lambda semantic_model: semantic_model.name): self._add_semantic_model(semantic_model) + # Cache for defined time granularity. + self._time_dimension_to_defined_time_granularity: Dict[TimeDimensionReference, TimeGranularity] = {} + def get_dimension_references(self) -> Sequence[DimensionReference]: """Retrieve all dimension references from the collection of semantic models.""" return tuple(self._dimension_index.keys()) @@ -378,6 +381,16 @@ def get_agg_time_dimension_specs_for_measure( def get_defined_time_granularity(self, time_dimension_reference: TimeDimensionReference) -> TimeGranularity: """Time granularity from the time dimension's YAML definition. If not set, defaults to DAY.""" + result = self._time_dimension_to_defined_time_granularity.get(time_dimension_reference) + + if result is not None: + return result + + result = self._get_defined_time_granularity(time_dimension_reference) + self._time_dimension_to_defined_time_granularity[time_dimension_reference] = result + return result + + def _get_defined_time_granularity(self, time_dimension_reference: TimeDimensionReference) -> TimeGranularity: time_dimension = self.get_dimension(time_dimension_reference) defined_time_granularity = DEFAULT_TIME_GRANULARITY