云数据流:读取整个文本文件而不是逐行读取

时间:2016-06-06 22:31:45

标签: java google-cloud-dataflow

我正在寻找一种方法来读取整个ENTIRE文件,以便将每个文件完全读取到一个字符串。 我想在gs://my_bucket/*/*.json上传递JSON文本文件的模式,然后让ParDo完全处理每个文件。

最好的方法是什么?

4 个答案:

答案 0 :(得分:3)

我会给出最普遍有用的答案,即使有特殊情况[1],你可能会做一些不同的事情。

我认为您要做的是定义FileBasedSource的新子类并使用Read.from(<source>)。您的来源还将包含FileBasedReader的子类; source 包含配置数据,而 reader 实际上是在阅读。

我认为API的完整描述最好留给Javadoc,但我会重点介绍关键覆盖点以及它们与您的需求之间的关系:

  • FileBasedSource#isSplittable()您要覆盖并返回false。这表示没有文件内拆分。
  • FileBasedSource#createForSubrangeOfFile(String, long, long)您将覆盖以仅返回指定文件的子源。
  • FileBasedSource#createSingleFileReader()您将覆盖以为当前文件生成FileBasedReader(该方法应该假设它已经拆分为单个文件的级别)。

实施读者:

  • FileBasedReader#startReading(...)你会覆盖什么都不做;框架已经为你打开了文件,它将关闭它。
  • FileBasedReader#readNextRecord()您将覆盖以将整个文件作为单个元素读取。

[1]一个简单的例子就是当你实际拥有少量文件时,可以在提交作业之前扩展它们,并且它们都需要相同的时间来处理。然后,您可以使用Create.of(expand(<glob>)),然后使用ParDo(<read a file>)

答案 1 :(得分:1)

我自己正在寻找类似的解决方案。遵循Kenn的建议和其他一些引用,如XMLSource.java,创建了以下自定义源,似乎工作正常。

我不是开发人员,所以如果有人就如何改进它提出建议,请随时提供帮助。

public class FileIO {
// Match TextIO.
public static Read.Bounded<KV<String,String>> readFilepattern(String filepattern) {
    return Read.from(new FileSource(filepattern, 1));
}

public static class FileSource extends FileBasedSource<KV<String,String>> {
    private String filename = null;

    public FileSource(String fileOrPattern, long minBundleSize) {
        super(fileOrPattern, minBundleSize);
    }

    public FileSource(String filename, long minBundleSize, long startOffset, long endOffset) {
        super(filename, minBundleSize, startOffset, endOffset);
        this.filename = filename;
    }

    // This will indicate that there is no intra-file splitting.
    @Override
    public boolean isSplittable(){
        return false;
    }

    @Override
    public boolean producesSortedKeys(PipelineOptions options) throws Exception {
        return false;
    }

    @Override
    public void validate() {}

    @Override
    public Coder<KV<String,String>> getDefaultOutputCoder() {
        return KvCoder.of(StringUtf8Coder.of(),StringUtf8Coder.of());
    }

    @Override
    public FileBasedSource<KV<String,String>> createForSubrangeOfFile(String fileName, long start, long end) {
        return new FileSource(fileName, getMinBundleSize(), start, end);
    }

    @Override
    public FileBasedReader<KV<String,String>> createSingleFileReader(PipelineOptions options) {
        return new FileReader(this);
    }
}

/**
 * A reader that should read entire file of text from a {@link FileSource}.
 */
private static class FileReader extends FileBasedSource.FileBasedReader<KV<String,String>> {
    private static final Logger LOG = LoggerFactory.getLogger(FileReader.class);
    private ReadableByteChannel channel = null;
    private long nextOffset = 0;
    private long currentOffset = 0;
    private boolean isAtSplitPoint = false;
    private final ByteBuffer buf;
    private static final int BUF_SIZE = 1024;
    private KV<String,String> currentValue = null;
    private String filename;

    public FileReader(FileSource source) {
        super(source);
        buf = ByteBuffer.allocate(BUF_SIZE);
        buf.flip();
        this.filename = source.filename;
    }

    private int readFile(ByteArrayOutputStream out) throws IOException {
        int byteCount = 0;
        while (true) {
            if (!buf.hasRemaining()) {
                buf.clear();
                int read = channel.read(buf);
                if (read < 0) {
                    break;
                }
                buf.flip();
            }
            byte b = buf.get();
            byteCount++;

            out.write(b);
        }
        return byteCount;
    }

    @Override
    protected void startReading(ReadableByteChannel channel) throws IOException {
        this.channel = channel;
    }

    @Override
    protected boolean readNextRecord() throws IOException {
        currentOffset = nextOffset;

        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int offsetAdjustment = readFile(buf);
        if (offsetAdjustment == 0) {
            // EOF
            return false;
        }
        nextOffset += offsetAdjustment;
        isAtSplitPoint = true;
        currentValue = KV.of(this.filename,CoderUtils.decodeFromByteArray(StringUtf8Coder.of(), buf.toByteArray()));
        return true;
    }

    @Override
    protected boolean isAtSplitPoint() {
        return isAtSplitPoint;
    }

    @Override
    protected long getCurrentOffset() {
        return currentOffset;
    }

    @Override
    public KV<String,String> getCurrent() throws NoSuchElementException {
        return currentValue;
    }
}

}

答案 2 :(得分:1)

一种更简单的方法是生成文件名列表并编写一个函数来分别处理每个文件。我正在显示Python,但Java与此类似:

def generate_filenames():
  for shard in xrange(0, 300):
    yield 'gs://bucket/some/dir/myfilname-%05d-of-00300' % shard

with beam.Pipeline(...) as p:
  (p | generate_filenames()
     | beam.FlatMap(lambda filename: readfile(filename))
     | ...)

答案 3 :(得分:0)

FileIO无需您实现自己的FileBasedSource即可为您完成此任务。

为要读取的每个文件创建匹配项:

mypipeline.apply("Read files from GCS", FileIO.match().filepattern("gs://mybucket/myfilles/*.txt"))

此外,如果不想为文件找不到文件时Dataflow引发异常,则可以这样阅读:

mypipeline.apply("Read files from GCS", FileIO.match().filepattern("gs://mybucket/myfilles/*.txt").withEmptyMatchTreatment(EmptyMatchTreatment.ALLOW))

使用FileIO读取您的比赛:

.apply("Read file matches", FileIO.readMatches())

上面的代码返回FileIO.ReadableFile类型的PCollection(PCollection )。然后创建一个DoFn来处理这些ReadableFiles以满足您的用例。

.apply("Process my files", ParDo.of(MyCustomDoFnToProcessFiles.create()))

您可以阅读FileIO here的整个文档。

相关问题