pig实例一

这里我们给出一个学生表(学号,姓名,性别,年龄,所在系),其中含有如下几条记录并保存在/home/hadoop/ziliao/student.txt文件:

201000101:李勇:男:20:计算机软件与理论
201000102:王丽:女:19:计算机软件与理论
201000103:刘花:女:18:计算机应用技术
201000104:李肖:男:19:计算机系统结构
201000105:吴达:男:19:计算机系统结构
201000106:滑可:男:19:计算机系统结构

它们所对应的数据类型如下所示:
Student(sno:chararray, sname:chararray, ssex:chararray, sage:int, sdept:chararray)
我们将在不同的运行方式下取出各个学生的姓名和年龄两个字段,执行结果如下:

李勇 20 
王丽 19 
刘花 18 
李肖 19 
吴达 19 
滑可 19

1、local模式
a、grunt shell

hadoop@ubuntu:~$ pig -x local
--加载数据(注意“=”左右两边要空格)
grunt>> A = load '/home/hadoop/ziliao/student.txt' using PigStorage(':') as (sno:chararray, sname:chararray, ssex:chararray, sage:int, sdept:chararray);
--从A中选出Student相应的字段(注意“=”左右两边要空格)
grunt>> B = foreach A generate sname, sage;
--将B中的内容输出到屏幕上
grunt>> dump B;
--将B的内容输出到本地文件中
grunt>> store B into '/home/hadoop/ziliao/result.txt';
--查看本地文件内容,没有''
grunt>> cat /home/hadoop/ziliao/result.txt;

b、脚本文件
脚本文件实质上是pig命令的批处理文件。
我们给出的script.pig文件包含以下内容:

A = load '/home/hadoop/ziliao/student.txt' using PigStorage(':') as (sno:chararray, sname:chararray, ssex:chararray, sage:int, sdept:chararray);
B = foreach A generate sname, sage;
dump B;
store B into '/home/hadoop/ziliao/result.txt';

然后通过执行pig -x local script.pig即可。
想看执行结果,可执行如下命令查看:

grunt>> cat /home/hadoop/ziliao/result.txt;

c、嵌入式程序

package com.ljq.pig;

import java.io.IOException;

import org.apache.pig.PigServer;

public class PigLocal {

        public static void main(String[] args) {
                try {
                        PigServer  server = new PigServer("local"); //Local模式
                        //PigServer  server = new PigServer("mapreduce"); //MapReduce模式
                        run(server);
                } catch (Exception e) {
                        e.printStackTrace();
                }  
                
        }
        
        private static void run(PigServer server) throws IOException{
                server.registerQuery("A = load '/home/hadoop/ziliao/student.txt' using PigStorage(':') as (sno:chararray, sname:chararray, ssex:chararray, sage:int, sdept:chararray);");
                server.registerQuery("B = foreach A generate sname, sage;");
                server.store("B", "/home/hadoop/ziliao/result.txt"); //home/hadoop/ziliao/result.txt存在要先删除,不然执行会报异常。
        }
}

2、MapReduce模式
就是把/home/hadoop/ziliao/student.txt文件放到hdfs中操作,其他操作跟local模式一样,也分为如下三种操作方式:
a.grunt shell

hadoop@ubuntu:~$ pig  

b.脚本文件

pig script.pig
c.嵌入式程序


 

原文地址:https://www.cnblogs.com/linjiqin/p/2956550.html