Apache pig 学习

jopen 8年前

一.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支持多个位置(文件,目录,水珠)作为输入


JsonLoaderJsonStorage

加载或存储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)

Terms

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(字符串,正则表达式)

例子

这个例子将返回的tuple192.168.1.5,8020)。

REGEX_EXTRACT_ALL'192 .168.1.5:8020’'*\:(*';

 

SUBSTRING

返回一个字符串从一个给定的字符串。

TRIM

返回一个字符串的开头和结尾的空白删除的副本。

句法

TRIM(表达)

UCFIRST

返回一个字符串的第一个字符转换为大写。

日期时间函数

currentTime

返回的DateTime对象的当前时间。

句法

currentTime的()

DaysBetween

返回两个DateTime对象之间的天数。

句法

DaysBetweendatetime1DATETIME2

GetDay

返回之日起一个月从一个DateTime对象。

句法

GetDay(日期时间)

GetHour

返回时的某一天,从一个DateTime对象。

句法

GetHour(日期时间)

GetMilliSecond

第二个毫秒返回一个DateTime对象。

句法

GetMilliSecond(日期时间)

GetMinute

返回分钟一个小时,从DateTime对象。

句法

GetMinute(日期时间)

getMonth

从DateTime对象返回月份的一年。

句法

getMonth(日期时间)

GetWeek

返回星期一个星期内从一个DateTime对象。

句法

GetWeek(日期时间)

HoursBetween

返回两个DateTime对象之间的小时数。

句法

HoursBetweendatetime1DATETIME2

MinutesBetween

返回两个DateTime对象之间的分钟数。

句法

MinutesBetweendatetime1DATETIME2

MonthsBetween

返回两个DateTime对象之间的月数。

句法

MonthsBetweendatetime1DATETIME2

TODATE

返回一个DateTime对象,根据参数。

句法

TODATE(毫秒)

迄今为止(iosstring

直至目前为止(userstring,格式)

TODATEuserstring,格式,时区)

条款

millseconds

1970-01-01T0000:00.000 Z的毫秒数(正或负)的偏移量。

isostring

ISO 8601格式的日期时间字符串。

userstring

在用户自定义格式的时间字符串。

格式

日期时间格式的模式字符串(见JavaSimpleDateFormat级的)。

时区

时区的字符串。无论是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)

 

 

SHELLUTILITY命令

Shell命令

FS

调用任何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.

Syntax

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.

Syntax

exit

Terms

none

no parameters

Usage

The quit command enables you to quit or exit the Pig grunt shell.

Example

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);

....PIGreduce数量

如果既不是“默认设置平行”,也不使用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

 

 

 

 




测试和调试

诊断运算符