我有一个包含470纬度和经度值的文本文件。我想计算所有点对的距离。任何人都可以告诉我如何在Apache Spark中使用JAVA作为编程语言。
〜此致 CHANDAN
答案 0 :(得分:1)
你可以获取你的RDD点,然后在它自己的RDD上使用笛卡尔函数,这将返回一个带有所有点组合对的RDD,然后你可以映射它并计算每对的距离。
答案 1 :(得分:0)
为了补充@Holden的回答,这是一个说明这个想法的Java片段。该代码假定您有一个文件,其中每一行由空格分隔的纬度和经度值组成。
JavaRDD<String> input = sc.textFile("/path/to/your/file");
// map each line to pairs of Double, representing the points
JavaPairRDD<Double, Double> points = input.mapToPair(
new PairFunction<String, Double, Double>() {
public Tuple2<Double, Double> call(String s) throws Exception {
String[] parts = s.split(" +");
return new Tuple2<>(
Double.parseDouble(parts[0]),
Double.parseDouble(parts[1]));
}
}
);
// then, get the cartesian product of the point set, and map
// each resulting pair of points to the distance between them
JavaDoubleRDD distances = points.cartesian(points).mapToDouble(new DoubleFunction<Tuple2<Tuple2<Double, Double>, Tuple2<Double, Double>>>() {
public double call(Tuple2<Tuple2<Double, Double>, Tuple2<Double, Double>> pointPair) throws Exception {
Double lat1 = pointPair._1()._1();
Double lon1 = pointPair._1()._2();
Double lat2 = pointPair._2()._1();
Double lon2 = pointPair._2()._2();
return dist(lat1, lon1, lat2, lon2); // omitted for clarity
}
});
// then, do something with your distances
distances.foreach(new VoidFunction<Double>() {
public void call(Double aDouble) throws Exception {
System.out.println("D: " + aDouble);
}
});
当然,如果由于某种原因需要保持每对点之间的链接以及它们之间的距离,只需映射到由一对点组成的对作为第一个元素,距离作为第二个。
希望它有所帮助。干杯!