How to turn (A, B, C) into (AB, AC, BC) with Pig?

僤鯓⒐⒋嵵緔 提交于 2019-12-22 17:50:54

问题


In Pig, given the following Bag: (A, B, C), can I somehow calculate the unique combinations of all the values? The result I'm looking for is something like (AB, AC, BC). I'm disregarding BA, CA, CB since they would become duplicates of the existing values if sorted in alphabetic order.


回答1:


The only way of doing something like that is writing a UDF. This one will do exactly what you want:

public class CombinationsUDF extends EvalFunc<DataBag> {
    public DataBag exec(Tuple input) throws IOException {
        List<Tuple> bagValues = new ArrayList<Tuple>();
        Iterator<Tuple> iter = ((DataBag)input.get(0)).iterator();
        while (iter.hasNext()) {
            bagValues.add(iter.next());
        }

        List<Tuple> outputTuples = new ArrayList<Tuple>();
        for (int i = 0; i < bagValues.size() - 1; i++) {
            List<Object> currentTupleValues = bagValues.get(i).getAll();

            for (int j = i + 1; j < bagValues.size(); j++) {
                List<Object> aux = new ArrayList<Object>(currentTupleValues);
                aux.addAll(bagValues.get(j).getAll());
                outputTuples.add(TupleFactory.getInstance().newTuple(aux));
            }
        }

        DataBag output = BagFactory.getInstance().newDefaultBag(outputTuples);
        return output;
    }
}


来源:https://stackoverflow.com/questions/29994246/how-to-turn-a-b-c-into-ab-ac-bc-with-pig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!