String Scala/Spark高效部分字符串匹配

String Scala/Spark高效部分字符串匹配,string,scala,apache-spark,String,Scala,Apache Spark,我正在用Scala用Spark编写一个小程序,遇到了一个问题。我有一个单字字符串列表/RDD和一个句子列表/RDD,其中可能包含单字列表中的单词,也可能不包含单字列表中的单词。i、 e val singles = Array("this", "is") val sentence = Array("this Date", "is there something", "where are something", "this is a string") 我想从单曲中选择包含一个或多个单词的句子,结果

我正在用Scala用Spark编写一个小程序,遇到了一个问题。我有一个单字字符串列表/RDD和一个句子列表/RDD,其中可能包含单字列表中的单词,也可能不包含单字列表中的单词。i、 e

val singles = Array("this", "is")
val sentence = Array("this Date", "is there something", "where are something", "this is a string")
我想从单曲中选择包含一个或多个单词的句子,结果应该是:

output[(this, Array(this Date, this is a String)),(is, Array(is there something, this is a string))]

我考虑了两种方法,一种是通过拆分句子和使用.contains进行过滤。另一种方法是将句子拆分并格式化为RDD,并使用.join进行RDD交叉。我在看大约50个单词和500万个句子,哪种方法更快?还有其他解决办法吗?您能帮我编码吗?我的代码似乎没有结果(尽管它编译并运行时没有错误)

我刚刚尝试解决您的问题,最后得到了以下代码:

def check(s:String, l: Array[String]): Boolean = {
  var temp:Int = 0
  for (element <- l) {
    if (element.equals(s)) {temp = temp +1}
  }
  var result = false
  if (temp > 0) {result = true}
  result
}
val singles = sc.parallelize(Array("this", "is"))
val sentence = sc.parallelize(Array("this Date", "is there something", "where are something", "this is a string"))
val result = singles.cartesian(sentence)
                    .filter(x => check(x._1,x._2.split(" ")) == true )
                    .groupByKey()
                    .map(x => (x._1,x._2.mkString(", ") ))  // pay attention here(*)
result.foreach(println)
使用该映射行(使用mkString命令),我可以获得如下更可读的输出:

(is,CompactBuffer(is there something, this is a string))     
(this,CompactBuffer(this Date, this is a string))
(is,is there something, this is a string)
(this,this Date, this is a string)
希望能有所帮助


FF

您可以创建一组必需的键,在句子中查找键并按键分组

val singles = Array("this", "is")

val sentences = Array("this Date", 
                      "is there something", 
                      "where are something", 
                      "this is a string")

val rdd = sc.parallelize(sentences) // create RDD

val keys = singles.toSet            // words required as keys.

val result = rdd.flatMap{ sen => 
                    val words = sen.split(" ").toSet; 
                    val common = keys & words;       // intersect
                    common.map(x => (x, sen))        // map as key -> sen
                }
                .groupByKey.mapValues(_.toArray)     // group values for a key
                .collect                             // get rdd contents as array

// result:
// Array((this, Array(this Date, this is a string)),
//       (is,   Array(is there something, this is a string)))

500万句的笛卡尔公式将是一个艰难的曲奇,但好答案永远不会少。你可能是对的。。。但是你可以试试看它是怎么工作的。。。我承认这只是一个“快速”的答案,我可以找到一个改进的方法。事实上,这一点都不坏,考虑到它使用的是Spark RDD,它比我的版本稍慢,而我的版本只在Master上运行,但我认为对于更多的数据,你的要比我的好得多;此外,如果你仔细想想,笛卡尔可能是最有效的搜索方式。鉴于每个单词的平均句子数为10万句,分组可能不是一个真正的选择。(单词、句子)将是更好的结尾格式我应该如何运行子字符串匹配?想象一下,这里没有单词列表,而是短语列表:val singles=Array(“这本书”,“很棒”)在那里我无法写出这个句子!有什么建议吗?