在本章中,我们将了解如何以批处理模式运行Apache Pig脚本.
猪脚本中的注释
写作时一个文件中的脚本,我们可以在其中包含注释,如下所示.
多行注释
我们将开始多行注释使用'/*',以'*/'结尾.
/* These are the multi-line comments In the pig script */
单行注释
我们将以' - '开始单行评论.
--we can write single line comments like this.
以批处理模式执行Pig脚本
在批处理模式下执行Apache Pig语句时,请按照以下步骤操作.
第1步
在一个文件中写下所有必需的Pig Latin语句.我们可以将所有Pig Latin语句和命令写在一个文件中,并将其保存为 .pig 文件.
步骤2
执行Apache Pig脚本.您可以从shell(Linux)执行Pig脚本,如下所示.
本地模式 | MapReduce模式 |
---|---|
$ pig -x local Sample_script.pig | $ pig -x mapreduce Sample_script.pig |
您也可以使用exec命令从Grunt shell执行它,如下所示.
grunt> exec /sample_script.pig
从HDFS执行Pig脚本
我们还可以执行驻留在的Pig脚本HDFS.假设在名为/pig_data/的HDFS目录中有一个名为 Sample_script.pig 的Pig脚本.我们可以执行它,如下所示.
$ pig -x mapreduce hdfs://localhost:9000/pig_data/Sample_script.pig
示例
假设我们在HDFS中有一个文件 student_details.txt ,其中包含以下内容.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad 002,siddarth,Battacharya,22,9848022338,Kolkata003,Rajesh,Khanna,22,9848022339,Delhi 004,Preethi,Agarwal,21,9848022330,Pune 005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar 006,Archana,Mishra,23,9848022335,Chennai 007,Komal,Nayak,24,9848022334,trivendram 008,Bharathi,Nambiayar,24,9848022333,Chennai
我们在同一个HDFS目录中也有一个名为 sample_script.pig 的示例脚本.该文件包含对学生关系执行操作和转换的语句,如下所示.
student = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',') as (id:int, firstname:chararray, lastname:chararray, phone:chararray, city:chararray);student_order = ORDER student BY age DESC; student_limit = LIMIT student_order 4; Dump student_limit;
脚本的第一个语句将加载名为的文件中的数据student_details.txt 作为名为学生的关系.
脚本的第二个语句将安排该元组的元组关系按降序排列,基于年龄,并将其存储为 student_order .
脚本的第三个语句将存储第一个4个 student_order 元组为 student_limit .
最后第四个语句将转储关系的内容 student_limit .
现在让我们执行 sample_script.pig ,如下所示.
$./pig -x mapreduce hdfs://localhost:9000/pig_data/sample_script.pig
Apache Pig被执行并为您提供以下内容的输出.
(7,Komal,Nayak,24,9848022334,trivendram)(8,Bharathi,Nambiayar,24,9848022333,Chennai) (5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar) (6,Archana,Mishra,23,9848022335,Chennai)2015-10-19 10:31:27,446 [main] INFO org.apache.pig.Main - Pig script completed in 12minutes, 32 seconds and 751 milliseconds (752751 ms)