wosiu

sparkutils_for_erdal.py

Feb 7th, 2017
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. # RUN THIS SSH:
  2. # ssh imo2123 -tC "imo-pyspark --conf spark.ui.port=0 --num-executors 100"
  3. # You can also change: --driver-memory 2g --executor-memory 2g
  4. # You can increase --num-executors as well, but be careful during pick hours as you might wait a bit for resources from scheduler if you set too big
  5. # AND THEN COPY FOLLOWING INTO PYSPARK SHELL:
  6.  
  7. import json
  8. import datetime
  9. import time
  10.  
  11. def format_line(line):
  12.     try:
  13.         splitted_line = line.split(" ", 1)
  14.         t = float(splitted_line[0])
  15.         data = json.loads(splitted_line[1])
  16.         data['time'] = t
  17.         return data
  18.     except:
  19.         return None
  20.  
  21. def get_fields(rdd):
  22.     return b.flatMap(lambda j: j.keys()).distinct().collect()
  23.  
  24. def get_columns(rdd, col_names):
  25.     return rdd.map(lambda dic_line:
  26.                    {k: dic_line.get(k, None) for k in col_names})
  27.  
  28. def get_valid_lines_as_dict(rdd):
  29.     return (rdd.map(format_line).filter(lambda dic_line: dic_line is not None))
  30.  
  31.  
  32. def load_topic(topic, date=None, partition="*"):
  33.     if date is None:
  34.         date = datetime.datetime.now()
  35.     else:
  36.         date = datetime.datetime.strptime(date, "%Y-%m-%d")
  37.     date = date.strftime("%Y/%m/%d")
  38.     a = sc.textFile("hdfs:///data/logs/%s/%s/%s/*" % (topic, date, partition))
  39.     return get_valid_lines_as_dict(a)
  40.  
  41.  
  42. # -------------------------   QUICK TUTORIAL   --------------------------------
  43. # group by (country_name, carrier_name) and count
  44. # Load logs
  45. a = load_topic("ImoAccount.registrations", date="2017-02-05")
  46.  
  47. # show one line to see how it looks
  48. a.take(1)
  49.  
  50. # grouping:
  51. # 1) creates (key, value) pairs, where key is whatever column, and value is 1
  52. # 2) reduce by key to sum those "ones"
  53. b = a.map(lambda x: ( (x['country_name'], x['carrier_name']), 1 ) ).reduceByKey(lambda acc, val: acc+val)
  54.  
  55. # show 3 the biggest
  56. b.takeOrdered(3, lambda (k,v): -v)
  57.  
  58. # For more google: "Spark RDD transformations", e.g. https://www.supergloo.com/fieldnotes/apache-spark-examples-of-transformations/
Advertisement
Add Comment
Please, Sign In to add comment