Apache spark 带函数迭代器的spark并行化

Apache spark 带函数迭代器的spark并行化,apache-spark,pyspark,warc,Apache Spark,Pyspark,Warc,我有一个迭代器,它对WARC文档序列进行操作,并为每个文档生成标记的修改列表: class MyCorpus(object): def __init__(self, warc_file_instance): self.warc_file = warc_file_instance def clean_text(self, html): soup = BeautifulSoup(html) # create a new bs4 object from the html data lo

我有一个迭代器,它对WARC文档序列进行操作,并为每个文档生成标记的修改列表:

class MyCorpus(object):
def __init__(self, warc_file_instance):
    self.warc_file = warc_file_instance
def clean_text(self, html):
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded
    for script in soup(["script", "style"]): # remove all javascript and stylesheet code
        script.extract()
    # get text
    text = soup.get_text()
    # break into lines and remove leading and trailing space on each
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return text
def __iter__(self):
    for r in self.warc_file:
        try:
            w_trec_id = r['WARC-TREC-ID']
            print w_trec_id
        except KeyError:
            pass
        try:
            text = self.clean_text(re.compile('Content-Length: \d+').split(r.payload)[1])
            alnum_text = re.sub('[^A-Za-z0-9 ]+', ' ', text)
            yield list(set(alnum_text.encode('utf-8').lower().split()))
        except:
            print 'An error occurred'
现在我应用apache spark paraellize来进一步应用所需的映射函数:

warc_file = warc.open('/Users/akshanshgupta/Workspace/00.warc')
documents = MyCorpus(warc_file) 
x = sc.parallelize(documents, 20)
data_flat_map = x.flatMap(lambda xs: [(x, 1) for x in xs])
sorted_map = data_flat_map.sortByKey()
counts = sorted_map.reduceByKey(add)
print(counts.max(lambda x: x[1]))
我有以下疑问:

  • 这是实现这一目标的最佳方式还是有更简单的方式
  • 当我并行化迭代器时,实际的处理是并行的吗?它仍然是连续的吗
  • 如果我有多个文件呢?如何将其扩展到一个非常大的语料库,比如TB

  • 更多来自Scala上下文,但:

  • 我有一个疑问,那就是在还原之前先做sortByKey
  • 如果使用map、foreachPartition、Dataframe Writer等或通过sc和sparksession读取,则处理是并行的,Spark范式通常适用于非顺序相关算法。mapPartitions和其他API通常用于提高性能。该函数应该是我认为的mapPartitions的一部分,或者与map一起使用,或者在MapClosure中使用。注意可序列化问题,请参阅:

  • 更多的计算机资源可以实现更大的扩展,并具有更好的性能和吞吐量


  • x=sc.parallelize(documents,20)确保分区数为的RDD等于集群中的核心数,这样所有分区都将并行处理,资源也将被平等使用。此外,如果您希望设置影响每一行的全局参数,那么您可以使用广播变量。答案中的任何好处,出于兴趣?