Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# A categorical Data Insights axis lists only the categories its chart counts

- **Status:** Accepted
- **Revisions:** v1 2026-11-16 (initial)
- **Deciders:** pmbrull
- **Guard:** `OpenSearchCategoricalAxisRealEngineTest` and `ElasticSearchCategoricalAxisRealEngineTest` (`theAxisHoldsExactlyTheServicesTheChartCounts`, `aServiceTheChartCountsKeepsItsBucketWhenTheMetricFindsNothingThere`, `aMetricReportsZeroForAServiceOnlyAnotherMetricCounts`, `aGroupedChartListsOnlyTheGroupsItsMetricCounts`, `aBuiltInChartReadForOneServiceListsOnlyThatService`); `OpenSearchLineChartAggregatorTest` and `ElasticSearchLineChartAggregatorTest` (`aFilteredCategoricalChartQueriesOnlyTheDocumentsItCounts`, `metricsThatDisagreeQueryTheDocumentsEitherCounts`, `aMetricWithoutAFilterKeepsTheRequestWide`, `aTimestampAxisIsNeitherRankedNorNarrowed`); `DataInsightMetricFilterTest` (`aMetricThatCountsEveryDocumentLeavesNoPopulation`)
- **Related:** #32115, open-metadata/ai-platform#2269

## Context

A categorical (terms) x-axis bucketed every document in range and applied each metric's `filter`
only inside the bucket. #32115 ranked the axis by that filter, so the categories a chart counts are
picked first. It kept the request wide so that a category the filter empties still reports 0.

When the filter is the chart's scope, those zero rows are categories held only outside the scope.
For example, a "tables per owner" chart listed every owner of a dashboard at 0. On one instance,
28 of its 45 rows were such zeros, and an AI chat answer built on the chart said 45 owners hold
tables when 17 do. These zeros never formed a complete list either:
- they appeared only while fewer than 100 categories held matching documents;
- which ones appeared depended on how the engine broke ties;
- a category that no document of the day holds never appeared at all.

## Decision

For a categorical x-axis, the request queries the chart's population: the documents that at least
one metric's `filter` matches (`DataInsightMetricFilter.populationFilters`). That is one `should`
clause per distinct filter, with `minimum_should_match: 1`, combined with the snapshot range when
the request is not live.

- **A category the chart counts keeps its bucket.** A term's own `q=` never narrows the population,
so a real 0 stays. With several metrics, a metric reads 0 for a category that only another metric
counts.
- **A `groupBy` on a categorical chart draws its groups from the same population.**
- **A metric with no filter counts every document**, so the request stays wide. An unreadable filter
counts as no filter, as before.
- **An `@timestamp` axis stays wide, groups included.** A date histogram has no top N to align, and
narrowing it would move the first and last days it plots.

## Consequences

- Breakdowns with metric filters stop showing zero bars for categories outside their scope. That
covers custom charts, AI chat charts and Collate's pinned-chart refresh.
- **Built-in categorical charts are narrowed when read for a scope.** They declare no filter of
their own, but `DataInsightSystemChartRepository` merges the caller's filter and the navbar domain
into every metric. So a built-in chart read for one service or domain no longer lists other
services, tag groups or entity types at 0. That applies to the service page's PII and tier
distributions, and to the total data assets chart under a domain.
- **A scope that matches no document returns no buckets**, instead of a breakdown of zeros.
- **A filter can carry a condition rather than a scope.** Collate's chart builder in function mode
puts its advanced filter in `metrics[i].filter`. In that case a category where nothing matches the
condition gets no bucket. To keep its 0, use formula mode: the scope goes in `filter` and the
condition in the formula's `q=`.
- A complete list of categories, such as every tier whether held or not, needs an explicit list of
values. A terms axis cannot provide one.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Objects;
import org.openmetadata.schema.dataInsight.custom.LineChartMetric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -30,6 +33,19 @@ public final class DataInsightMetricFilter {

private DataInsightMetricFilter() {}

/**
* Distinct query JSON of every metric's filter: the documents a categorical axis draws its
* categories from. Empty when a metric has no readable filter, because that metric counts every
* document (ADR:2026-11-16-a-categorical-axis-lists-only-the-categories-its-chart-counts).
*/
public static List<String> populationFilters(List<LineChartMetric> metrics) {
List<String> filters =
metrics.stream().map(metric -> queryJson(metric.getFilter())).distinct().toList();
boolean everyMetricIsFiltered =
!filters.isEmpty() && filters.stream().noneMatch(Objects::isNull);
return everyMetricIsFiltered ? filters : List.of();
}

/**
* JSON text of the filter's {@code query} node, or null when the filter is absent, empty or
* unparseable. The {@code "{}"} comparison is an exact string match, which is what the inline
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import org.openmetadata.common.utils.CommonUtil;
import org.openmetadata.schema.dataInsight.custom.DataInsightCustomChart;
Expand All @@ -26,6 +27,7 @@
import org.openmetadata.schema.dataInsight.custom.LineChartMetric;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.jdbi3.DataInsightSystemChartRepository;
import org.openmetadata.service.search.DataInsightMetricFilter;

public class ElasticSearchLineChartAggregator
implements ElasticSearchDynamicChartAggregatorInterface {
Expand Down Expand Up @@ -53,8 +55,9 @@ public MetricFormulaHolder(String formula, List<FormulaHolder> holders) {
* <p>Ranking on the wrapper's document count rather than the metric's own value is what makes
* this safe for every function: an empty {@code min} reads as larger than any real minimum and an
* empty {@code sum} is zero, so ordering by either would float the empty categories to the top. A
* document count is never negative, and is zero exactly when the category matched nothing, which
* keeps those categories in the response but last, where they cannot displace one that has data.
* document count is never negative, and is zero exactly when the wrapper matched nothing in that
* category: another metric counts it, or this metric's {@code q=} finds nothing there. Such a
* category sorts last, where it cannot displace one that has data.
*/
private static ObjectBuilder<TermsAggregation> termsAxis(
TermsAggregation.Builder builder,
Expand All @@ -81,6 +84,32 @@ private static ObjectBuilder<Aggregation> withSubAggregations(
return subAggregations.isEmpty() ? container : container.aggregations(subAggregations);
}

/** Whether the x-axis holds categories rather than the snapshot timeline. */
private static boolean hasCategoricalAxis(LineChart lineChart) {
return lineChart.getxAxisField() != null
&& !lineChart.getxAxisField().equals(DataInsightSystemChartRepository.TIMESTAMP_FIELD);
}

/** The documents some metric counts, or null when a metric counts every document. */
private static Query chartPopulation(List<LineChartMetric> metrics) {
List<String> filters = DataInsightMetricFilter.populationFilters(metrics);
return filters.isEmpty() ? null : anyOf(filters);
}

private static Query anyOf(List<String> filters) {
List<Query> clauses =
filters.stream().map(ElasticSearchDynamicChartAggregatorInterface::queryFromJson).toList();
return clauses.size() == 1
? clauses.get(0)
: Query.of(q -> q.bool(b -> b.should(clauses).minimumShouldMatch("1")));
Comment on lines +99 to +104

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Helpers miss Java requirements

The new helpers violate three directives in CLAUDE.md: use getFirst() instead of get(0), mark unchanged locals and parameters final, and share logic that does not depend on the engine. Both engines repeat this pattern.

Update anyOf to follow the collection and final rules, and move the duplicated hasCategoricalAxis check into a shared helper. These repository requirements must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

}

private static Query withinPopulation(Query range, Query population) {
return population == null
? range
: Query.of(q -> q.bool(b -> b.filter(range).filter(population)));
}

@Override
public SearchRequest prepareSearchRequest(
@NotNull DataInsightCustomChart diChart,
Expand Down Expand Up @@ -125,8 +154,7 @@ public SearchRequest prepareSearchRequest(
metricName,
formulas);

if (lineChart.getxAxisField() != null
&& !lineChart.getxAxisField().equals(DataInsightSystemChartRepository.TIMESTAMP_FIELD)) {
if (hasCategoricalAxis(lineChart)) {
metricAggregations.put(
metricName,
Aggregation.of(
Expand Down Expand Up @@ -198,6 +226,9 @@ public SearchRequest prepareSearchRequest(

SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder().size(0);
final long finalStartTime = startTime;
// After the loop, so a filter populateDateHistogram refused has already failed the request.
Query population =
hasCategoricalAxis(lineChart) ? chartPopulation(lineChart.getMetrics()) : null;
if (!live) {
Query rangeQuery =
Query.of(
Expand All @@ -214,9 +245,10 @@ public SearchRequest prepareSearchRequest(
es.co.elastic.clients.json.JsonData.of(
String.valueOf(end))))));

searchRequestBuilder.query(rangeQuery);
searchRequestBuilder.query(withinPopulation(rangeQuery, population));
searchRequestBuilder.index(DataInsightSystemChartRepository.getDataInsightsSearchIndex());
} else {
Optional.ofNullable(population).ifPresent(searchRequestBuilder::query);
searchRequestBuilder.index(
DataInsightSystemChartRepository.getLiveSearchIndex(lineChart.getSearchIndex()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import org.openmetadata.common.utils.CommonUtil;
import org.openmetadata.schema.dataInsight.custom.DataInsightCustomChart;
Expand All @@ -14,6 +15,7 @@
import org.openmetadata.schema.dataInsight.custom.LineChartMetric;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.jdbi3.DataInsightSystemChartRepository;
import org.openmetadata.service.search.DataInsightMetricFilter;
import os.org.opensearch.client.json.JsonData;
import os.org.opensearch.client.opensearch._types.SortOrder;
import os.org.opensearch.client.opensearch._types.aggregations.Aggregate;
Expand Down Expand Up @@ -50,8 +52,9 @@ public MetricFormulaHolder(String formula, List<FormulaHolder> holders) {
* <p>Ranking on the wrapper's document count rather than the metric's own value is what makes
* this safe for every function: an empty {@code min} reads as larger than any real minimum and an
* empty {@code sum} is zero, so ordering by either would float the empty categories to the top. A
* document count is never negative, and is zero exactly when the category matched nothing, which
* keeps those categories in the response but last, where they cannot displace one that has data.
* document count is never negative, and is zero exactly when the wrapper matched nothing in that
* category: another metric counts it, or this metric's {@code q=} finds nothing there. Such a
* category sorts last, where it cannot displace one that has data.
*/
private static ObjectBuilder<TermsAggregation> termsAxis(
TermsAggregation.Builder builder,
Expand All @@ -78,6 +81,32 @@ private static ObjectBuilder<Aggregation> withSubAggregations(
return subAggregations.isEmpty() ? container : container.aggregations(subAggregations);
}

/** Whether the x-axis holds categories rather than the snapshot timeline. */
private static boolean hasCategoricalAxis(LineChart lineChart) {
return lineChart.getxAxisField() != null
&& !lineChart.getxAxisField().equals(DataInsightSystemChartRepository.TIMESTAMP_FIELD);
}

/** The documents some metric counts, or null when a metric counts every document. */
private static Query chartPopulation(List<LineChartMetric> metrics) {
List<String> filters = DataInsightMetricFilter.populationFilters(metrics);
return filters.isEmpty() ? null : anyOf(filters);
}

private static Query anyOf(List<String> filters) {
List<Query> clauses =
filters.stream().map(OpenSearchDynamicChartAggregatorInterface::queryFromJson).toList();
return clauses.size() == 1
? clauses.get(0)
: Query.of(q -> q.bool(b -> b.should(clauses).minimumShouldMatch("1")));
}

private static Query withinPopulation(Query range, Query population) {
return population == null
? range
: Query.of(q -> q.bool(b -> b.filter(range).filter(population)));
}

@Override
public SearchRequest prepareSearchRequest(
@NotNull DataInsightCustomChart diChart,
Expand Down Expand Up @@ -122,8 +151,7 @@ public SearchRequest prepareSearchRequest(
metricName,
formulas);

if (lineChart.getxAxisField() != null
&& !lineChart.getxAxisField().equals(DataInsightSystemChartRepository.TIMESTAMP_FIELD)) {
if (hasCategoricalAxis(lineChart)) {
metricAggregations.put(
metricName,
Aggregation.of(
Expand Down Expand Up @@ -195,6 +223,9 @@ public SearchRequest prepareSearchRequest(

SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder().size(0);
final long finalStartTime = startTime;
// After the loop, so a filter populateDateHistogram refused has already failed the request.
Query population =
hasCategoricalAxis(lineChart) ? chartPopulation(lineChart.getMetrics()) : null;
if (!live) {
Query rangeQuery =
Query.of(
Expand All @@ -205,9 +236,10 @@ public SearchRequest prepareSearchRequest(
.gte(JsonData.of(finalStartTime))
.lte(JsonData.of(end))));

searchRequestBuilder.query(rangeQuery);
searchRequestBuilder.query(withinPopulation(rangeQuery, population));
searchRequestBuilder.index(DataInsightSystemChartRepository.getDataInsightsSearchIndex());
} else {
Optional.ofNullable(population).ifPresent(searchRequestBuilder::query);
searchRequestBuilder.index(
DataInsightSystemChartRepository.getLiveSearchIndex(lineChart.getSearchIndex()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.openmetadata.schema.dataInsight.custom.LineChartMetric;

/**
* Both engines fall back to an unfiltered aggregation on a filter they cannot read, so this parser
Expand Down Expand Up @@ -38,6 +42,32 @@ void absentEmptyOrUnreadableFiltersYieldNothing() {
assertNull(DataInsightMetricFilter.queryJson("{"), "unparseable");
}

@Test
void aPopulationHasOneFilterPerDistinctMetricFilter() {
List<String> population =
DataInsightMetricFilter.populationFilters(
metricsFiltering(
"{\"query\":{\"term\":{\"a\":\"b\"}}}",
"{ \"query\" : { \"term\" : { \"a\" : \"b\" } } }",
"{\"query\":{\"term\":{\"a\":\"c\"}}}"));

assertEquals(List.of("{\"term\":{\"a\":\"b\"}}", "{\"term\":{\"a\":\"c\"}}"), population);
}

@Test
void aMetricThatCountsEveryDocumentLeavesNoPopulation() {
// One metric without a readable filter counts the whole index, so no category is outside the
// chart and a categorical axis must stay wide.
String table = "{\"query\":{\"term\":{\"entityType.keyword\":\"table\"}}}";
assertTrue(DataInsightMetricFilter.populationFilters(metricsFiltering(table, null)).isEmpty());
assertTrue(DataInsightMetricFilter.populationFilters(metricsFiltering(table, "{")).isEmpty());
assertTrue(DataInsightMetricFilter.populationFilters(List.of()).isEmpty());
}

private static List<LineChartMetric> metricsFiltering(String... filters) {
return Arrays.stream(filters).map(filter -> new LineChartMetric().withFilter(filter)).toList();
}

@Test
void theOrderKeyPrefixCannotContainADot() {
// An order path splits on '.' into an aggregation and a metric sub-field, and the engine
Expand Down
Loading
Loading