szehon-ho commented on code in PR #10288:
URL: https://github.com/apache/iceberg/pull/10288#discussion_r1663188357


##########
api/src/main/java/org/apache/iceberg/actions/AnalyzeTable.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.actions;
+
+import org.apache.iceberg.StatisticsFile;
+
+/** An action that collects statistics of an Iceberg table and writes to 
Puffin files. */
+public interface AnalyzeTable extends Action<AnalyzeTable, 
AnalyzeTable.Result> {
+  /**
+   * The set of columns to be analyzed
+   *
+   * @param columns a set of column names to be analyzed
+   * @return this for method chaining
+   */
+  AnalyzeTable columns(String... columns);
+
+  /**
+   * Id of the snapshot for which stats need to be collected

Review Comment:
   Choose the snapshot of the table to analyze



##########
spark/v3.5/spark/src/test/java/org/apache/iceberg/spark/actions/TestAnalyzeTableAction.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.actions;
+
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+import java.util.List;
+import org.apache.iceberg.BlobMetadata;
+import org.apache.iceberg.StatisticsFile;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.actions.AnalyzeTable;
+import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.CatalogTestBase;
+import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.source.SimpleRecord;
+import org.apache.spark.sql.Encoders;
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
+import org.apache.spark.sql.catalyst.parser.ParseException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+public class TestAnalyzeTableAction extends CatalogTestBase {
+
+  @TestTemplate
+  public void testAnalyzeTableAction() throws NoSuchTableException, 
ParseException {
+    assumeTrue(catalogName.equals("spark_catalog"));
+    sql("CREATE TABLE %s (id int, data string) USING iceberg", tableName);
+
+    List<SimpleRecord> records =
+        Lists.newArrayList(
+            new SimpleRecord(1, "a"),
+            new SimpleRecord(1, "a"),
+            new SimpleRecord(2, "b"),
+            new SimpleRecord(3, "c"),
+            new SimpleRecord(4, "d"));
+    spark
+        .createDataset(records, Encoders.bean(SimpleRecord.class))
+        .coalesce(1)
+        .writeTo(tableName)
+        .append();
+    Table table = Spark3Util.loadIcebergTable(spark, tableName);
+    SparkActions actions = SparkActions.get();
+    AnalyzeTable.Result results = actions.analyzeTable(table).columns("id", 
"data").execute();
+    assertNotNull(results);
+
+    List<StatisticsFile> statisticsFiles = table.statisticsFiles();
+    Assertions.assertEquals(statisticsFiles.size(), 1);
+
+    StatisticsFile statisticsFile = statisticsFiles.get(0);
+    assertNotEquals(statisticsFile.fileSizeInBytes(), 0);
+    Assertions.assertEquals(statisticsFile.blobMetadata().size(), 2);
+
+    BlobMetadata blobMetadata = statisticsFile.blobMetadata().get(0);
+    Assertions.assertEquals(
+        
blobMetadata.properties().get(NDVSketchGenerator.APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY),
+        String.valueOf(4));
+  }
+
+  @TestTemplate
+  public void testAnalyzeTableActionWithoutExplicitColumns()
+      throws NoSuchTableException, ParseException {
+    assumeTrue(catalogName.equals("spark_catalog"));
+    sql("CREATE TABLE %s (id int, data string) USING iceberg", tableName);
+
+    List<SimpleRecord> records =
+        Lists.newArrayList(
+            new SimpleRecord(1, "a"),
+            new SimpleRecord(2, "b"),
+            new SimpleRecord(3, "c"),
+            new SimpleRecord(4, "d"));
+    spark
+        .createDataset(records, Encoders.bean(SimpleRecord.class))
+        .coalesce(1)
+        .writeTo(tableName)
+        .append();
+    Table table = Spark3Util.loadIcebergTable(spark, tableName);
+    SparkActions actions = SparkActions.get();
+    AnalyzeTable.Result results = actions.analyzeTable(table).execute();
+    assertNotNull(results);
+
+    Assertions.assertEquals(1, table.statisticsFiles().size());
+    StatisticsFile statisticsFile = table.statisticsFiles().get(0);
+    Assertions.assertEquals(2, statisticsFile.blobMetadata().size());
+    assertNotEquals(0, statisticsFile.fileSizeInBytes());
+    assertNotEquals(
+        4,
+        statisticsFile
+            .blobMetadata()
+            .get(0)
+            .properties()
+            
.get(NDVSketchGenerator.APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY));
+    assertNotEquals(
+        4,
+        statisticsFile
+            .blobMetadata()
+            .get(1)
+            .properties()
+            
.get(NDVSketchGenerator.APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY));
+  }
+
+  @TestTemplate
+  public void testAnalyzeTableForInvalidColumns() throws NoSuchTableException, 
ParseException {
+    assumeTrue(catalogName.equals("spark_catalog"));
+    sql("CREATE TABLE %s (id int, data string) USING iceberg", tableName);
+    // Append data to create snapshot
+    sql("INSERT into %s values(1, 'abcd')", tableName);
+    Table table = Spark3Util.loadIcebergTable(spark, tableName);
+    SparkActions actions = SparkActions.get();
+    ValidationException validationException =
+        assertThrows(
+            ValidationException.class, () -> 
actions.analyzeTable(table).columns("id1").execute());
+    String message = validationException.getMessage();
+    assertTrue(message.contains("No column with id1 name in the table"));
+  }
+
+  @TestTemplate
+  public void testAnalyzeTableWithNoSnapshots() throws NoSuchTableException, 
ParseException {
+    assumeTrue(catalogName.equals("spark_catalog"));
+    sql("CREATE TABLE %s (id int, data string) USING iceberg", tableName);
+    Table table = Spark3Util.loadIcebergTable(spark, tableName);
+    SparkActions actions = SparkActions.get();
+    RuntimeException exception =
+        assertThrows(
+            RuntimeException.class, () -> 
actions.analyzeTable(table).columns("id").execute());
+    assertTrue(exception.getMessage().contains("Snapshot id is null"));

Review Comment:
   Probably need to change this message?



##########
api/src/main/java/org/apache/iceberg/actions/AnalyzeTable.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.actions;
+
+import org.apache.iceberg.StatisticsFile;
+
+/** An action that collects statistics of an Iceberg table and writes to 
Puffin files. */
+public interface AnalyzeTable extends Action<AnalyzeTable, 
AnalyzeTable.Result> {
+  /**
+   * The set of columns to be analyzed

Review Comment:
   Choose the set of columns to be analyzed, by default all columns are 
analyzed.



##########
spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/NDVSketchGenerator.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.actions;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.datasketches.theta.Sketch;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.puffin.Blob;
+import org.apache.iceberg.puffin.StandardBlobTypes;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.spark.SparkReadOptions;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Types;
+import org.apache.spark.api.java.JavaPairRDD;
+import org.apache.spark.sql.Column;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.SparkSession;
+import org.apache.spark.sql.functions;
+import scala.Tuple2;
+
+public class NDVSketchGenerator {
+
+  private NDVSketchGenerator() {}
+
+  public static final String APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY = "ndv";
+
+  static List<Blob> generateNDVSketchesAndBlobs(
+      SparkSession spark, Table table, long snapshotId, Set<String> 
columnsToBeAnalyzed) {
+    Map<Integer, ThetaSketchJavaSerializable> columnToSketchMap =
+        computeNDVSketches(spark, table, snapshotId, columnsToBeAnalyzed);
+    return generateBlobs(table, columnsToBeAnalyzed, columnToSketchMap, 
snapshotId);
+  }
+
+  private static List<Blob> generateBlobs(
+      Table table,
+      Set<String> columns,
+      Map<Integer, ThetaSketchJavaSerializable> sketchMap,
+      long snapshotId) {
+    return columns.stream()
+        .map(
+            columnName -> {
+              Types.NestedField field = table.schema().findField(columnName);
+              Sketch sketch = sketchMap.get(field.fieldId()).getSketch();
+              long ndv = (long) sketch.getEstimate();
+              return new Blob(
+                  StandardBlobTypes.APACHE_DATASKETCHES_THETA_V1,
+                  ImmutableList.of(field.fieldId()),
+                  snapshotId,
+                  table.snapshot(snapshotId).sequenceNumber(),
+                  ByteBuffer.wrap(sketch.toByteArray()),
+                  null,
+                  ImmutableMap.of(APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY, 
String.valueOf(ndv)));
+            })
+        .collect(Collectors.toList());
+  }
+
+  private static Map<Integer, ThetaSketchJavaSerializable> computeNDVSketches(
+      SparkSession spark, Table table, long snapshotId, Set<String> 
toBeAnalyzedColumns) {

Review Comment:
   Nit: columnsToBeAnalyzed to be consistent with above method



##########
api/src/main/java/org/apache/iceberg/actions/AnalyzeTable.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.actions;
+
+import org.apache.iceberg.StatisticsFile;
+
+/** An action that collects statistics of an Iceberg table and writes to 
Puffin files. */
+public interface AnalyzeTable extends Action<AnalyzeTable, 
AnalyzeTable.Result> {
+  /**
+   * The set of columns to be analyzed
+   *
+   * @param columns a set of column names to be analyzed
+   * @return this for method chaining
+   */
+  AnalyzeTable columns(String... columns);
+
+  /**
+   * Id of the snapshot for which stats need to be collected
+   *
+   * @param snapshotId long id of the snapshot for which stats need to be 
collected

Review Comment:
   'to be collected' => 'analyzed' to be consistent with previous javadoc?



##########
api/src/main/java/org/apache/iceberg/actions/AnalyzeTable.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.actions;
+
+import org.apache.iceberg.StatisticsFile;
+
+/** An action that collects statistics of an Iceberg table and writes to 
Puffin files. */
+public interface AnalyzeTable extends Action<AnalyzeTable, 
AnalyzeTable.Result> {
+  /**
+   * The set of columns to be analyzed
+   *
+   * @param columns a set of column names to be analyzed
+   * @return this for method chaining
+   */
+  AnalyzeTable columns(String... columns);
+
+  /**
+   * Id of the snapshot for which stats need to be collected
+   *
+   * @param snapshotId long id of the snapshot for which stats need to be 
collected
+   * @return this for method chaining
+   */
+  AnalyzeTable snapshot(long snapshotId);
+
+  /** The action result that contains summaries of the Analysis. */

Review Comment:
   Analysis can be lower case, as its not a class object.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to