pig中map的组键值

uoifb46i  于 2021-06-24  发布在  Pig
关注(0)|答案(1)|浏览(476)

我是新来的。嘿,我们有个档案

[a#1,b#2,c#3]
[a#4,b#5,c#6]
[a#7,b#8,c#9]

Pig手稿

A = LOAD 'txt' AS (in: map[]);
B = FOREACH A GENERATE in#'a';
DUMP B;

我们知道,我们可以在关键的价值观喂养。在上面的示例中,我使用了包含键“a”的值的Map。假设我不知道键,我想根据关系中的键对值进行分组并转储它。

(a,{1,4,7})
(b,{2,5,8})
(c,{3,6,9})

pig是否允许此类操作或需要使用自定义项?请帮我渡过难关。谢谢。

uklbhaso

uklbhaso1#

您可以创建自定义 UDF 将Map转换为袋子(使用清管器v0.10.0):

package com.example;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;

public class MapToBag extends EvalFunc<DataBag> {

    private static final BagFactory bagFactory = BagFactory.getInstance();
    private static final TupleFactory tupleFactory = TupleFactory.getInstance();

    @Override
    public DataBag exec(Tuple input) throws IOException {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) input.get(0);
            DataBag result = null;
            if (map != null) {
                result = bagFactory.newDefaultBag();
                for (Entry<String, Object> entry : map.entrySet()) {
                    Tuple tuple = tupleFactory.newTuple(2);
                    tuple.set(0, entry.getKey());
                    tuple.set(1, entry.getValue());
                    result.add(tuple);
                }
            }
            return result;

        }
        catch (Exception e) {
            throw new RuntimeException("MapToBag error", e);
        }
    }
}

然后:

B = foreach A generate 
      flatten(com.example.MapToBag(in)) as (k:chararray, v:chararray);
describe B;
B: {k: chararray,v: chararray}

现在按键分组并使用嵌套的foreach:

C = foreach (group B by k) {
    value = foreach B generate v;
    generate group as key, value;
};
dump C;
(a,{(1),(4),(7)})
(b,{(2),(5),(8)})
(c,{(3),(6),(9)})

相关问题