簡體   English   中英

連接,聚合然后選擇Apache Spark中的特定列

[英]Join, Aggregate Then Select Specific Columns In Apache Spark

像這樣正確地從csv文件加載產品及其銷售

    Dataset<Row> dfProducts = sparkSession.read()
            .option("mode", "DROPMALFORMED")
            .option("header", "true")
            .option("inferSchema", "true")
            .option("charset", "UTF-8")
            .csv(new ClassPathResource("products.csv").getURL().getPath());
    Dataset<Row> dfSaledetails = sparkSession.read()
            .option("mode", "DROPMALFORMED")
            .option("header", "true")
            .option("inferSchema", "true")
            .option("charset", "UTF-8")
            .csv(new ClassPathResource("saledetails.csv").getURL().getPath());

產品具有列(product_id,product_name等)。 銷售具有列(product_id,金額,...)

我需要實現的是加入基於公共列中的兩個數據集(product_id) ,按組product_id ,總和柱amount ,然后選擇/顯示只有特定列(這里給,並從求和的結果)

以下是我的嘗試

    Dataset<Row> dfSalesTotals = dfSaledetails
            .join(dfProducts, dfSaledetails.col("product_id").equalTo(dfProducts.col("product_id")))
            .groupBy(dfSaledetails.col("product_id"))
            .agg(sum(dfSaledetails.col("amount")).alias("total_amount"))
            .select(dfProducts.col("product_name"), col("total_amount"));
    dfSalesTotals.show();

哪個拋出以下錯誤

;;原因:org.apache.spark.sql.AnalysisException:操作員!項目[product_name#215,total_amount#499]中product_id#272,total_amount#499中缺少已解決的屬性product_name#215。 !項目[product_name#215,total_amount#499] +-總計[product_id#272],[product_id#272,sum(amount#277)AS total_amount#499] +-加入內部(product_id#272 = product_id#212) :-關系[sale_detail_auto_id#266,sale_auto_id#267,sale_id#268,agent_id#269,sale_detail_id#270,庫存ID#271,產品ID#272,單位成本#273,單位價格#274,vat#275,數量#276,數量# 277,promotion_id#278,折扣#279] csv +-關系[product_id#212,user_group_id_super_owner#213,product_category#214,product_name#215,product_type#216,product_code#217,distributor_code#218,product_units#219,product_unitCost#220 ,product_manufacturer#221,product_distributor#222,create_date#223,update_date#224,vat#225,product_weight#226,紙盒尺寸#227,product_listStatus#228,active_status#229,distributor_type#230,bundle_type#231,barcode_type#232,product_family_id #233] csv

如果要保留product_name則它應位於groupBy

.groupBy(
  dfSaledetails.col("product_id"),
  col("product_name")))

或在agg

.agg(
  sum(dfSaledetails.col("amount")).alias("total_amount"), 
  first(col("product_name")).alias("product_name"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM