Search code examples
scalaazureapache-commons-dbutilsazure-databricks

Azure Databricks Notebook unable to find "dbutils" when it is in package


I am creating a class in for communicating with azure storage blobs and it is working fine but if I try to put this class in package it is giving me an error "error: not found: value dbutils". It is working fine if I remove the "package Libraries.Custom" above my class.

I am creating a class in azure databricks notebook using Scala. Could anybody help me out. The code is stated below:

Class Code

package Libraries.Custom

import org.apache.spark.sql._

class BlobContext {
  // Basic Azure Storage Configurations
  val blob_account_name = "REPLACE_BY_ACTUAL_VALUE"
  val blob_account_access_key = "REPLACE_BY_ACTUAL_VALUE"
  val blob_container_name = "REPLACE_BY_ACTUAL_VALUE"
  val blob_server = s"REPLACE_BY_ACTUAL_VALUE"
  val blob_wasbs = s"REPLACE_BY_ACTUAL_VALUE"

  val spark = SparkSession
    .builder()
    .appName("Path SOM")
    .master("local[*]")
    .config("spark.ui.enabled", "false")
    .getOrCreate()

  def SetConfigurations {
    spark.conf.set(blob_server, blob_account_access_key)
  }

  def ReadData(fileName: String, fileType: String): DataFrame = {
    SetConfigurations
    val dataFrame = spark.read.format(fileType).option("header", "true").load(s"${blob_wasbs}${fileName}.${fileType}")    
    return dataFrame
  }

  def WriteData(fileDataFrame: DataFrame, fileName: String, fileType: String) {
    val absTempFilePath = s"${blob_wasbs}SPARK_NEW_${fileName}.temp"
    val absFilePath = s"${blob_wasbs}SPARK_NEW_${fileName}.${fileType}"

    fileDataFrame.repartition(1).write.format(fileType).mode("overwrite").option("header", "true").option("inferSchema", "true").option("delimiter", ",").csv(absTempFilePath)

    val partition_path = dbutils.fs.ls(absTempFilePath + "/").filter(file=>file.name.endsWith(".csv"))(0).path
    dbutils.fs.cp(partition_path, absFilePath)
    dbutils.fs.rm(absTempFilePath,recurse=true)
  }      
}

Error

<notebook>:37: error: not found: value dbutils
    val partition_path = dbutils.fs.ls(absTempFilePath + "/").filter(file=>file.name.endsWith(".csv"))(0).path
                         ^
<notebook>:38: error: not found: value dbutils
    dbutils.fs.cp(partition_path, absFilePath)
    ^
<notebook>:39: error: not found: value dbutils
    dbutils.fs.rm(absTempFilePath,recurse=true)
    ^
<notebook>:39: error: not found: value recurse
    dbutils.fs.rm(absTempFilePath,recurse=true)
                                  ^
Compilation failed.

Solution

  • Try adding this import:

    import com.databricks.dbutils_v1.DBUtilsHolder.dbutils