pyspark RDD 自定義排序(python)
阿新 • • 發佈:2019-01-27
問題:
現有資料 data = ((‘crystal’,90,22),(‘crystal1’,100,28),(‘crystal3’,100,22))
現在對data 進行排序
排序規則:
1 按元組中的第二個欄位排序
2 第二個欄位相等的話,按第三個欄位排序
實現思路:
定義一個列表元素類,每一個元素都可以例項化成這個類的物件
定義類的比較規則,比較規則即為需求規則,
然後將RDD遠端例項化成類,進行排序即可
實現程式碼:
from operator import gt
from pyspark import SparkContext, SparkConf
conf = SparkConf().setAppName('myFirstApp' ).setMaster('local')
sc = SparkContext(conf = conf)
class MySort():
def __init__(self,list):
self.rdd = sc.parallelize(list)
@staticmethod
def _toGirl(x):
return Girl(x[0],x[1],x[2])
def sort(self,ascending=True):
return self.rdd.sortBy(self._toGirl,ascending) ##按Girl的比較規則進行排序
class Girl():
def __init__(self,name,faceValue,age):
self.name = name
self.faceValue =faceValue
self.age = age
def __gt__(self,other):#實現__gt__方法,定義比較規則,python2 中用__cmp__方法
if other.faceValue == self.faceValue:
return gt(self.age,other.age)
else :
return gt(self.faceValue, other.faceValue)
def __repr__(self):
return self.name
l = [('crystal',90,22),('crystal1',100,28),('crystal3',100,22)]
s = MySort(l)
print(s.sort(ascending=False).collect())
- 列印結果:
[(‘crystal1’, 100, 28), (‘crystal3’, 100, 22), (‘crystal’, 90, 22)]