Showing posts with label Pig. Show all posts
Showing posts with label Pig. Show all posts

Friday, November 11, 2016

ToDate Format in Pig

EEE MMM dd HH:mm:ss z yyyy

"yyyy-MM-dd"
yyyy/MM/dd"
"yyyy.MM.dd"
       
MM/dd/yyyy
"MM-dd-yyyy
"MM.dd.yyyy"

"dd-MM-yyyy"
"dd/MM/yyyy"
"dd.MM.yyyy"
       
       
  "M/dd/yyyy"
"dd.M.yyyy"
"M/dd/yyyy hh:mm:ss a"
"dd.M.yyyy hh:mm:ss a"
"dd.MMM.yyyy"
"dd-MMM-yyyy"
"yyyy/dd/MM"

data = LOAD ' part-r-00000.bz2'
using PigStorage('\t') AS (
 yuid: chararray,
 domain: chararray,
 templateid: int,
 messageid: chararray,
 senderdate: chararray,
 template: chararray
 );

toISOA = FOREACH data GENERATE yuid, REGEX_EXTRACT(senderdate, '((.*)\\,)?\\s([1-9]+\\s(.*)\\s(19|20)\\d{2})(.*)',3) as sdate;
toISOA1 = FILTER toISOA BY string.LENGTH(sdate)>=10
toISOA2 = FOREACH toISOA1 GENERATE yuid, REPLACE(sdate,' ','-') AS sdate1;
toISOA3 = FOREACH toISOA2 GENERATE yuid, SUBSTRING(CustomFormatToISO(sdate1, 'dd-MMM-yyyy'), 0, 10) as mail_date;
by_mail_date = GROUP toISOA3 BY mail_date;
by_mail_date1 = FOREACH by_mail_date GENERATE group, COUNT($1) AS count;
STORE by_mail_date1 INTO 'by_mail_date1';

Read Json in Pig

-- Modify to your path
REGISTER /home/*/pig/elephant-bird-core-4.6rc4.jar;
REGISTER /home/*/pig/elephant-bird-pig-4.6rc4.jar;
REGISTER /home/*/pig/elephant-bird-hadoop-compat-4.6rc4.jar;
REGISTER /home/*/share/pig/lib/json-simple-1.1.jar;
REGISTER /home/*/share/pig/lib/piggybank.jar;

DEFINE UnixToISO org.apache.pig.piggybank.evaluation.datetime.convert.UnixToISO();

data = LOAD '/20140905/*' USING com.twitter.elephantbird.pig.load.JsonLoader('-nestedLoad');
--basefeed = FOREACH data GENERATE $0#'email_type', $0#'identity';
--data1 = limit basefeed 10;
--dump data1;

basefeed = FOREACH data GENERATE
$0#'email_type' as email_type,
$0#'identity' as identity,
$0#'domain_name' as domain_name,
$0#'domain_category' as domain_category,
$0#'purchase_category' as purchase_category,
$0#'country' as country,
$0#'email_id' as email_id,
$0#'ts' as ts;

basefeed1 = filter basefeed by (country == 'us');
--STORE basefeed1 INTO '20140903';


--by_basefeed1 = group basefeed1 all;
--by_basefeed2 = FOREACH by_basefeed1 GENERATE group, COUNT($1) as count;
--STORE by_basefeed2 INTO '20140903/by_basefeed2';


--0 count distinct email_id;
--by_email = FOREACH basefeed1 generate email_id;
--by_email1 = distinct by_email;
--by_email2 = group by_email1 all;
--by_email3 = FOREACH by_email2 GENERATE group, COUNT($1) as user_count;
--STORE by_email3 INTO '20140903/by_email3';


--1 count distinct identity;
---by_identity = FOREACH basefeed1 generate identity;
---by_identity1 = distinct by_identity;
---by_identity2 = group by_identity1 all;
---by_identity3 = FOREACH by_identity2 GENERATE group, COUNT($1) as user_count;
---STORE by_identity3 INTO '20140903/by_identity';

import json
#path=os.path.abspath()
#file = os.path.join(path, 'output.txt')
f = open("long example.txt", 'r')

#@outputSchema("record:bag{t:(cat2:chararray)}")
#def parse_list(line):
for line1 in f:
    print line1;
    category_dictinary = {"mailtype":[]}
    line = json.loads(line1)
    if type(line) == type(None):
        print 'null'
        #return outbag
    for element in line.keys():
        print element;
        print line[element];
        items = line[element];
        for item in items.keys():
            category_dictinary["mailtype"].append(item)
            print category_dictinary;
        print ('\n');

import json
f = open("long example.txt", 'r')

Python function
#@outputSchema("record:bag{t:(cat2:chararray)}")
#def parse_list(line):
for line1 in f:
    print line1
    category_dictinary = {"mailtype":[]}
    line = json.loads(line1)
    outbag = []
    if type(line) == type(None):
        print 'null'
        #return outbag
    for element in line.keys():
        print element;
        # element = elements
        items = line[element];
        print items.keys();
        # items key = ParcelDelivery
        for item in items.keys():
            item2 = items[item]
            if type(item2) is dict:
                #if 'itemShipped_name' in item2.keys(): print outbag.append(item2['itemShipped_name'])
                if 'itemShipped_name' in item2.keys(): print outbag.append(item2['itemShipped_name'])
            if type(item2) is list:
                for item3 in item2:
                    if 'itemShipped_name' in item3.keys(): outbag.append(item3['itemShipped_name'])
    print outbag;

Python UDF in Pig

@outputSchema("adimp1dbucket:int")
def adimp1dtoimp1dbucket(adimpfreq1d):
    if (adimpfreq1d == 0): adimp1dbucket = 0   
    elif (adimpfreq1d >= 1) and (adimpfreq1d <= 5): adimp1dbucket = 1
    elif (adimpfreq1d >= 6) and (adimpfreq1d <= 20): adimp1dbucket = 2
    elif (adimpfreq1d >= 21): adimp1dbucket = 3
    else: adimp1dbucket = -1
    return (adimp1dbucket)

@outputSchema("adimp3wbucket:int")
def adimp3wtoimp3wbucket(adimpfreq3w): 
    if (adimpfreq3w == 0): adimp3wbucket = 0 
    elif (adimpfreq3w >= 1) and (adimpfreq3w <= 12): adimp3wbucket = 1
    elif (adimpfreq3w >= 13) and (adimpfreq3w <= 50): adimp3wbucket = 2
    elif (adimpfreq3w >= 50): adimp3wbucket = 3
    else: adimp3wbucket = -1
    return (adimp3wbucket)

Imps12A = FOREACH Imps11A GENERATE row_id, adfreq1d, bucket.adimp1dtoimp1dbucket(adfreq1d), adfreq3w, bucket.adimp3wtoimp3wbucket(adfreq3w), adrec;


--Hello world data sample.
$ cat hello_world.txt
foo
foo
baz

--Sample Pig using Jython.
$ cat hello_world.pig
Register 'hello.py' using jython as hello;
A = load 'hello_world.txt' as (name: chararray);
b = foreach A generate name,hello.helloworld();
store b into '/user/*****/hello_world_output' using P****e();

--Python Hello world File
$ cat hello.py
#!/usr/bin/python

@outputSchema("word:chararray")
def helloworld(): 
  return ('Hello, World')

--Copy data file
hadoop fs -put hello_world.txt
--Run Pig Scripts
ls -la

pig -****job.queue.name=***** hello_world.pig

Extending Apache Pig with Python UDFs
2 Created myudf.pig file:

from pig_util import outputSchema 

@outputSchema("word:chararray")
def hi_world(self):
  return "hello word"

3 Created udf.pig
REGISTER 'myudf.py' using python as my_special udders

users = LOAD '/kohls/stage/tmp/***/pyudf/user_date' AS (name: char array):
hello_users = FOREACH users GENERATE name, my_special_udfs.hi_world():
dump hello_users

4 Here's user_data
sunil
kumar
avril
lavigne

5 Ran the pig job using: pig -x local udf.pig

Faced one problem, which is passing 'self' parameter to python function. That is not mentioned in tutorial.