【问题标题】:Databricks read Azure blob last modified dateDatabricks 读取 Azure blob 上次修改日期
【发布时间】:2023-03-04 10:08:01
【问题描述】:
我有一个 Azure blob 存储安装到我的 Databricks hdfs。
有没有办法在数据块中获取 blob 的最后修改日期?
这就是我阅读 blob 内容的方式:
val df = spark.read
.option("header", "false")
.option("inferSchema", "false")
.option("delimiter", ",")
.csv("/mnt/test/*")
【问题讨论】:
标签:
azure-blob-storage
azure-databricks
【解决方案1】:
通常,有两种方法可以读取 Azure Blob 上次修改的数据,如下所示。
- 通过 Azure Storage REST API 或 Azure Storage SDK for Java 直接读取。
在我研究了 Azure Blob Storage REST API 之后,有两个 REST API
Get Blob 和 Get Blob Properties 可以从响应头中获取 Last-Modified 属性。因此,您可以在 Scala 中调用这些 api 来解析 api 响应标头来获取它,或者简单地使用 Scala 中的 Azure Storage SDK for Java 来做同样的事情。
这是我的 Java 示例代码,用于获取 blob 的 Last-Modified 属性。
import java.util.Date;
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
String StorageConnectionStringTemplate = "DefaultEndpointsProtocol=https;" +
"DefaultEndpointsProtocol=https;" +
"AccountName=%s;" +
"AccountKey=%s";
String accountName = "<your storage account name for HDInsight>";
String accountKey = "<your storage account key for HDInsight>";
String containerName = "<container name for HDFS>";
String blobName = "<blob name>";
String storageConnectionString = String.format(StorageConnectionStringTemplate, accountName, accountKey);
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient client = storageAccount.createCloudBlobClient();
CloudBlobContainer container = client.getContainerReference(containerName);
CloudBlob blob = container.getBlobReferenceFromServer(blobName);
Date lastModifiedDate = blob.getProperties().getLastModified();
考虑到Hadoop Azure是基于Azure Storage SDK for Java8.0.0,而不是最新版本10.0,所以我上面的示例代码与the offical tutorial of Azure Blob Storage for Java不同。
如果要获取容器的Last-Modified 属性,可以使用REST API [Get Container Properties][5] 或Java 代码Date lastModifiedDate = container.getProperties().getLastModified();。
-
将 Hadoop Azure Java API 用于wasb:// 协议。
import java.util.Date;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
Configuration conf = new Configuration();
FileSystem hdfs = FileSystem.get(conf);
Path f = new Path("<blob path on HDFS>");
FileStatus fileStatus = hdfs.getFileStatus(f);
long lastModifiedTime = f.getModificationTime();
Date lastModifiedDate = new Date(lastModifiedTime);