是否可以通过从TextIO.Read读入PCollection的行来访问行号?对于此处的上下文,我正在处理CSV文件,并且需要访问给定行的行号。
如果没有可能通过TextIO.Read似乎应该可以使用某种自定义读取或转换,但我无法确定从哪里开始。
答案 0 :(得分:1)
您可以使用FileIO
手动读取文件,并在从ReadableFile
读取时确定行号。
一个简单的解决方案如下所示:
p
.apply(FileIO.match().filepattern("/file.csv"))
.apply(FileIO.readMatches())
.apply(FlatMapElements
.into(strings())
.via((FileIO.ReadableFile f) -> {
List<String> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(Channels.newReader(f.open(), "UTF-8"))) {
int lineNr = 1;
String line = br.readLine();
while (line != null) {
result.add(lineNr + "," + line);
line = br.readLine();
lineNr++;
}
} catch (IOException e) {
throw new RuntimeException("Error while reading", e);
}
return result;
}));
上面的解决方案只是将行号添加到每个输入行。