hepzi
hepzi

Reputation: 445

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

When we try to convert the Pcollection to Long we are getting Type casting exception. kindly have a look into below code.

error

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

Creating the 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());

Query

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

Converting RowTo method

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);    
    }

}

Upvotes: 1

Views: 422

Answers (1)

Butter cup
Butter cup

Reputation: 66

Try this using below code.

Query

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

Converting row to method

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

Upvotes: 3

Related Questions