ruby和pig處理流式檔案執行個體_ruby專題

來源:互聯網
上載者:User

大資料操作中涉及到資料清洗步奏還是用指令碼處理比較方便,下邊介紹一下pig載入hdfs檔案後調用ruby指令碼處理資料,再返回資料流至pig中處理的一個簡單案例。

注意:ruby的串流用到wukong這個gem包,相關下載:
https://github.com/mrflip/wukong

pig中載入分布式檔案調用ruby串流:

複製代碼 代碼如下:

log = load '$INFILE' using PigStorage('\t');

define tracking_parser `/usr/ruby parse_click.rb --map` SHIP('parse_click.rb', 'click_tracking.rb');

strmo = stream log through tra_parser;

store strmo into '$OUTFILE' using PigStorage('\t');

複製代碼 代碼如下:

require 'wukong'
require 'json'
require './click_tra.rb'

module ParseClick
  class Mapper < Wukong::Streamer::RecordStreamer
    def before_stream
      @bad_count = 0
    end

    def after_stream
      raise RuntimeError, "Exceeded bad records : #{@bad_count}" if @bad_count > 10
    end

    def process *records
      yield ClickTra.new(JSON.parse(records[2])).to_a
    rescue => e
      @bad_count += 1
      warn "Bad record #{e}: #{records[2]}"
    end
  end
end

Wukong.run ParseClick::Mapper, nil

複製代碼 代碼如下:

require 'date'
require './models.rb'

class ClickTra
 
  output :ip
  output :c_date
  #output your other atrributes

  def c_date
    click_date.strftime("%Y%m%d").to_i
  end 

  def ip
    browser_ip.to_i
  end

end

其中

strmo = stream log through tra_parser;調用定義的外部程式tra_parser處理log對象。
Wukong.run ParseClick::Mapper, nil執行完後,將ruby執行結果回調pig接收。
store strmo into '$OUTFILE' using PigStorage('\t');做結果儲存持久化。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.