java - 如何将 CSV 文件加载到 Apache Arrow vectors 并将箭头文件保存到磁盘

标签 java scala csv apache-arrow

我目前正在玩 Apache Arrow的 java API(尽管我在代码示例中使用了 Scala 中的它)以熟悉此工具。

作为练习,我选择将 CSV 文件加载到箭头 vector 中,然后将它们保存到箭头文件中。第一部分看起来很简单,我试了一下:

val csvLines: Stream[Array[String]] = <open stream from CSV parser>

// There are other types of allocator, but things work with this one...
val allocator = new RootAllocator(Int.MaxValue)

// Initialize the vectors
val vectors = initVectors(csvLines.head, allocator)
// Put their mutators into an array for easy access
val mutators = vectors.map(_.getMutator)

// Work on the data, zipping it with its index 
Stream.from(0)
  .zip(csvLines.tail) // Work on the tail (head contains the headers)
  .foreach(rowTup =>  // rowTup = (index, csvRow as an Array[String])
    Range(0, rowTup._2.size) // Iterate on each column...
      .foreach(columnNumber =>
        writeToMutator(
          mutators(columnNumber), // get that column's mutator
          idx=rowTup._1,          // pass the current row number
          data=rowTup._2(columnNumber) // pass the entry of the curernt column
        )
      )
)

initVectors()writeToMutator() 定义为:

def initVectors(
  columns: Array[String], 
  alloc: RootAllocator): Array[NullableVarCharVector] = {

  // Initialize a vector for each column
  val vectors = columns.map(colName => 
    new NullableVarCharVector(colName, alloc))
  // 4096 size, for 1024 values initially. This is arbitrary
  vectors.foreach(_.allocateNew(2^12,1024))
  vectors
}

def writeToMutator(
  mutator: NullableVarCharVector#Mutator, 
  idx: Int, 
  data: String): Unit = {

  // The CSV may contain null values
  if (data != null) {
    val bytes = data.getBytes()
    mutator.setSafe(idx, bytes, 0, bytes.length)
  }
  mutator.setNull(idx)
}

(我目前不关心使用正确的类型,而是将所有内容都存储为字符串,或箭头符号中的 VarChar)

所以在这一点上,我有一个 NullableVarCharVector 的集合,并且可以从/向它们读取和写入。在这一点上一切都很棒。不过,现在,对于下一步,我想知道如何将它们实际包装在一起并将它们序列化为箭头文件。我偶然发现了一个 AbstractFieldWriter 抽象类,但不清楚如何使用这些实现。

所以,问题主要是:

  • 将一堆 vector 保存到箭头文件的(最好的?- 似乎有多种)方法是什么。
  • 是否有其他方法可以将 CSV 列加载到箭头 vector ?

编辑添加: metadata description page就该主题提供了一个很好的总体概述。

api 的测试类似乎包含一些可以提供帮助的东西,我会在尝试过后发布一个带有示例的回复。

最佳答案

查看TestArrowFile.javaBaseFileTest.java我发现:

  • 如何将单个箭头文件写入磁盘
  • 另一种填充 vector 的方法,因为我的第一次尝试阻止了我组装单个箭头文件(或者至少以直接的方式这样做)。

所以,填充 vector 现在看起来像:

// Open stream of rows 
val csvLines: Stream[Array[String]] = <open stream from CSV parser>
// Define a parent to hold the vectors
val parent = MapVector.empty("parent", allocator)
// Create a new writer. VarCharWriterImpl would probably do as well?
val writer = new ComplexWriterImpl("root", parent)

// Initialise a writer for each column, using the header as the name
val rootWriter = writer.rootAsMap()
val writers = csvLines.head.map(colName => 
                                  rootWriter.varChar(colName))

Stream.from(0)
  .zip(csvLines.tail) // Zip the rows with their index
  .foreach( rowTup => { // Iterate on each (index, row) tuple
    val (idx, row) = rowTup
      Range(0, row.size) // Iterate on each field of the row
        .foreach(column =>
          Option(row(column)) // row(column) may be null,
            .foreach(str =>   // use the option as a null check
              write(writers(column), idx, allocator, str)
            )
      )
  }
)

toFile(parent.getChild("root"), "csv.arrow") // Save everything to a file

write 定义为:

def write(writer: VarCharWriter, idx: Int, 
  allocator: BufferAllocator, data: String): Unit = {
  // Set the position to the correct index
  writer.setPosition(idx)
  val bytes = data.getBytes()
  // Apparently the allocator is required again to build a new buffer
  val varchar = allocator.buffer(bytes.length)
  varchar.setBytes(0, data.getBytes())
  writer.writeVarChar(0, bytes.length, varchar)
}

def toFile(parent: FieldVector, fName: String): Unit = {
  // Extract a schema from the parent: that's the part I struggled with in the original question
  val rootSchema = new VectorSchemaRoot(parent)
  val stream = new FileOutputStream(fName)
  val fileWriter = new ArrowFileWriter(
                        rootSchema,
                        null, // We don't use dictionary encoding.
                        stream.getChannel)
  // Write everything to file...
  fileWriter.start()
  fileWriter.writeBatch()
  fileWriter.end()
  stream.close()
}

有了上面的内容,我就可以将 CSV 文件保存到文件中。我通过阅读并再次将其转换为 CSV 来检查一切是否顺利,内容没有改变。

请注意,ComplexWriterImpl 允许写入不同类型的列,这有助于避免将数字列存储为字符串。

(我现在正在玩阅读方面的东西,这些东西可能值得他们自己提出 SO 问题。)

关于java - 如何将 CSV 文件加载到 Apache Arrow vectors 并将箭头文件保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886465/

相关文章:

java - 如何从字符串中删除特定字符?

java - float 与 double(在 Java 中)

scala 和 lift : rewriting URL using variable declared outside LiftRules. statelessRewrite.append

java - MySQL 中的字段由 LOAD DATA INFILE 终止

csv - 将制表符分隔符转换为分号

android - Akka on Android 多重引用.conf

java - JFrame 中的 JTree 颜色不改变

java - 将 ActionEvent 添加到许多 JButton

java - Spring 注入(inject)接口(interface)实现给出 Nullpointer

scala - 在 PartialFunction 的 isDefined 和 Apply 中都发生了代价高昂的计算