1. 程式人生 > >hive mapreduce script用法示例

hive mapreduce script用法示例

2013-03-27

周海漢/文 2013.3.27

對於一些hql語句特殊處理,hive本身沒有提供相應功能,可以有兩種方式,一是mapreduce script,二是寫UDF,UDAF,UDTF等。後者需要呼叫hive提供的api。前者則類似mapreduce的stream模式,只需正確處理輸入輸出即可。 所以mapreduce指令碼進行一些簡單處理還是很方便的。

本例想計算德州撲克玩家是否贏牌,演算法是:如果棄牌或所贏籌碼為NULL,則輸。如果有贏邊池或底池的籌碼,也不一定贏。要用底池+邊池籌碼-所投注數,如果大於0,則一定贏了。 現在底池邊池籌碼是不固定的,格式如下: 0:籌碼|1:籌碼|2:籌碼|… 0表示底池,1,2等index表示不同的邊池,最多8個邊池。 用python來分析

cat calcwin.py

#!/usr/bin/env python
# coding:utf8
# author zhouhh
# date :2013-03-27

import sys
import datetime

def calcwin():
    for line in sys.stdin:

        (ldate,userid,roundbet,fold,allin,chipwon)=line.strip().split()
        win = '0'
        if fold=='1':

            print 't'.join(["%s:
%s"%(ldate,userid),win,fold,allin]) continue cw = [] if chipwon == "NULL": print 't'.join(["%s:%s"%(ldate,userid),win,fold,allin]) continue #print "userid win ",userid cw=chipwon.split('|') chipwonv=0 roundbetv=int(roundbet
) for v in cw: chipwonv += int(v.split(':')[1]) if chipwonv > roundbetv: win = '1' print 't'.join(["%s:%s"%(ldate,userid),win,fold,allin]) calcwin()

原始資料格式:

hive> !hadoop fs -cat /flume/test/testpoker;
03/13/13 14:59:51 00000ab4 1009 185690475 8639 240 1 0 -1 NULL NULL
03/13/13 14:59:51 00000cb4 1009 187270278 92030 600 1 0 -1 NULL NULL
03/13/13 14:59:52 000003d8 1009 184151687 8639 600 1 0 -1 NULL NULL
03/13/13 14:59:52 00000ba8 1009 186012530 8593 154135 0 1 7 8|21|16|42|39 0:73250|1:60500|2:100135
03/13/13 14:59:52 00000a88 1009 180286243 92041 100 1 0 -1 NULL NULL
03/13/13 14:59:52 00000ad8 1009 163003653 2829 40 1 0 -1 NULL NULL
03/13/13 14:59:54 000002ac 1009 183824880 8639 1200 0 0 -1 NULL 0:1900
03/13/13 14:59:55 0000091c 1009 173274868 92030 600 0 0 -1 NULL 0:1150

然後,在hive命名行新增calcwin.py

hive> add file calcwin.py
hive> from testpoker select transform(ldate,userid,roundbet,fold,allin,chipwon) using 'calcpoker.py' as (key,win,fold,allin) ;
...
OK
03/13/13:185690475      0       1       0
03/13/13:187270278      0       1       0
03/13/13:184151687      0       1       0
03/13/13:186012530      1       0       1

如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源