use of io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics in project trino by trinodb.
the class TestDeltaLakeWriter method testMergeFloatNaNStatistics.
@Test
public void testMergeFloatNaNStatistics() {
String columnName = "t_float";
PrimitiveType type = new PrimitiveType(Type.Repetition.REQUIRED, PrimitiveType.PrimitiveTypeName.FLOAT, columnName);
List<ColumnChunkMetaData> metadata = ImmutableList.of(createMetaData(columnName, type, 10, Statistics.getBuilderForReading(type).withMin(getFloatByteArray(0.01f)).withMax(getFloatByteArray(1.0f)).withNumNulls(6).build()), createMetaData(columnName, type, 10, Statistics.getBuilderForReading(type).withMin(getFloatByteArray(Float.NaN)).withMax(getFloatByteArray(1.0f)).withNumNulls(6).build()), createMetaData(columnName, type, 10, Statistics.getBuilderForReading(type).withMin(getFloatByteArray(-2.001f)).withMax(getFloatByteArray(0.0f)).withNumNulls(7).build()));
DeltaLakeColumnHandle floatColumn = new DeltaLakeColumnHandle(columnName, REAL, REGULAR);
DeltaLakeFileStatistics fileStats = mergeStats(buildMultimap(columnName, metadata), ImmutableMap.of(columnName, REAL), 20);
assertEquals(fileStats.getNumRecords(), Optional.of(20L));
assertEquals(fileStats.getMinColumnValue(floatColumn), Optional.empty());
assertEquals(fileStats.getMaxColumnValue(floatColumn), Optional.empty());
assertEquals(fileStats.getNullCount(columnName), Optional.empty());
}
use of io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics in project trino by trinodb.
the class TestDeltaLakeWriter method testMergeStringStatistics.
@Test
public void testMergeStringStatistics() {
String columnName = "t_string";
PrimitiveType type = new PrimitiveType(Type.Repetition.REQUIRED, PrimitiveType.PrimitiveTypeName.BINARY, columnName);
List<ColumnChunkMetaData> metadata = ImmutableList.of(createMetaData(columnName, type, 10, Statistics.getBuilderForReading(type).withMin("aba".getBytes(UTF_8)).withMax("ab⌘".getBytes(UTF_8)).withNumNulls(6).build()), createMetaData(columnName, type, 10, Statistics.getBuilderForReading(type).withMin("aba".getBytes(UTF_8)).withMax("abc".getBytes(UTF_8)).withNumNulls(6).build()));
DeltaLakeColumnHandle varcharColumn = new DeltaLakeColumnHandle(columnName, VarcharType.createUnboundedVarcharType(), REGULAR);
DeltaLakeFileStatistics fileStats = mergeStats(buildMultimap(columnName, metadata), ImmutableMap.of(columnName, createUnboundedVarcharType()), 20);
assertEquals(fileStats.getNumRecords(), Optional.of(20L));
assertEquals(fileStats.getMinColumnValue(varcharColumn), Optional.of(utf8Slice("aba")));
assertEquals(fileStats.getMaxColumnValue(varcharColumn), Optional.of(utf8Slice("ab⌘")));
assertEquals(fileStats.getNullCount(columnName), Optional.of(12L));
}
use of io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics in project trino by trinodb.
the class HiveMetastoreBackedDeltaLakeMetastore method getTableStatistics.
@Override
public TableStatistics getTableStatistics(ConnectorSession session, DeltaLakeTableHandle tableHandle, Constraint constraint) {
TableSnapshot tableSnapshot = getSnapshot(tableHandle.getSchemaTableName(), session);
double numRecords = 0L;
MetadataEntry metadata = transactionLogAccess.getMetadataEntry(tableSnapshot, session).orElseThrow(() -> new TrinoException(DELTA_LAKE_INVALID_SCHEMA, "Metadata not found in transaction log for " + tableHandle.getTableName()));
List<ColumnMetadata> columnMetadata = DeltaLakeSchemaSupport.extractSchema(metadata, typeManager);
List<DeltaLakeColumnHandle> columns = columnMetadata.stream().map(columnMeta -> new DeltaLakeColumnHandle(columnMeta.getName(), columnMeta.getType(), metadata.getCanonicalPartitionColumns().contains(columnMeta.getName()) ? PARTITION_KEY : REGULAR)).collect(toImmutableList());
Map<DeltaLakeColumnHandle, Double> nullCounts = new HashMap<>();
columns.forEach(column -> nullCounts.put(column, 0.0));
Map<DeltaLakeColumnHandle, Double> minValues = new HashMap<>();
Map<DeltaLakeColumnHandle, Double> maxValues = new HashMap<>();
Map<DeltaLakeColumnHandle, Set<String>> partitioningColumnsDistinctValues = new HashMap<>();
columns.stream().filter(column -> column.getColumnType() == PARTITION_KEY).forEach(column -> partitioningColumnsDistinctValues.put(column, new HashSet<>()));
if (tableHandle.getEnforcedPartitionConstraint().isNone() || tableHandle.getNonPartitionConstraint().isNone() || constraint.getSummary().isNone()) {
return createZeroStatistics(columns);
}
Set<String> predicatedColumnNames = tableHandle.getNonPartitionConstraint().getDomains().orElseThrow().keySet().stream().map(DeltaLakeColumnHandle::getName).collect(toImmutableSet());
List<ColumnMetadata> predicatedColumns = columnMetadata.stream().filter(column -> predicatedColumnNames.contains(column.getName())).collect(toImmutableList());
for (AddFileEntry addEntry : transactionLogAccess.getActiveFiles(tableSnapshot, session)) {
Optional<? extends DeltaLakeFileStatistics> fileStatistics = addEntry.getStats();
if (fileStatistics.isEmpty()) {
// Open source Delta Lake does not collect stats
return TableStatistics.empty();
}
DeltaLakeFileStatistics stats = fileStatistics.get();
if (!partitionMatchesPredicate(addEntry.getCanonicalPartitionValues(), tableHandle.getEnforcedPartitionConstraint().getDomains().orElseThrow())) {
continue;
}
TupleDomain<DeltaLakeColumnHandle> statisticsPredicate = createStatisticsPredicate(addEntry, predicatedColumns, tableHandle.getMetadataEntry().getCanonicalPartitionColumns());
if (!tableHandle.getNonPartitionConstraint().overlaps(statisticsPredicate)) {
continue;
}
if (stats.getNumRecords().isEmpty()) {
// Not clear if it's possible for stats to be present with no row count, but bail out if that happens
return TableStatistics.empty();
}
numRecords += stats.getNumRecords().get();
for (DeltaLakeColumnHandle column : columns) {
if (column.getColumnType() == PARTITION_KEY) {
Optional<String> partitionValue = addEntry.getCanonicalPartitionValues().get(column.getName());
if (partitionValue.isEmpty()) {
nullCounts.merge(column, (double) stats.getNumRecords().get(), Double::sum);
} else {
// NULL is not counted as a distinct value
// Code below assumes that values returned by addEntry.getCanonicalPartitionValues() are normalized,
// it may not be true in case of real, doubles, timestamps etc
partitioningColumnsDistinctValues.get(column).add(partitionValue.get());
}
} else {
Optional<Long> maybeNullCount = stats.getNullCount(column.getName());
if (maybeNullCount.isPresent()) {
nullCounts.put(column, nullCounts.get(column) + maybeNullCount.get());
} else {
// If any individual file fails to report null counts, fail to calculate the total for the table
nullCounts.put(column, NaN);
}
}
// Math.min returns NaN if any operand is NaN
stats.getMinColumnValue(column).map(parsedValue -> toStatsRepresentation(column.getType(), parsedValue)).filter(OptionalDouble::isPresent).map(OptionalDouble::getAsDouble).ifPresent(parsedValueAsDouble -> minValues.merge(column, parsedValueAsDouble, Math::min));
stats.getMaxColumnValue(column).map(parsedValue -> toStatsRepresentation(column.getType(), parsedValue)).filter(OptionalDouble::isPresent).map(OptionalDouble::getAsDouble).ifPresent(parsedValueAsDouble -> maxValues.merge(column, parsedValueAsDouble, Math::max));
}
}
if (numRecords == 0) {
return createZeroStatistics(columns);
}
TableStatistics.Builder statsBuilder = new TableStatistics.Builder().setRowCount(Estimate.of(numRecords));
Optional<DeltaLakeStatistics> statistics = Optional.empty();
if (isExtendedStatisticsEnabled(session)) {
statistics = statisticsAccess.readDeltaLakeStatistics(session, tableHandle.getLocation());
}
for (DeltaLakeColumnHandle column : columns) {
ColumnStatistics.Builder columnStatsBuilder = new ColumnStatistics.Builder();
Double nullCount = nullCounts.get(column);
columnStatsBuilder.setNullsFraction(nullCount.isNaN() ? Estimate.unknown() : Estimate.of(nullCount / numRecords));
Double maxValue = maxValues.get(column);
Double minValue = minValues.get(column);
if (isValidInRange(maxValue) && isValidInRange(minValue)) {
columnStatsBuilder.setRange(new DoubleRange(minValue, maxValue));
} else if (isValidInRange(maxValue)) {
columnStatsBuilder.setRange(new DoubleRange(NEGATIVE_INFINITY, maxValue));
} else if (isValidInRange(minValue)) {
columnStatsBuilder.setRange(new DoubleRange(minValue, POSITIVE_INFINITY));
}
// extend statistics with NDV
if (column.getColumnType() == PARTITION_KEY) {
columnStatsBuilder.setDistinctValuesCount(Estimate.of(partitioningColumnsDistinctValues.get(column).size()));
}
if (statistics.isPresent()) {
DeltaLakeColumnStatistics deltaLakeColumnStatistics = statistics.get().getColumnStatistics().get(column.getName());
if (deltaLakeColumnStatistics != null && column.getColumnType() != PARTITION_KEY) {
columnStatsBuilder.setDistinctValuesCount(Estimate.of(deltaLakeColumnStatistics.getNdvSummary().cardinality()));
}
}
statsBuilder.setColumnStatistics(column, columnStatsBuilder.build());
}
return statsBuilder.build();
}
use of io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics in project trino by trinodb.
the class AbstractTestDeltaLakeCreateTableStatistics method testDateRecords.
@Test
public void testDateRecords() throws IOException {
String columnName = "t_date";
DeltaLakeColumnHandle columnHandle = new DeltaLakeColumnHandle(columnName, DateType.DATE, REGULAR);
try (TestTable table = new TestTable("test_date_records_", ImmutableList.of(columnName), "VALUES DATE '2011-08-08', DATE '2012-08-08', DATE '2013-08-08', DATE '2013-08-09'")) {
List<AddFileEntry> addFileEntries = getAddFileEntries(table.getName());
AddFileEntry entry = getOnlyElement(addFileEntries);
assertThat(entry.getStats()).isPresent();
DeltaLakeFileStatistics fileStatistics = entry.getStats().get();
assertEquals(fileStatistics.getNumRecords(), Optional.of(4L));
assertEquals(fileStatistics.getMinColumnValue(columnHandle), Optional.of(LocalDate.parse("2011-08-08").toEpochDay()));
assertEquals(fileStatistics.getMaxColumnValue(columnHandle), Optional.of(LocalDate.parse("2013-08-09").toEpochDay()));
assertEquals(fileStatistics.getNullCount(columnName), Optional.of(0L));
}
}
use of io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics in project trino by trinodb.
the class AbstractTestDeltaLakeCreateTableStatistics method testPartitionedTable.
@Test
public void testPartitionedTable() throws IOException {
String columnName = "t_string";
DeltaLakeColumnHandle columnHandle = new DeltaLakeColumnHandle(columnName, createUnboundedVarcharType(), REGULAR);
String partitionColumn = "t_int";
try (TestTable table = new TestTable("test_partitioned_table_", ImmutableList.of(columnName, partitionColumn), ImmutableList.of(partitionColumn), "VALUES ('a', 1), ('b', 1), ('c', 1), ('c', 2), ('d', 2), ('e', 2), (null, 1)")) {
List<AddFileEntry> addFileEntries = getAddFileEntries(table.getName());
assertEquals(addFileEntries.size(), 2);
for (AddFileEntry addFileEntry : addFileEntries) {
assertThat(addFileEntry.getStats()).isPresent();
DeltaLakeFileStatistics fileStatistics = addFileEntry.getStats().get();
if (addFileEntry.getPartitionValues().get(partitionColumn).equals("1")) {
assertEquals(fileStatistics.getMinColumnValue(columnHandle), Optional.of(utf8Slice("a")));
assertEquals(fileStatistics.getMaxColumnValue(columnHandle), Optional.of(utf8Slice("c")));
assertEquals(fileStatistics.getNumRecords(), Optional.of(4L));
assertEquals(fileStatistics.getNullCount(columnName), Optional.of(1L));
} else if (addFileEntry.getPartitionValues().get(partitionColumn).equals("2")) {
assertEquals(fileStatistics.getMinColumnValue(columnHandle), Optional.of(utf8Slice("c")));
assertEquals(fileStatistics.getMaxColumnValue(columnHandle), Optional.of(utf8Slice("e")));
assertEquals(fileStatistics.getNumRecords(), Optional.of(3L));
assertEquals(fileStatistics.getNullCount(columnName), Optional.of(0L));
}
}
}
}
Aggregations