Mapreduce java程序搜索四叉树索引,也运行几何引擎.包含使用WKT文件来确认多边形中的点



这篇文章是针对我之前的问题建议的map reduce实现:"如何优化Hive中1个大文件/表的扫描以确认/检查是否包含在wkt几何形状中"

我并不精通编写map-reduce的java程序,主要使用Hive或者Pig或者spark在Hadoop生态系统中进行开发。为了给出手头任务的背景:我试图将每个纬度/经度ping与相应的ZIP邮政编码相关联。我有一个WKT多多边形形状文件(500 MB)与所有的zip信息。我已经在Hive中加载了这个,可以使用ST_Contains(多边形,点)进行连接。然而,它需要很长时间才能完成。为了克服这个瓶颈,我试图利用ESRI("https://github.com/Esri/gis-tools-for-hadoop/tree/master/samples/point-in-polygon-aggregation-mr")中的例子,通过构建一个四叉树索引来搜索从latlong在多边形中派生的点。

我已经设法编写代码,它阻塞了集群的Java堆内存。任何关于改进代码或寻找不同方法的建议将不胜感激:错误信息:错误:Java堆空间ApplicationMaster杀死的容器。应要求杀死集装箱。退出代码是143容器以非零退出代码143退出

我的代码:
public class MapperClass extends Mapper<LongWritable, Text, Text, IntWritable> {
    // column indices for values in the text file
    int longitudeIndex;
    int latitudeIndex;
    int wktZip; 
    int wktGeom;
    int wktLineCount;
    int wktStateID;
    // in boundaries.wkt, the label for the polygon is "wkt"
    //creating ArrayList to hold details of the file
    ArrayList<ZipPolyClass> nodes = new ArrayList<ZipPolyClass>();
    String labelAttribute;
    EsriFeatureClass featureClass;
    SpatialReference spatialReference;
    QuadTree quadTree;
    QuadTreeIterator quadTreeIter;
    BufferedReader csvWkt;
    // class to store all the values from wkt file and calculate geometryFromWKT 
    public class ZipPolyClass {
        public String zipCode;
        public String wktPoly;
        public String stateID;
        public int indexJkey;
        public Geometry wktGeomObj; 
        public ZipPolyClass(int ijk, String z, String w, String s ){
            zipCode = z;
            wktPoly = w;
            stateID = s;
            indexJkey = ijk;
            wktGeomObj = GeometryEngine.geometryFromWkt(wktPoly, 0, Geometry.Type.Unknown);
        }
    }

    //building quadTree Index from WKT multiPolygon and creating an iterator
    private void buildQuadTree(){
        quadTree = new QuadTree(new Envelope2D(-180, -90, 180, 90), 8);
        Envelope envelope = new Envelope();
        int j=0;
        while(j<nodes.size()){
            nodes.get(j).wktGeomObj.queryEnvelope(envelope);
            quadTree.insert(j, new Envelope2D(envelope.getXMin(), envelope.getYMin(), envelope.getXMax(), envelope.getYMax()));
        }
        quadTreeIter = quadTree.getIterator();
    }

    /**
     * Query the quadtree for the feature containing the given point
     * 
     * @param pt point as longitude, latitude
     * @return index to feature in featureClass or -1 if not found
     */
    private int queryQuadTree(Point pt)
    {
        // reset iterator to the quadrant envelope that contains the point passed
        quadTreeIter.resetIterator(pt, 0);
        int elmHandle = quadTreeIter.next();
        while (elmHandle >= 0){
            int featureIndex = quadTree.getElement(elmHandle);
            // we know the point and this feature are in the same quadrant, but we need to make sure the feature
            // actually contains the point
            if (GeometryEngine.contains(nodes.get(featureIndex).wktGeomObj, pt, spatialReference)){
                return featureIndex;
            }
            elmHandle = quadTreeIter.next();
        }
        // feature not found
        return -1;
    }

    /**
     * Sets up mapper with filter geometry provided as argument[0] to the jar
     */
    @Override
    public void setup(Context context)
    {
        Configuration config = context.getConfiguration();
        spatialReference = SpatialReference.create(4326);
        // first pull values from the configuration     
        String featuresPath = config.get("sample.features.input");
        //get column reference from driver class 
        wktZip = config.getInt("sample.features.col.zip", 0);
        wktGeom = config.getInt("sample.features.col.geometry", 18);
        wktStateID = config.getInt("sample.features.col.stateID", 3);
        latitudeIndex = config.getInt("samples.csvdata.columns.lat", 5);
        longitudeIndex = config.getInt("samples.csvdata.columns.long", 6);
        FSDataInputStream iStream = null;
        try {
            // load the text WKT file provided as argument 0
            FileSystem hdfs = FileSystem.get(config);
            iStream = hdfs.open(new Path(featuresPath));
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            String wktLine ;
            int i=0;
            while((wktLine = br.readLine()) != null){
                String [] val = wktLine.split("\|");
                String qtZip = val[wktZip];
                String poly = val[wktGeom];
                String stID = val[wktStateID];
                ZipPolyClass zpc = new ZipPolyClass(i, qtZip, poly, stID);
                nodes.add(i,zpc);
                i++; // increment in the loop before end
                }
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        } 
        finally
        {
            if (iStream != null)
            {
                try {
                    iStream.close();
                } catch (IOException e) { }
            }
        }
        // build a quadtree of our features for fast queries
        if (!nodes.isEmpty()) {
            buildQuadTree();
        }
    }
    @Override
    public void map(LongWritable key, Text val, Context context)
            throws IOException, InterruptedException {
        /* 
         * The TextInputFormat we set in the configuration, by default, splits a text file line by line.
         * The key is the byte offset to the first character in the line.  The value is the text of the line.
         */
        String line = val.toString();
        String [] values = line.split(",");
        // get lat long from file and convert to float
        float latitude = Float.parseFloat(values[latitudeIndex]);
        float longitude = Float.parseFloat(values[longitudeIndex]);
        // Create our Point directly from longitude and latitude
        Point point = new Point(longitude, latitude);

        int featureIndex = queryQuadTree(point);
        // Each map only processes one record at a time, so we start out with our count 
                // as 1. Since we have a distinct record file we will not run reducer
                IntWritable one = new IntWritable(1);
        if (featureIndex >= 0){
            String zipTxt =nodes.get(featureIndex).zipCode;
            String stateIDTxt = nodes.get(featureIndex).stateID;
            String latTxt = values[latitudeIndex];
            String longTxt = values[longitudeIndex];
            String pointTxt = point.toString();
            String name;
            name = zipTxt+"t"+stateIDTxt+"t"+latTxt+"t"+longTxt+ "t" +pointTxt;
            context.write(new Text(name), one);
        } else {
            context.write(new Text("*Outside Feature Set"), one);
        }
    }
}

我能够解决内存不足的问题通过修改arrayList 保存arrayList <几何>类型。

创建一个类对象(大约50k)来保存文本文件的每一行,消耗了所有的java堆内存。在此更改之后,代码即使在1节点的虚拟沙箱中也能正常运行。我能够在6分钟内处理大约4000万行数据。

最新更新