Github user andrewor14 commented on a diff in the pull request: https://github.com/apache/spark/pull/93#discussion_r10490986 --- Diff: python/pyspark/rdd.py --- @@ -628,6 +656,31 @@ def mergeMaps(m1, m2): m1[k] += v return m1 return self.mapPartitions(countPartition).reduce(mergeMaps) + + def top(self, num): + """ + Get the top N elements from a RDD. + + Note: It returns the list sorted in ascending order. + >>> sc.parallelize([10, 4, 2, 12, 3]).top(1) + [12] + >>> sc.parallelize([2, 3, 4, 5, 6]).cache().top(2) + [5, 6] + """ + def f(iterator): + q = BoundedPriorityQueue(num) + for k in iterator: + q.put(k) + return q --- End diff -- Now that BoundedPriorityQueue is quite simple, I don't think you even need it any more. In fact, you can do everything in ```f``` (and I would rename this) as follows: ``` def topIterator(iterator): q = [] for k in iterator: if len(q) < num: heappush(q, k) else: heappushpop(q, k) yield q ```` Then your ```f2``` (merge function) can look something like ``` def merge(a, b): return next(topIterator(a + b)) ``` (The ```next``` is there only because topIterator returns a 1 element generator)
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. ---