Apache pig 學習
一.Pig安裝說明
1.介紹
2.安裝
2.1 獲取PIG穩定版本
wget http://www.eu.apache.org/dist/pig/pig-0.11.0/pig-0.11.0.tar.gz
(注:此版本適用于Hadoop的0.20.X,1.x中,0.23.X和2.X)
SVN下載地址:http://svn.apache.org/repos/asf/pig/trunk
2.2 解壓
tar -zxvf pig-0.11.0.tar.gz -C /usr/local/pig.0.11.0
2.3 配置環境變量
PIG_HOME=/usr/local/pig.0.11.0
PATH=$PIG_HOME/bin
2.4 測試pig安裝簡單命令
pig -help
3.運行
3.1 執行模式
pig有兩個執行模式或執行方式的:
本地模式 -pig在本地模式下運行,您需要訪問一臺機器,使用本地主機和文件系統的所有文件都安裝并運行。指定使用-x標志(pig-X本地)的本地模式。需要注意的是本地模式下不支持并行映射執行與Hadoop 0.20.x和1.0.0。這是,因為這些Hadoop版本的LocalJobRunner是不是線程安全的。
MapReduce的模式 -要運行的MapReduce模式的pig,你需要訪問一個Hadoop集群和HDFS安裝。MapReduce的模式是默認的模式,就可以了,但并不需要,指定使用-x標志(豬或pig-X的MapReduce)。
您可以在這兩種模式下運行的PIG的“pig”命令 或者“java”命令(java命令pig.jar)。
案例:
pig命令形式:
A.本地模式:pig -x local
B.集群模式:pig -x mapreduce
java 命令形式:
A.本地模式:java -cp ../pig-0.10.0.jar org.apache.pig.Main -x local
B.集群模式:java -cp ../pig-0.10.0.jar org.apache.pig.Main -x mapreduce
批處理模式
你可以在本地和hadoop模式下 使用pig腳本和pig命令
1.創建一個 id.pig,編寫pig腳本
$ touch id.pig
$ vim id.pig
/* id.pid*/
A = load 'passwd' using PigStorage(':'); -- load the passwd file
B = foreach A generate $0 as id; -- extract the user IDs
store B into 'id.out'; -- write the results to a file name id.out
2.準備數據 cp /etc/passwd ./passwd
3.本地模式運行id.pig
Pig -x local id.pig
輸出: mapreduce模型運行id.pig
1.將測試數據passwd put hadoop目錄下
/* id.pid*/
--rm /recommend/test/input/passwd
--rm /user/hadoop_recommend/id.out
copyFromLocal /etc/passwd /recommend/test/input/
A = load '/recommend/test/input/passwd' using PigStorage(':');
B = foreach A generate $0 as id; -- extract the user IDs
store B into 'id.out'; -- write the results to a file name id.out
2.pig id.pid 或者 pig-x mapreduce id.pig
您可以包括在pig腳本的注解:
對于使用多行注釋/ * .... * /
對于單行注釋使用 -
/* v_recommend.pig
My script is simple.
It includes three Pig Latin statements.
*/
A = LOAD 'recommend.csv' USING PigStorage('\t') AS (tittle:chararray, label:chararray, time:int, vv:int, up_date:chararray); -- loading data
B = FOREACH A GENERATE tittle; -- transforming data
DUMP B; -- retrieving results
PIG教程
PIG目錄下有一個文件夾 ”pig-0.11.0/tutorial” 屬于PIG提供的完整的教程案例
1.在使用前環境變量配置完全:JAVA_HOME,PIG_HOME,ANT_HOME
2.在tutorial 下運行 ant -f build.xml,將創建 pigtutorial.tar.gz 這個文件
3.復制pigtutorial.tar.gz這個文件到指定目錄下,并解壓,
4.生成pigtmp文件夾,此目錄包含 pig教程文件,與hadoop0.20.2 這些文件工作,包括你要運行pig腳本script和script2
在本地模式下運行PIG腳本
在本地模式下運行PIG腳本,請執行以下操作:
1.進入pigtmp目錄
2.執行下面的命令(使用script1_local.pig或者script2_local.pig)
3.檢測結果文件,在部分—R-00000的目錄。輸出的可能是hadoop的警告,可以忽略不計的
在mapreduce模式下運行pig腳本
在mapreduce模式下運行pig腳本,請執行以下操作:
1.進入pigtmp目錄下;
2.復制excite.log.bz2的文件從pigtmp目錄到HDFS 目錄/user/hadoop_recommend/
hadoop fs -copyFromLocal excite.log.bz2 /user/hadoop_recommend/
3.設置PIG_CLASSPATH的環境變量的集群配置目錄(該目錄包含核心的site.xml,HDFS的site.xml和mapred-site.xml文件)的位置
4.設置環境變量的HADOOP_CONF_DIR的群集配置目錄的位置
5.執行下面的命令(使用或者script1 hadoop.pig或SCRIPT2 hadoop.pig):
6.審查的結果文件,在的script1結果Hadoop的HDFS目錄或SCRIPT2 Hadoop的結果:
hadoop fs -cat /user/hadoop_recommend/script1-hadoop-results/part-r-00000
文件 |
描述 |
pig.jar |
豬JAR文件 |
tutorial.jar |
用戶定義的函數(UDF)和Java類 |
script1-local.pig |
豬腳本1,查詢短語人氣(本地模式) |
script1-hadoop.pig |
豬腳本1的查詢短語人氣(MapReduce的模式) |
SCRIPT2-local.pig |
豬腳本2,臨時的查詢短語人氣(本地模式) |
SCRIPT2-hadoop.pig |
豬腳本2,臨時的查詢短語人氣(MapReduce的模式) |
興奮的small.log |
日志文件,驚險刺激的搜索引擎(本地模式) |
excite.log.bz2 |
日志文件,驚險刺激的搜索引擎(MapReduce的) |
用戶定義函數(UDF)的描述。
UDF |
描述 |
ExtractHour |
從記錄中提取小時。 |
NGramGenerator |
從字組組成的n-gram。 |
NonURLDetector |
刪除的記錄,如果查詢字段為空或一個URL。 |
ScoreGenerator |
計算得分的N-gram的“人氣”。 |
ToLower將 |
查詢字段更改為小寫。 |
TutorialUtil |
的查詢字符串分割成一組的話。 |
腳本解析
Script1:查詢短語人氣
查詢短語人氣腳本(script1 local.pig或script1 hadoop.pig)處理在Excite搜索引擎的搜索查詢日志文件,發現搜索短語,尤其是高頻率發生在一天的某些時間
腳本內容所示:
注冊教程JAR文件,所包含的UDF也可以在腳本中調用。
REGISTER ./tutorial.jar;
使用的PigStorage的函數來加載在Excite的日志文件(excite.log或激發,small.log)到“原始”包作為一個數組的領域的用戶,時間,和查詢的記錄。
raw = LOAD 'excite.log' USING PigStorage('\t') AS (user, time, query);
如果查詢字段為空或一個URL調用NonURLDetector UDF中刪除記錄。
clean1 = FILTER raw BY org.apache.pig.tutorial.NonURLDetector(query);
調用ToLower將UDF改變查詢字段小寫的。
clean2 = FOREACH clean1 GENERATE user, time, org.apache.pig.tutorial.ToLower(query) as query;
因為日志文件中只包含一個單一的一天的查詢,我們只關心在一小時。激發查詢日志的時間戳格式是YYMMDDHHMMSS。調用ExtractHour UDF中提取小時(HH)的時間字段。
houred = FOREACH clean2 GENERATE user, org.apache.pig.tutorial.ExtractHour(time) as hour, query;
調用NGramGenerator UDF組成的n-gram的查詢。
ngramed1 = FOREACH houred GENERATE user, hour, flatten(org.apache.pig.tutorial.NGramGenerator(query)) as ngram;
使用DISTINCT quey 獲得獨特的n-gram的所有記錄。
ngramed2 = DISTINCT ngramed1;
使用該組操作員組記錄的N-gram和小時。
hour_frequency1 = GROUP ngramed2 BY (ngram, hour);
使用COUNT函數計數(點)的每個n-gram的。
hour_frequency2 = FOREACH hour_frequency1 GENERATE flatten($0), COUNT($1) as count;
n-gram的唯一的,使用組操作員組的記錄。現在每個組對應一個不同的N-gram,每個小時的計數。
uniq_frequency1 = GROUP hour_frequency2 BY group::ngram;
對于每個組,確定在此n-gram的具有特別高的頻率使用的小時。調用ScoreGenerator UDF計算得分的N-gram的“人氣”。
uniq_frequency2 = FOREACH uniq_frequency1 GENERATE flatten($0), flatten(org.apache.pig.tutorial.ScoreGenerator($1));
使用FOREACH生成運營商指定的字段的名稱。
uniq_frequency3 = FOREACH uniq_frequency2 GENERATE $1 as hour, $0 as ngram, $2 as score, $3 as count, $4 as mean;
使用FILTER運營商刪除所有記錄的得分小于或等于2.0。
iltered_uniq_frequency = FILTER uniq_frequency3 BY score > 2.0;
請使用ORDER運營商小時,得分排序剩下的記錄。、
ordered_uniq_frequency = ORDER filtered_uniq_frequency BY hour, score;
使用PigStorage功能,存儲的結果。輸出文件包含了一系列的N-gram以下字段:小時,NGRAM,得分,計算,意味著。
STORE ordered_uniq_frequency INTO '/tmp/tutorial-results' USING PigStorage();
內置函數
SIZE
計算任何PIG數據類型元素長度
例子
在這個例子中,在第一字段中的字符數來計算。
A = LOAD'數據'(F1:,F2 chararray:chararray,F3:chararray);(Apache的,開放的,源)(Hadoop的地圖,減少)(豬,豬,拉丁)
X = FOREACH的產生的SIZE(F1);
DUMP X;(6L)(6L)(3L)
int |
returns 1 |
long |
returns 1 |
float |
returns 1 |
double |
returns 1 |
chararray |
returns number of characters in the array |
bytearray |
returns number of bytes in the array |
tuple |
returns number of fields in the tuple |
bag |
returns number of tuples in bag |
map |
returns number of key/value pairs in map |
TOKENIZE
使用記號化的方式將字符創分割(一個元組中每個單詞)的
Example
In this example the strings in each row are split.
A = LOAD 'data' AS (f1:chararray);
DUMP A;
(Here is the first string.)
(Here is the second string.)
(Here is the third string.)
X = FOREACH A GENERATE TOKENIZE(f1);
DUMP X;
({(Here),(is),(the),(first),(string.)})
({(Here),(is),(the),(second),(string.)})
({(Here),(is),(the),(third),(string.)})
In this example a field delimiter is specified.
{code}
A = LOAD 'data' AS (f1:chararray);
B = FOREACH A TOKENIZE (f1,'||');
DUMP B;
{code}
IsEmpty
一包或地圖檢查是否是空的。
為IsEmpty(表達式) |
Example
In this example all students with an SSN but no name are located.
SSN = load 'ssn.txt' using PigStorage() as (ssn:long);
SSN_NAME = load 'students.txt' using PigStorage() as (ssn:long, name:chararray);
/* do a left outer join of SSN with SSN_Name */
X = JOIN SSN by ssn LEFT OUTER, SSN_NAME by ssn;
/* only keep those ssn's for which there is no name */
Y = filter X by IsEmpty(SSN_NAME);
LOAD/STORE 表達式
PIG 提供一組加載和存儲功能,同時也支持壓縮和存儲功能,PigStorage和的的TextLoader支持gzip和bzip壓縮讀取(加載)和write(寫)。BinStorage不支持壓縮
A = load ‘myinput.gz’;
store A into ‘myoutput.gz’;
To work with bzip compressed files, the input/output files need to have a .bz or .bz2 extension. Because the compression is block-oriented, bzipped files can be split across multiple maps.
A = load ‘myinput.bz’;
store A into ‘myoutput.bz’;
Note: PigStorage and TextLoader correctly read compressed files as long as they are NOT CONCATENATED FILES generated in this manner:
cat *.gz > text/concat.gz
cat *.bz > text/concat.bz
cat *.bz2 > text/concat.bz2
If you use concatenated gzip or bzip files with your Pig jobs, you will NOT see a failure but the results will be INCORRECT.
BinStorage
加載和存儲數據以機器可讀的格式
豬使用BinStorage的,加載和存儲多個MapReduce工作之間產生的臨時數據。
BinStorage作品表示的數據在磁盤上以機器可讀的格式。BinStorage不支持壓縮。
BinStorage支持多個位置(文件,目錄,水珠)作為輸入
JsonLoader,JsonStorage
加載或存儲JSON數據。
用法
使用JsonLoader加載JSON數據。
使用JsonStorage存儲JSON數據。
請注意,有沒有劃在JsonLoader或JsonStorer的概念。的數據進行編碼,在標準的JSON格式。JsonLoader可選的架構的結構參數。
Examples
In this example data is loaded with a schema.
a = load 'a.json' using JsonLoader('a0:int,a1:{(a10:int,a11:chararray)},a2:(a20:double,a21:bytearray),a3:[chararray]');
In this example data is loaded without a schema; it assumes there is a .pig_schema (produced by JsonStorage) in the input directory.
a = load 'a.json' using JsonLoader();
PigDump
在UTF-8格式存儲數據
用法
PigDump存儲數據,在人類可讀的UTF-8格式的元組。
Example
In this example PigDump is used with the STORE function.
STORE X INTO 'output' USING PigDump();
PigStorage
加載和存儲數據的結構化文本文件。
ield_delimiter |
默認字段分隔符“選項卡('\ t')。 您可以指定其他的字符作為字段分隔符,但一定要裝箱單引號中的字符。 |
用法
PigStorage是默認的功能,使用豬加載/存儲的數據。PigStorage支持結構化文本文件(以人類可讀的UTF-8格式)壓縮或非壓縮的形式(見處理壓縮)。所有的豬既簡單又復雜的數據類型()使用此功能可以讀/寫。輸入數據的負載可以是一個文件,一個目錄或水珠
復雜數據類型
復雜的數據類型的格式如下所示:
元組:包含(),項目用“,”
o 非空元組:(項目1,項目2,項目3)
o 空的元組是有效的:()
包:括由{},元組用“,”
o 非空袋:{代碼} {(tuple1),(tuple2),(tuple3)} {代碼}
o 空袋子是有效的:{}
地圖:[],項目分離“,”鍵和值之間用“#”括起來
o 非空的地圖:[KEY1,KEY2#VALUE1#value2的]
o 空地圖,地圖是有效的:[]
TextLoader
在UTF-8格式的非結構化數據加載。
Example
In this example TextLoader is used with the LOAD function.
A = LOAD 'data' USING TextLoader();
HBaseStorage
加載和存儲數據的HBase的表。
Syntax
HBaseStorage('columns', ['options']) |
用法
從HBase的HBaseStorage加載和存儲的數據。這個函數有兩個參數。第一個參數是一個空間分隔的列表列。第二個可選參數是一個空間分隔的列表的選項。上面列出的列語法和選項。
Load Example
In this example HBaseStorage is used with the LOAD function with an explicit schema.
raw = LOAD 'hbase://SomeTableName'
USING org.apache.pig.backend.hadoop.hbase.HBaseStorage(
'info:first_name info:last_name tags:work_* info:*', '-loadKey=true -limit=5') AS
(id:bytearray, first_name:chararray, last_name:chararray, tags_map:map[], info_map:map[]);
Store Example
In this example HBaseStorage is used to store a relation into HBase.
A = LOAD 'hdfs_users' AS (id:bytearray, first_name:chararray, last_name:chararray);
STORE A INTO 'hbase://users_table' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage(
'info:first_name info:last_name');
數學函數
ABS
返回絕對值的表達。
ACOS
返回一個表達式的反余弦值。
ASIN
返回一個表達式的反正弦。
ATAN
返回一個表達式的反正切值。
CBRT
返回的立方根的表達。
CEIL
返回向上舍入到最接近的整數的表達式的值。
COS
返回的三角余弦的表達。
EXP
返回歐拉數e的x次方。
FLOOR
一個表達式的返回值向下調整至最接近的整數。
RANDOM
返回一個偽隨機數
ROUND
四舍五入到整數表達式的返回值。
字符串函數
indexOf
返回一個字符在字符串中第一次出現的索引,從一開始索引搜索。
Syntax
INDEXOF(string, 'character', startIndex) |
LAST_INDEX_OF
返回一個字符在字符串中最后一次出現的索引,從一開始索引搜索落后。
LCFIRST
在一個字符串中的第一個字符轉換為小寫。
LOWER
在一個字符串中的所有字符轉換為小寫。
REGEX_EXTRACT
執行正則表達式匹配和提取匹配的參數定義的索引。
Syntax
REGEX_EXTRACT (string, regex, index) |
string |
The string in which to perform the match. |
regex |
The regular expression. |
index |
The index of the matched group to return. |
Example
This example will return the string '192.168.1.5'.
REGEX_EXTRACT('192.168.1.5:8020', '(.*):(.*)', 1);
REGEX_EXTRACT_ALL
執行正則表達式匹配和提取所有匹配的組。
REGEX_EXTRACT(字符串,正則表達式) |
例子
這個例子將返回的tuple(192.168.1.5,8020)。
REGEX_EXTRACT_ALL('192 .168.1.5:8020’,'(*)\:(*)');
SUBSTRING
返回一個字符串從一個給定的字符串。
TRIM
返回一個字符串的開頭和結尾的空白刪除的副本。
TRIM(表達) |
UCFIRST
返回一個字符串的第一個字符轉換為大寫。
日期時間函數
currentTime的
返回的DateTime對象的當前時間。
currentTime的() |
DaysBetween
返回兩個DateTime對象之間的天數。
DaysBetween(datetime1,DATETIME2) |
GetDay
返回之日起一個月從一個DateTime對象。
GetDay(日期時間) |
GetHour
返回時的某一天,從一個DateTime對象。
GetHour(日期時間) |
GetMilliSecond
第二個毫秒返回一個DateTime對象。
GetMilliSecond(日期時間) |
GetMinute
返回分鐘一個小時,從DateTime對象。
GetMinute(日期時間) |
getMonth
從DateTime對象返回月份的一年。
的getMonth(日期時間) |
GetWeek
返回星期一個星期內從一個DateTime對象。
GetWeek(日期時間) |
HoursBetween
返回兩個DateTime對象之間的小時數。
HoursBetween(datetime1,DATETIME2) |
MinutesBetween
返回兩個DateTime對象之間的分鐘數。
MinutesBetween(datetime1,DATETIME2) |
MonthsBetween
返回兩個DateTime對象之間的月數。
MonthsBetween(datetime1,DATETIME2) |
TODATE
返回一個DateTime對象,根據參數。
TODATE(毫秒) 迄今為止(iosstring) 直至目前為止(userstring,格式) TODATE(userstring,格式,時區) |
millseconds |
1970-01-01T00:00:00.000 Z的毫秒數(正或負)的偏移量。 |
isostring |
在ISO 8601格式的日期時間字符串。 |
userstring |
在用戶自定義格式的時間字符串。 |
格式 |
日期時間格式的模式字符串(見Java的SimpleDateFormat級的)。 |
時區 |
時區的字符串。無論是UTC偏移量和基于位置的格式可以被用作一個參數,而將被轉換為內部的時區的UTC偏移量的格式。 |
TOTUPLE
將一個或多個表達式輸入元組。
Syntax
REGEX_EXTRACT (string, regex, index) |
Example
In this example, fields f1, f2 and f3 are converted to a tuple.
a = LOAD 'student' AS (f1:chararray, f2:int, f3:float);
DUMP a;
(John,18,4.0)
(Mary,19,3.8)
(Bill,20,3.9)
(Joe,18,3.8)
b = FOREACH a GENERATE TOTUPLE(f1,f2,f3);
DUMP b;
((John,18,4.0))
((Mary,19,3.8))
((Bill,20,3.9))
((Joe,18,3.8))
TOBAG
將一個或多個表達式輸入包。
Example
In this example, fields f1 and f3 are converted to tuples that are then placed in a bag.
a = LOAD 'student' AS (f1:chararray, f2:int, f3:float);
DUMP a;
(John,18,4.0)
(Mary,19,3.8)
(Bill,20,3.9)
(Joe,18,3.8)
b = FOREACH a GENERATE TOBAG(f1,f3);
DUMP b;
({(John),(4.0)})
({(Mary),(3.8)})
({(Bill),(3.9)})
({(Joe),(3.8)})
TOMAP
轉換鍵/值對成地圖的表達。
TOMAP(關鍵表現,價值表達,關鍵表達,價值表達...) |
Example
In this example, student names (type chararray) and student GPAs (type float) are used to create three maps.
A = load 'students' as (name:chararray, age:int, gpa:float);
B = foreach A generate TOMAP(name, gpa);
store B into ‘results’;
Input (students)
joe smith 20 3.5
amy chen 22 3.2
leo allen 18 2.1
Output (results)
[joe smith#3.5]
[amy chen#3.2]
[leo allen#2.1]
參數替換
描述
在運行時替換參數值。
Syntax: Specifying Parameters Using the Pig Command Line
pig {–param param_name = param_value | –param_file file_name} [-debug | -dryrun] script |
指定參數
您可以指定參數名稱和參數值如下:
作為一個命令行的一部分。
在參數文件中,一個命令行的一部分。
用Declare語句,如豬腳本的一部分。
default語句,豬腳本的一部分。
參數替換不能被宏內使用。應明確地傳遞參數的宏和參數替代,只在頂層(請參閱DEFINE(宏))。
的參數的優先級如下:
最高 - 使用Declare語句定義的參數
下一步 - 在命令行中定義的參數
最低 - 在腳本中定義的參數
條款
豬 |
關鍵詞 注:執行,執行,并解釋還支持參數替換。 |
- 參數 |
標志。使用此選項時在命令行中的參數。 可以指定多個參數。如果指定了多個相同的參數,最后一個值將被使用,將產生一個警告。 可以結合優先考慮的命令行參數的命令行參數和參數文件。 |
param_name |
的參數的名稱。 該參數的名稱有一個標準的語言標識符的結構:它必須以字母開頭,或者下劃線后接任意數量的字母,數字,和下劃線。 參數名是區分大小寫的。 如果你傳遞一個參數到一個腳本,該腳本不使用時,此參數將被忽略。如果腳本有一個參數,并沒有提供值或取代,將產生一個錯誤。 |
param_value |
該參數的值。 參數值可以采取兩種形式: 在單或雙引號括起來的字符序列。在這種情況下,非上市的版本值的過程中使用的替代。引號內的值可以用反斜杠轉義字符(\)。單字的值,不要使用特殊字符,如%=沒有被引用。 在反引號括起來的命令。 一個參數的值,在以下兩種方式中,可以在其他參數方面表示,只要相關的參數的值已經被定義。 有沒有硬性的大小限制,除了參數需要存放到內存中。 |
- param_file |
標志。使用此選項時,該參數包含在一個文件中。 多個文件可以被指定。如果相同的參數是多次在文件中,最后一個值將被使用,會產生一個警告。如果一個參數出現在多個文件中,從最后的文件將被使用,會產生一個警告。 可以結合優先考慮的命令行參數的命令行參數和參數文件。 |
FILE_NAME |
含有一個或多個參數的文件的名稱。 參數文件將包含每行一個參數。空行是允許的。Perl樣式的注釋行(#)也是允許的。評論必須采取全系列#的第一個字符就行了。每個參數行會的形式為:param_name = param_value。空格是允許的,但周圍=是可選的。 |
- 調試 |
標志。使用此選項,在運行該腳本,并完全取代豬在當前工作目錄的腳本名為original_script_name.substituted |
使用-dryrun |
標志。使用此選項,腳本無法運行,完全取代豬在當前工作目錄的腳本名為original_script_name.substituted |
腳本 |
豬腳本。豬在豬命令行的腳本必須是最后一個元素。 如果豬命令行參數中指定的參數文件中的腳本應該包括一個$ param_name為每個para_name在命令行或參數文件。 如果指定參數使用預處理語句,腳本應該包括為%宣派或派%的違約。 在腳本中的參數名稱可以使用反斜杠字符(\),在這種情況下,不會發生替代逃脫。 |
%declare |
在豬腳本的預處理語句。 使用其他參數描述中的一個參數。 Declare語句之前處理的豬腳本運行。 使用declare定義的參數值的范圍是所有的行之后,直到下一次遇到相同的參數定義的聲明,聲明的聲明語句。 |
%default |
在豬腳本的預處理語句。 使用提供的參數的默認值。的默認值,具有最低的優先級,并且如果還沒有被定義的參數值通過其他手段使用。 default語句處理之前運行的豬腳本。 %申報的范圍是相同的。 |
Examples
Specifying Parameters in the Command Line
Suppose we have a data file called 'mydata' and a pig script called 'myscript.pig'.
mydata
1 2 3
4 2 1
8 3 4
myscript.pig
A = LOAD '$data' USING PigStorage() AS (f1:int, f2:int, f3:int);
DUMP A;
In this example the parameter (data) and the parameter value (mydata) are specified in the command line. If the parameter name in the command line (data) and the parameter name in the script ($data) do not match, the script will not run. If the value for the parameter (mydata) is not found, an error is generated.
$ pig –param data=mydata myscript.pig
(1,2,3)
(4,2,1)
(8,3,4)
SHELL和UTILITY命令
Shell命令
調用任何FsShell命令從豬八戒腳本或繁重的外殼內。
Syntax
fs subcommand subcommand_parameters |
Examples
In these examples a directory is created, a file is copied, a file is listed.
fs -mkdir /tmp
fs -copyFromLocal file-x file-y
fs -ls file-y
SH
從PIG腳本或 Grunt shell內調用任何sh shell命令。
Syntax
sh subcommand subcommand_parameters |
Example
In this example the ls command is invoked.
grunt> sh ls
bigdata.conf
nightly.conf
.....
grunt>
實用程序命令
clear
清除豬繁重的外殼和屏幕上的光標定位在屏幕上方的
Example
In this example the clear command clean up Pig grunt shell.
grunt> clear
exec
Run a Pig script.
Syntax
exec [–param param_name = param_value] [–param_file file_name] [script] |
Examples
In this example the script is displayed and run.
grunt> cat myscript.pig
a = LOAD 'student' AS (name, age, gpa);
b = LIMIT a 3;
DUMP b;
grunt> exec myscript.pig
(alice,20,2.47)
(luke,18,4.00)
(holly,24,3.27)
In this example parameter substitution is used with the exec command.
grunt> cat myscript.pig
a = LOAD 'student' AS (name, age, gpa);
b = ORDER a BY name;
STORE b into '$out';
grunt> exec –param out=myoutput myscript.pig
In this example multiple parameters are specified.
grunt> exec –param p1=myparam1 –param p2=myparam2 myscript.pig
history
Example
In this example the history command shows all the statements with line numbers and without them.
grunt> a = LOAD 'student' AS (name, age, gpa);
grunt> b = order a by name;
grunt> history
1 a = LOAD 'student' AS (name, age, gpa);
2 b = order a by name;
grunt> c = order a by name;
grunt> history -n
a = LOAD 'student' AS (name, age, gpa);
b = order a by name;
c = order a by name;
kill
Kills a job.
kill jobid |
Example
In this example the job with id job_0001 is killed.
grunt> kill job_0001
quit
Quits from the Pig grunt shell.
exit |
none |
no parameters |
The quit command enables you to quit or exit the Pig grunt shell.
In this example the quit command exits the Pig grunt shall.
grunt> quit
Example
In this example the script interacts with the results of commands issued via the Grunt shell.
grunt> cat myscript.pig
b = ORDER a BY name;
c = LIMIT b 10;
grunt> a = LOAD 'student' AS (name, age, gpa);
grunt> run myscript.pig
grunt> d = LIMIT c 3;
grunt> DUMP d;
(alice,20,2.47)
(alice,27,1.95)
(alice,36,2.27)
SET
將值指派給豬中使用的鍵
Syntax
set key 'value' |
用法
使用set命令來指定值的鍵,如表中所示。(豬和Hadoop)的所有鍵和相應的值是區分大小寫的。
關鍵 |
值 |
描述 |
default_parallel |
一個完整的數 |
設置減速器MapReduce工作所產生的豬的數量(請參閱 使用并行特性)。 |
debug |
On/off |
打開調試級別的日志記錄或關閉。 |
job.name |
單引號的字符串,其中包含作業的名稱。 |
設置用戶指定的名稱的工作 |
job.priority |
可接受的值(不區分大小寫):very_low, low, normal, high, very_high |
豬作業的優先級設置。 |
stream.skippath |
包含路徑的字符串。 |
對于流媒體,設置的路徑中不發貨數據(請參閱DEFINE(用戶定義函數(UDF),流媒體)和關于汽車,船舶)。 |
Examples
In this example key value pairs are set at the command line.
grunt> SET debug 'on'
grunt> SET job.name 'my job'
grunt> SET default_parallel 100
In this example default_parallel is set in the Pig script; all MapReduce jobs that get launched will use 20 reducers.
SET default_parallel 20;
A = LOAD 'myfile.txt' USING PigStorage() AS (t, u, v);
B = GROUP A BY t;
C = FOREACH B GENERATE group, COUNT(A.t) as mycount;
D = ORDER C BY mycount;
STORE D INTO 'mysortedcount' USING PigStorage();
In this example multiple key value pairs are set in the Pig script. These key value pairs are put in job-conf by Pig (making the pairs available to Pig and Hadoop). This is a script-wide setting; if a key value is defined multiple times in the script the last value will take effect and will be set for all jobs generated by the script.
...
SET mapred.map.tasks.speculative.execution false;
SET pig.logfile mylogfile.log;
SET my.arbitrary.key my.arbitary.value;
性能和效率
當組合使用
一般是用在非嵌套的foreach的情況下,所有的預測要么是組列或表達式的代數的UDF 讓你的UDF的代數表達式的組合 。
Example:
A = load 'studenttab10k' as (name, age, gpa);
B = group A by age;
C = foreach B generate ABS(SUM(A.gpa)), COUNT(org.apache.pig.builtin.Distinct(A.name)), (MIN(A.gpa) + MAX(A.gpa))/2, group.age;
explain C;
改進
A = load 'studenttab10k' as (name, age, gpa);
B = group A by age;
C = foreach B { D = distinct (A.name); generate group, COUNT(D);}
減速機估計
默認情況下,豬的數量決定了減速器,用于輸入地圖相的大小的基礎上一個給定的作業。輸入數據的大小劃分的 pig.exec.reducers.bytes.per.reducer參數值(默認1GB)的數量來確定減速。作業的減速器的最大數目是有限的由 pig.exec.reducers.max參數(默認值999)。
錯誤處理
多查詢執行豬的一次處理整個腳本或批處理語句。默認情況下,豬的是,無論在執行過程中的一些工作是否失敗嘗試運行的所有作業的結果。要檢查的作業成功或失敗使用這些選項之一。
首先,豬會記錄所有成功和失敗的存儲命令。輸出路徑確定的存儲命令。在執行一個匯總行表示成功,部分失敗或失敗的所有存儲命令。
其次,豬八戒返回不同的代碼完成后,這些場景:
返回碼0:所有作業成功
返回代碼1:用于檢索錯誤
返回代碼2:所有作業都已失敗
返回代碼3:有些工作已經失敗
在某些情況下,它可能是可取的失敗了整個劇本,當檢測到第一個失敗的作業。要做到這一點的“-F”或“stop_on_failure的”命令行標志。如果使用,豬八戒將停止執行,當檢測到第一個失敗的作業,并停止進一步的處理。這也意味著該文件失敗后,存儲在腳本中的命令將不會被執行(這可以被用來創建 “完成”文件)。
This is how the flag is used:
$ pig -F myscript.pig
or
$ pig -stop_on_failure myscript.pig
解決方案,其一是:
指定“-M”或“no_multiquery”恢復到舊名稱
指定一個自定義方案的LoadFunc /切片機
不會擴大,并通過使用LOAD語句的參數有一個計劃以外的“HDFS”或“文件”LoadFunc /切片不變的。
在SQL的情況下,SQLLOADER函數被調用,SQL :/ / mytable的“。
A = LOAD'SQL :/ / mytable的'的使用SQLLOADER();
隱式依賴關系
如果一個腳本的執行順序依賴于外豬知道,執行可能會失敗。
Example
In this script, MYUDF might try to read from out1, a file that A was just stored into. However, Pig does not know that MYUDF depends on the out1 file and might submit the jobs producing the out2 and out1 files at the same time.
...
STORE A INTO 'out1';
B = LOAD 'data2';
C = FOREACH B GENERATE MYUDF($0,'out1');
STORE C INTO 'out2';
To make the script work (to ensure that the right execution order is enforced) add the exec statement. The exec statement will trigger the execution of the statements that produce the out1 file.
...
STORE A INTO 'out1';
EXEC;
B = LOAD 'data2';
C = FOREACH B GENERATE MYUDF($0,'out1');
STORE C INTO 'out2';
性能增強
使用優化
豬八戒支持各種優化規則,默認情況下是打開的。熟悉這些規則。
使用類型
如果加載語句中沒有指定類型,pig不承擔任何類型數值計算。很多的時候,您的數據將是更小的,也許,整數或長。指定的類型算術運算的速度。它有一個附加的優點,早期的錯誤檢測
Use Types
If types are not specified in the load statement, Pig assumes the type of =double= for numeric computations. A lot of the time, your data would be much smaller, maybe, integer or long. Specifying the real type will help with speed of arithmetic computation. It has an additional advantage of early error detection.
--Query 1
A = load 'myfile' as (t, u, v);
B = foreach A generate t + u;
--Query 2
A = load 'myfile' as (t: int, u: int, v);
B = foreach A generate t + u;
Make Your UDFs Algebraic
Queries that can take advantage of the combiner generally ran much faster (sometimes several times faster) than the versions that don't. The latest code significantly improves combiner usage; however, you need to make sure you do your part. If you have a UDF that works on grouped data and is, by nature, algebraic (meaning their computation can be decomposed into multiple steps) make sure you implement it as such. For details on how to write algebraic UDFs, see Algebraic Interface.
A = load 'data' as (x, y, z)
B = group A by x;
C = foreach B generate group, MyUDF(A);
....PIG的reduce數量
如果既不是“默認設置平行”,也不使用PARALLEL子句,豬的數目設置的減速器,使用所輸入的數據的大小的基礎上一個啟發式。您可以設置這些屬性的值:
· pig.exec.reducers.bytes.per.reducer - 定義每減少輸入字節的數量,默認值是1000 * 1000 * 1000(1GB)。
· pig.exec.reducers.max - 定義減速器的數量的上限,默認為999。
的計算公式如下圖所示,是非常簡單的,并會隨著時間的推移有所改善。計算出的值需要在腳本中的所有輸入到豬腳本內的所有工作和應用的計算值。
#減速= MIN(pig.exec.reducers.max,總投入的大小(以字節為單位)/減速字節數)
Examples
In this example PARALLEL is used with the GROUP operator.
A = LOAD 'myfile' AS (t, u, v);
B = GROUP A BY t PARALLEL 18;
...
In this example all the MapReduce jobs that get launched use 20 reducers.
SET default_parallel 20;
A = LOAD ‘myfile.txt’ USING PigStorage() AS (t, u, v);
B = GROUP A BY t;
C = FOREACH B GENERATE group, COUNT(A.t) as mycount;
D = ORDER C BY mycount;
STORE D INTO ‘mysortedcount’ USING PigStorage();
使用LIMIT
A = load 'myfile' as (t, u, v);
B = limit A 500;
Top results:
A = load 'myfile' as (t, u, v);
B = order A by t;
C = limit B 500;
使用 DISTINCT 拋棄GROUP BY/GENERATE
To extract unique values from a column in a relation you can use DISTINCT or GROUP BY/GENERATE. DISTINCT is the preferred method; it is faster and more efficient.
Example using GROUP BY - GENERATE:
A = load 'myfile' as (t, u, v);
B = foreach A generate u;
C = group B by u;
D = foreach C generate group as uniquekey;
dump D;
Example using DISTINCT:
A = load 'myfile' as (t, u, v);
B = foreach A generate u;
C = distinct B;
dump C;
結果壓縮設置
結果壓縮的中級
如果你的豬腳本生成一個序列的MapReduce工作,你可以在壓縮中間作業使用LZO壓縮的輸出。(使用“ EXPLAIN運營商,以確定如果你的腳本生成多個MapReduce工作。)
通過這樣做,你會節省空間,用來存儲HDFS使用豬的中間數據和潛在的改進查詢的執行速度。在一般情況下,生成更多的中間數據,在存儲和速度,導致更多的好處。
您可以設置這些屬性的值:
· pig.tmpfilecompression - 確定是否要壓縮的臨時文件(設置為默認值false)。
· pig.tmpfilecompression.codec - 指定使用的壓縮編解碼器。目前,pig接受“GZ”和“LZO”可能的值。然而,由于LZO是在GPL許可下(默認情況下禁用),您將需要配置您的群集使用LZO編解碼器,利用此功能。有關詳細信息,請參閱http://code.google.com/p/hadoop-gpl-compression /wiki/FAQ。
在不平凡的查詢(一個運行的時間超過兩分鐘),我們看到了顯著的改善,無論是在查詢等待時間和空間使用情況。對于某些查詢,我們看到最多節省96%的磁盤和高達4倍的查詢速度上升。當然,性能特點是非常查詢和數據依賴和測試需要進行,以確定收益。我們沒有看到任何放緩的測試中,我們做灌胃,這意味著你至少節省空間,同時使用壓縮。
用gzip我們看到了一個更好的壓縮(96-99%),但在成本的4%放緩。因此,我們不建議使用gzip壓縮的。
、Example
-- launch Pig script using lzo compression
java -cp $PIG_HOME/pig.jar
-Djava.library.path=<path to the lzo library>
-Dpig.tmpfilecompression=true
-Dpig.tmpfilecompression.codec=lzo org.apache.pig.Main myscript.pig
測試和調試
診斷運算符