【问题标题】:Distance between all pairs of points in Apache SparkApache Spark中所有点对之间的距离
【发布时间】:2015-03-20 05:00:46
【问题描述】:

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

~问候, 钱丹

【问题讨论】:

  • 到目前为止你做了什么?你能告诉我们一些代码以及问题出在哪里吗?

标签: mapreduce apache-spark


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    为了补充@Holden 的答案,这里有一个Java sn-p 说明了这个想法。该代码假定您有一个文件,其中每一行都包含用空格分隔的纬度和经度值。

    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);
      }
    });
    

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

    希望它有所帮助。干杯!

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 2017-04-24
      • 2019-07-10
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多