如何使用 Java 在 Dataflow Apache Beam 中将 PCollection<Row> 转换为 Long

How to convert PCollection<Row> to Long in Dataflow Apache beam using Java

当我们尝试将 Pcollection 转换为 Long 时,我们遇到类型转换异常。请查看以下代码。

错误

java.lang.Integer cannot be cast to java.lang.Long

正在创建 pcollection

PCollection<Row> count = pt.apply(SqlTransform.query(Constants.total_count));
        PCollectionView<Long> outputCount = detail_count
                .apply("Row to long",
                        ParDo.of(new RowToLong())).apply(View.asSingleton());

查询

String total_count  = select sum(cast(col1 as INT)) as total_count from <table>

转换 RowTo 方法

public class RowToLong extends DoFn<Row, Long> {
    public static final Logger LOG = LoggerFactory.getLogger(RowToLong.class.getName());    

    private PCollectionView<Long> outputCount;      

    @ProcessElement
    public void processElement(ProcessContext context) {    
        
    //  Long total_count=((Number)c.element().getInt64("total_count")).longValue();
        Long total_count= Long.valueOf(context.element().getInt64("total_count"));          
          context.output(total_count);    
    }

}

使用下面的代码试试这个。

查询

String total_count  = select sum(cast(col1 as bigint)) as total_count from <table>

正在将行转换为方法

Long total_count = context.element().getInt64("total_count").longValue();