cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

How to get the total number of records in a delta table from the stats, without querying it?

brickster_2018
Databricks Employee
Databricks Employee
 
1 ACCEPTED SOLUTION

Accepted Solutions

brickster_2018
Databricks Employee
Databricks Employee

The below code can be used to get the number of records in a Delta table without querying it

%scala
import com.databricks.sql.transaction.tahoe.DeltaLog
import org.apache.hadoop.fs.Path
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._
 
val deltaTablePath = "location of the table"
 
def getRecordCount(deltaTablePath: String): Any = {
  val snapshot = DeltaLog.forTable(spark, new Path(deltaTablePath)).update()
  val statsSchema = snapshot.statsSchema
  var files = snapshot.allFiles.withColumn("stats", from_json($"stats", statsSchema))
  val dfWithNumRecords = files.select($"path", $"stats.numRecords".as("numRecords"))
  val totalCount = dfWithNumRecords.select(sum($"numRecords")).first().get(0)
  return totalCount
 }
println(getRecordCount(deltaTablePath))

View solution in original post

1 REPLY 1

brickster_2018
Databricks Employee
Databricks Employee

The below code can be used to get the number of records in a Delta table without querying it

%scala
import com.databricks.sql.transaction.tahoe.DeltaLog
import org.apache.hadoop.fs.Path
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._
 
val deltaTablePath = "location of the table"
 
def getRecordCount(deltaTablePath: String): Any = {
  val snapshot = DeltaLog.forTable(spark, new Path(deltaTablePath)).update()
  val statsSchema = snapshot.statsSchema
  var files = snapshot.allFiles.withColumn("stats", from_json($"stats", statsSchema))
  val dfWithNumRecords = files.select($"path", $"stats.numRecords".as("numRecords"))
  val totalCount = dfWithNumRecords.select(sum($"numRecords")).first().get(0)
  return totalCount
 }
println(getRecordCount(deltaTablePath))

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group