Apache Spark 中所有点对之间的距离

Distance between all pairs of points in Apache Spark

我有一个包含 470 个纬度和经度值的文本文件。我想计算所有点对的距离。谁能告诉我如何使用 JAVA 作为编程语言在 Apache Spark 中做到这一点。

~此致 钱丹

您可以获取点的 RDD,然后在 RDD 上对其自身使用笛卡尔函数,这将 return 一个包含所有点组合对的 RDD,然后您可以对其进行映射并计算每对的距离。

为了补充@Holden 的回答,这里有一个 Java 片段说明了这个想法。该代码假定您有一个文件,其中每一行都包含由 space.

分隔的纬度和经度值
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);
  }
});

当然,如果出于某种原因需要保持每对点之间的link和它们之间的距离,只需映射到由作为第一个元素的点对和距离组成的对作为第二。

希望对您有所帮助。干杯!