[spark]倒排索引

ref:   http://www.aboutyun.com/thread-12900-1-1.html

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.SparkContext._
import scala.collection.mutable


/**
 *
 * Created by youxingzhi on 15-5-3.
 */
object InvertedIndex {
  def main (args: Array[String]) {
    val conf = new SparkConf().setAppName("InvertedIndex").setMaster("spark://192.168.1.170:7077")
    val spark =  new SparkContext(conf)
    spark.addJar("/home/youxingzhi/IdeaProjects/WordCount/out/artifacts/Spark1_jar/Spark1.jar")
    //textFile可以通过设置第二个参数来指定slice个数(slice与Hadoop里的split/block概念对应,一个task处理一个slice)。Spark默认将Hadoop上一个block对应为一个slice,但可以调大slice的个数,但不能比block的个数小,这就需要知道HDFS上一个文件的block数目,可以通过50070的dfs的jsp来查看。
    val words = spark.textFile("hdfs://master:8020/InvertedIndex",1).map(file=>file.split("\t")).
      map(item =>{
      (item(0),item(1))
    }).flatMap(file => {
      var map = mutable.Map[String,String]()
      val words = file._2.split(" ").iterator
      val doc = file._1
      while(words.hasNext){
        map+=(words.next() -> doc)
      }
      map
    })


    //save to file
    words.reduceByKey(_+" "+_).map(x=>{
      x._1+"\t"+x._2
    }).saveAsTextFile("hdfs://master:8020/test3")
  }
}
倒排索引是一种常用的数据结构,它将词汇表中每个单词与包含该单词的文档列表关联起来,以便实现文本搜索和相关性排序。在Spark中,我们可以使用RDD来实现倒排索引。下面是一个简单的示例代码: ```python from pyspark import SparkConf, SparkContext conf = SparkConf().setAppName("InvertedIndex") sc = SparkContext(conf=conf) # 定义输入数据 data = [ ("doc1", "hello world"), ("doc2", "hello spark"), ("doc3", "hello hadoop"), ("doc4", "hello world") ] # 创建RDD并切分单词 words_rdd = sc.parallelize(data).flatMap(lambda x: [(word, x[0]) for word in x[1].split()]) # 对单词进行分组 grouped_rdd = words_rdd.groupByKey() # 构建倒排索引 inverted_index = grouped_rdd.map(lambda x: (x[0], list(x[1]))) # 输出结果 for pair in inverted_index.collect(): print(pair) ``` 在这个示例中,我们首先定义了输入数据。然后,我们使用`flatMap`操作将每个文档中的单词与文档ID关联起来,并创建一个包含单词和文档ID对的RDD。接下来,我们使用`groupByKey`操作对单词进行分组,并创建一个包含每个单词及其对应文档ID列表的RDD。最后,我们使用`map`操作将每个单词和其对应的文档ID列表构建成一个键值对,并输出结果。 需要注意的是,该实现方法可能会存在一些性能瓶颈,特别是在处理大规模数据时。为了提高性能,我们可以使用更高级别的API,如DataFrame和DataSet,或者使用分布式数据库,如HBase、Cassandra等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值