Docsity
Top Seller

Big Data Processing and Analytics, Schemi e mappe concettuali di Elementi di Informatica

Anteprima parziale del testo

Scarica Big Data Processing and Analytics e più Schemi e mappe concettuali in PDF di Elementi di Informatica solo su Docsity!

> rene Lisa ("Ns+9) dio O Nus Ctcotsemne ai guaio botto |: Spatokh, Ue breax © 30m fsi Cso dita atora un o di Sinivolle CONVERSIONI value0F(i) per fossone de untifo primitivo a un Uuteggan lasfidoorino) int +Infeger Integer wu» Lrtegpr. value0f(i) int > Stino Str oa Strivg valueoHi) imfudibe CI fer passe da UN Uitoppane un pumitivo lumborino) int inti= wntugel) String > int (nti = Integer parseLat(3); Integer 3 Strivg Strimy s-u-oSmital); String > Trteopr Tniteger = Integer. udie0R( SÌ; Strito, + Double © Double d = Dove. fiarse Dauble (5) ; Stra > Float FloatF: Flost. parsefloat(s); TIMESTANP ne(Line): fields - Line. dimension dimension 4 UO [EROSS : Cortesion produd (RIGITIOUTERTIOII) torno tuti i necod dille ttello di desta atoli quel die moicloto della simistra. Cc tom da L'efincibsto in comme /melte «uti do (LEFT SOI VA) Re columms ossee wifà He Gfrtable cîe mfinmed JAVA _|_HADOOP String | Ted Tnteopr | Intwrtoble LongWntable Float Float Wr:toble IF (LohetoSirira(1.compareTo(encther Strta) = « O) .. if (vabvedoStrim().equols (notherStrin)) (Sorbo di sini) (EFTTOUTER DIN + nituwmo. dute fe comme etiti i Metodi caqelti che mon fonro Cabo in comume lo rette = null a (FOLLIDOTERIIOINI insiome del ER e dì Aufii asta Moll [tot N File dui input + N ife di mapper dle Quoto im parallelo A MAPPER : produce un coppie (dliove, ulsie) per ogni op dk ipo Serre (rest, (ut, ud2,..)) (teu (uot4,..]) 2) RENICER: nicne um dina e 0 Bd di lo: ossa a jeMo dine e Li clboa \NPUTFORNAT OUTPUT FORNAT Text IupdtFormet TortO.tputformat KEY «offset cF tie Lime + LONG WRITABLE rey\t vehe\n VALVE= comtemi cf the file > TEXT + The inpot of ile 2° giò com bo o leylale ext Inputformat Keybalve Text Tapulformet Keye seporatbra che The tuo paris ome TEXT defoutt è tb: \t NUIIDFBE = nel rey sed ufen DA dt Salo be gaged fagetten Nullbnitatie.agtli neiams Ae sirofe insionie «e dass (EINGLETON) "CONBINER “MG, if He neguce function is commutatie ovd assunte “The creation de Combimen 19 MX quoramised => tie tap Reduce jdo sfild n depend on tie Combimen exeurtion “UR Com mate ycb.set(ombinerCiass(Reduer.class) PERSONALISED DATA TYPES AND VALVES T db Mme Functions uit onfy One jdo public cid readfielàs (Dota Input in) to speci fu to cesematite tNe detta public void write (etsospit at) dliavto servalize Me data org.apache.hadoop.io.Writable { jurgare onde LB KES* Write Campo ro ENI ph VALVES Wrrtahle -nashG N setuoito pen lo ShofFle & sort n countValue) { count=countValue { (sum) (count) mein count=in. Hare differiti Files ovalizal by He ftopfedixe uiifi durfent fam Eodh input gamsi fequies a dedicate) Napron cRees + eiroci the. inipamatione specifi indi folte, ite int fonmot Less fon cad, DENVER Re mroppen dess fespamsità gn cadi impdi sonce Vial (yo, Mew Path (args E), Totinpiformat. cass, Mappert.chss) 3T0 coiiome Med imp Te So on = SA 3:fes ;Hlese Files stu te cccessibe by Mi modes Gite Muster (H6FS) 2 esdh mopeen/ieducen com Gccess tte fi Qoolly Driver: public int run(string[) args) throw ta 3 path 10): fp fi ra orig Ge } mini tree a lea 1 N-B.AB Tarso ife some frode sfe Ade same O5c® copy Jas T0Excoption, Interruptedfx PATTERNS NUMERICAL: gicup Petards by ove GA Moe rey Fields ard fem cdlufistes a Mumenical crpfgade gn cadi quip (NVERTEDSINDEX : TF-IDF COUNTINGINITATCOONTERS : iS COMMON im Tiap-Ondy jobs lese ro Rediucen iS meeded * FILTERING FILTERING : Hop sa, gd an, Tris too big + cat of fMemguy eno TOP setto amfl set Jiop F records arcortingio a nomina Yametiom . A map cid; sb è mot soffiient MAPPERS - 8A froppen imitializes am iM- mappe (Roud) top K UST Stomte stored im miritm MMENIOAA - imitano perpprmed mite setup mettg Lile maspar Ale donup mettiodì emits He k gote) poins ossonintad uiihim e in- mappen foco top k necorde REDUCER null’ im‘imapper top x feasd -asSitgle neducen Must be imstantiatec sort By(reyForc) sont asn onie meu retuims © Mu RID contonino tie some content ie inpui RIb sorted im ascending ode (descending False) SortadiamesRbb - inpito.s0v18y (lambda Name : name) Laplobokc ade is fe sadod od Ga Stungs -soriBy Clambda Name (len(name), name) odi puro per Onglezza e qui im odime Mpbdlico SAMPLE > sample (uthfepiacement, Frackion) i ord Seed sive Ve cnple ss a Godin Ge input ROD sine ((0,A)) Ndbiuns © Aardom compl di He dlementis tifi Repiacememt speccfies IP yu con use He chjedi imone Ham cme time SET TRANSFORMATIONS 2ingà RDDs + ostpui ROD (RDds ife some ds ye) UNION > union(otter) felunms © Item RDD confoimina He union (WNT DUPLICATES) Be demenis Y ie imptROD. UnionA_225D = inputRBDA.union( iNPvIRDDZ) _. cuume unionz.ARDD = iNPUTRDD2.UNION( inprtRBDA) INTERSEGTIONI — intersection(otter) + dat e sent n ife msuor 3 uuifatt dupficotes SUBTRACT + subtraci (etner) sd o sont om ife maior Me rest comtouns He ef&meants cppeoving ord, im ife RDD om dich the subito metfog is invored Li diplicoles cre mat removed CARTESIBNI + cartesian(attier) DO NOT USE IT +e dor omuntrofàdia iS sent om Se meu UThe datiupe Re tuo imput REDS con be diggetent 1 Re relbaured ROD Is In RDF fins(tupls) contbimifa A e combinclione. compossi cf cre element ci Re gist imput ROD cord ome elamemi È ffe setorò impuf RDD. ACTIONS COLLECT > cale) ? fefunms a dd pjlon List q cheds containito, Re same chieds cite considered RbD. COUNT count () Comi Ate Mumbai elements an ROD. It doesmt. cont ife mumbai c$ distimà efements. Lan intere gn och partition 18 sant on He metuoie crd fem fe mumbers ce umimed tegeiten COUNTBYVALVE > count Byiahe () retunis @ fed Gictionay confouniny Fe infoamation colt He Mumbe times asrelementozns im He ROD bife pays tte diclioroy ce associated” with ife inputrefemente Life uobes ce Pe pepenties 0 ffie clemente The omounti G used imain Memo im Rie Dover is redstiad do Ne mumber } distinc etementis/rjs Y TAKE +tare(num) Mus al pin list of deck: contizimin) He (Gist mumi elements: oi e comsidensà DD. Bdipdicles ole md nemoed Life oder i3 pesawedì FIRST + First) fem a Cod pian ded contormit, Re diet ment Lie oder is pesewed FIRST VS TRE The only difference between first() and take(1) is given by the fact that first() returns a single element. The returned element is the first element of the RDD take(1) returns a list of elements containing one single element. The only element of the returned list is the first element of the RDD TOP. > toplnum) tetunns w CocR pylfon List di dajeds containing He op mum fugestre lerments Li Re adenima is he det ore glass astuisi ii Re dest Stord im He RDD La dipdicdes die Nd nemoed a1d Hey ve considered Ae da is preseed (descendit order) toplnum, res) vsar specified Sunchion ressinputRDD.top(2,lembda S: len(s)) / res=inpit RDD.sortBullambda S:-4*En(9)) tore (2) “hop SIMONE eFFiccent om Ris vesion witti rt e “nos Ig cdode \ Car e ite sore Biras. ittores Elnieves te Simo Aptobetical arden ord iP Ate 0 N TAREORDERED > tareordered (num) fetugins a Cod pytfon dist qareds contaunino {a Mum smictest Tetsmante Bastardina, od iNURDD More Ordered(2) /top(2, lembda 5:- 4*lent9) tareddered (num, key) TARESATPLE 7 SEE NE I fetus © Qocoì puffiom Ust & chjedis contamio num nondamefementts) (+ Fsm ie Aronspanation Mei fureS (whAegscement,nom,seed) "9 Netnms è dei nd trote pio List) REDUCE > En fisiums @ sittafe putin chiedi obtacmed by combiluvo dA ife doeds & Ne RDD by sim a usen provide fiction bre red dep cd a inpds cre dI in fontes Preti ao) pe e a6 Y die - VI CONNUTATIV SumUales= inpàRDD. reduce (lambda pan 'ave SPE . (dd patita su tici ca em) FOLD >fdlg (cerstole, op) eq ripone n° fetumsa single paifm dard cttRLITES by LombiMimO, cile cbeds 4 He input ROD cid a zeto dhe by using o ASSOQIATIVE para AGSREGATE + (rerolate, s290p, combOp) fetumte a og psttan objet obama by combini ite cbeds ch ife ROD and on imitidt ar udhe bi usivo fo usse provide > ASSOCIATIVE TT y y SA Site rinmed dopdsond ife input com be insignces A DIFFERENT dlesses VU Example 1 Ned ab - Create an RDD of integers containing the values [1, 2, 3, 3) - Compute both U © thesumofthe values occurring in the input RDD o andthe number of elements of the input RDD - Finally, “store” in a local python variable of the Driver the average computed over the values of the input RDD This exercise can be done: - | Without aggregate funetion — You start with a map operation, where each integer is mapped to a tuple — the first elements the input value itself, and the second is that value plus one. Then, you apply a reduce operation to compute the final result. - With aggregate function Partition #1 acc=(0,0) Simulation: Ì Ga) InBDD = [1, 2, 3,3] Suppose inBDD.is split in the following two partitions: [1, 2] and [3, 3] V3U UaV imura got. U+U tro pic portitione COMBIEBIRES + combine Bf create Combiner, meragliate, margeCombier) > dela E saiit cm fe neluoîik dentes men (puts For cadi dist rey. Die Prickiom must cnby be ASSOCIATIVE ila LHlie dii type gi Ne ite ROD & polls com be DIFFERENT il fesped to He dieta tupe & imput (nu) isss Example: Create an RDD from a local python list containing the pairs - ("Paolo", 40) - ("Giorgio", 22) - ("Paolo", 35) The key is the first name of a user and the value is his/her age Store the results in an output HDFS folder. The output contains one line for each name followed by the average age of the users with that name. Version without CombineByKey We start with an RDD containing pairs of (name, profile), where the profile includes the user's age. Our goal is to compute the average age for each user name. For example, suppose we have two users named Paolo and one named Giorgio. We want to compute the average age of all users named Paolo, and since Giorgio appears only once, his average will simply be his own age. Each record has: - Key:the username (e.g., "Paolo") - Value: the user's age (e.g., 35) We can use the map operation to transform each input pair so that the value becomes a tuple containing: - the age (for summation) - the number1 (to count the occurrences) = rddyap(lambda pair: (pair[0], (pair[1], 1))) So each element becomes something like: ("Paolo", (35, 1)) ("Paolo", (40, 1)) ("Giorgio", (22, 1)) We now want to sum the ages and counts for each name. Since redugeByKey, operates only on the values (the key is used only to group them) , our function will take two tuples (v1, v2) and return their element-wise sum. SNoRDR, = BABRESBRR.KeduceRyzcy(lambda vi, v2: (vl[0] + v2[0], vl[1] + v2[1])) Resulting RDD: ("Paolo", (75, 2)) ("Giorgio”, (22, 1)) Finally, we can use map again to compute the average age for each key by dividing the total sum by the count: = spuRDR.mep (lambda p: (p[0], p[1](0] / p[1][1])) Resulting RDD: ("Paolo", 37.5) ("Giorgio”, 22.0) This approach allows us to compute the average age per user name using only map and reduceByKey, without relying on sombineBvkey SaRaRDR = sdd,mapllambda pair: (pair[0], (pair[1], 1))) \ . (lambda vl, v2: (vl[0] + v2[0], vl[1] + v2[1])) \ «map (lambda p: (p[0], p[1](9] / p[1](1])) Version with CombineByKey. # Create the local python list asnchige = | ("Paolo”, 40), ("Giorgio", 22), ("Paolo", 35)] # Create the RDD of pairs from the local collection = acspazalialàza (namshgs) # Compute the sum of ages and # the number of input pairs for each name (key) # Compute the average for each name # Store the result in an output folder Nam ARISARISELEALe (Gutpy ERBUPIBIIRES + glpbyiag() + a log: amount Y dea E sent om ife melwone Y cedes a Maw ROD dh Poruis uilere Rene 18 are pain Yan eodh distimi ny I ite imput pacas LG itoraps di ite uhes ossanated uni e some KEY nd produces am ITERABLE SY Mose whues + is a Vist quali Example: Create an RDD from a local python list containing the pairs ("Paolo", 40) - ("Giorgio", 22) - ("Paolo",35) The key is the first name of a user and the value is his/her age. Store the results in an output HDFS folder. The output contains one line for each name followed by the ages of all the users with that name # Create the local python list nameAge = [ ("Paolo", 40), ("Giorgio", 22), ("Paolo", 35)] # Create the RDD of pairs from the local collection nameAgePairRDD = sc.parallelize(namenge) # Create one group for each name with the list of associated ages = nameAgePairRDD.groupByKey() # Store the result in an output folder agesPerNamePairRDI aveAsTextFile Ronn NAPUALVES > maglisiues(F) opplies a Gunchiom 3 cun fe vate desc ion 3 He input Saga type & Pe udies con te dggenenti. The hay pont remims fe some Example: Create an RDD from a local python list containing the pairs Tneer. 10 Napidhes i5 mor efficient item Map! * ("Giorgio", 22) ("Paalo", 35) The key is the first name of a user and the value is his/her age. Increase the age of each user (+1 year) and store the result in the HDFS file system. One output line per user Versione senza mapvalues: xdd.map (lambda p: (p[0], p[1] + 1)) Versione con mapValues: Edd.mapValues (lambda age: age + 1) > This produces exactly. the. same result, but it's more efficient. # Create the local python list nameage = [ ("Paolo", 40), ("Giorgio", 22), ("Paolo", 35)] # Create the RDD of pairs from the local collection nameagePairRDD = sc.parallelize (nameage) # Increment age of all users ID = mapyi (lambda age: age+1) # Save the result on disk plusoneRaizEDo,saveAsTIenteile (cuEnzteazh) Result: I ("Paolo", 41), ("Giorgio”, 23), ("Paolo”, 36) 1 Why mapValyes() ls More Efficient? The key reason is that Spark maintains internal data structures and indexes that track how keys are distributed across partitions. When you use mapValues(), Spark knows that only the values are being modified, while the keys remain unchanged. That means any index on the keys remains valid and the data layout across partitions is preserved. However, when you use map(), Spark cannot assume that the keys stay the same, it must treat the operation as if both the key and the value might change. As a result, it may invalidate indexes and rebuild partitioning information, which reduces performance. FLATHAPVALUES — Fiattiap iiwes(F) FittippUdues is more eFficcent Pon Fiatitap! * Affres a Ginchiom Fa ie udie Q ed fe Metunms a List Juies meadh imut ude BF yo unit to pply a trmzfoumation Were sodi impit valle ton produce tero, are cr multiple odput ulues. KEYS > reus() Petutms tie BS GIESS A e input. B Tre addi is Imi om RDD graj-volle fils Mio dardo ROD » dupdtdes ce ‘mà remed VALUES + valves () telunns te Got Q VALUES Rie input. La The odiput is ii om RDD qrej-tolle faune Ii iso diordorà ROD b dupdides oe (Mi remored ACTIONS COUNTBIKEY covntByley() a se sant com Tie metuonx Retunis o Cd ouifiom diclioneu conttu:ming He infantion abadi He iumber efemente essociated ui ear DISTINCT rey Example: Create an RDD of pairs from the following python list [("Forrest Gump", 4), (*Star Trek", 5) , (“Forrest Gump", 3)]. Each pair contains a movie and the rating given by someone to that movie. Compute the number of ratings for each movie. Solution without countByKey: povisRatinaRDD.mapValues (lambda v: 1) #= ("Forrest Gump", 1), ("Star Trek", 1), ("Forrest Gump", 1)] wi -MapValnes (lambda v: 1).zeduceByEey (lambda a, b: a + b) #= ("Forrest Gump", 2), ("Star Trek", 1)] Solution with countByKey: # Create the local python list moyieRating= | ("Forrest Gump", 4), ("Star Trek", 5), ("Forrest Gump", 3)] # Create the RDD of pairs from the local collection MovisRatinaRon = sc.paralierize lmovichatina) # compete the number of rating for each movie = movieRat n o Pay attention to the size of the returnes local python dictionary a the number of distinct movies în this case) # Print the result on the standard output print (novisNumBatings) COLEGTIASIMAP! > ara gre sont on te mettuone Retunns a dol dichia: Corrtiniro, Pe same pois Qife imp RID Q fade Pay attention that the collectAsMap action returns a dictionary object. A dictionary cannot contain duplicate keys. Each key can be associated with at most one value. If the “input” RDD of pairs contains more than one pair with the same key, only one of those pairs is stored in the returned local python dictionary. Usually, the last one occurring in the input RDD of pairs. + Use collectAsMaR only if you are sure that each key appears only once in the input RDD of key- value pairs. Colkt Asttop US Cibd The gollectAsMapl) action returns a local dictionary while collect) return a list of key-value paîrs (i.e., a list of tuples! The list of pairs returned by collect() can contain more than one pair associated with the same key. mitistelt'Proto", 40), lorgie*, 45) 500 = se-paralleLime(mytist) rescornecteroo.cotieett) rescollecinap«fb0. col iectAstapi) SARA trescorleco) La Il*Paoto!, 40), ('Giorgio*, 45)1 use typelrescotecinip) [ace las rp) diet {'Paolo': 40, ‘Giorgio': 45) The difference is when you have duplicates: mydistaall‘Paato', 40), ('Panto”, 13), ('Giorgio*, 45) w002 » scsparalteLizelmytist2) resctieta»0002. collect) PESCO ciMn2uRD2, col ectAsto) l'Pooto®, 40); L'Proto”, 12), ( Giorgio”, 4511 type cosca) Dei vescica &'Paoto': 13, “iorgio”: 45) comtaimino fe vdes He (out o} Me input assouiteg wife te Ita, pen fied ce pafvmeren RDDs OF NUMBERS All the examples reported in the following are applied on inputRDD that is an RDD containing the following double values [1.5, 3.5, 2.0] sum) Return the sum over the inputRDD.sum() 7.0 values of the inputRDD mean() Return the mean value inputRDD.mean() 2.3333 stdevi) Return the standard inputRDD.stdev() 0.8498 deviation computed over the values of the inputRDD variance() Return the variance inputRDD. 0.7223 computed over the values of variance() the inputRDD max) Return the maximum value inputRDD.max) | 3.5 min() Return the minimum value inputRDD.min() 1.5 (PERSISTENCE AND CACHE >fon RDDS csed multiple times ord Expemsie + Mecompie persist(storagelal,..) + No esse: MEMORY_ONLY Store RDD as deserialized Java objects RDD does not fitin memory, some partitions will not be cached and will be recomputed on the fly each time they're needed. Thisis the default level. MEMORY_AND_DISK Store RDD as deserialized Java objects in the JVM. If the RDD does not fitin memory, store the partitions that don't fit on (local) disk, and read them from there when they're needed. DISK_ONLY Storethe RDD partitions only on disk. +018 if Pe Rbiis size. 13 Yale Ton ife size & fe impo deheei MEMORY_ONLY_2, Same as the levels above, but replicate each partition on MEMORY_AND_DISK_2, | twocluster nodes-+ iF oe male foi fe "Sn cm Ge 032 ‘o poor Ma chiome ete a Pro sito tecompdtira Pe contest ite RED OFF_HEAP (experimental) Similarto MEMORY_ONL, but store the data in off-heap memory. This requires off-heap memory to be enabled. NONE Cacheli + It comespords to persst fe RAD ws He Sivope da MEMORY ONLI atromsgpumations 155 ifay Aetuam a Mew ROD be Hay o smmitzble it con be removed by cada uniti Unperssi ACCUNULATORS + stoied vovisbies used to implement coumtens or sums Ohby ite dute mode com access Te Yival ue to fe octumulo. The tuoiren modes Cammi access Îfe volle atte acamveata . Tey com cy odg calbes to iT Lo {a om be Integors, Fiets cor, Mu detoiye | Bboclss fut implementa Me Accumulstor Bram inttenface 14 es to Madera Zeno ici LSSsinin rr Pay attention that the value of the accumulator is increased in the functions associated with transformations. Since transformations are lazily evaluated, the value of the accumulator is computed only when an action is executed on the RDD on which the transformations increasing the accumulator are applied. Ifthere are two actions associated with the output of the transformations the value of the accumulator is not correct, the system return a value of the accumulator that is two times the expected value. + you can use cache and persist inclicza neo tor = r\ctor (ualie) |: BemplE: Create an RDD from a textual file containing a lst of email addresses, one email fr each ine. Select the line: definition: ame ve, \ctor (ale) containing a valid email and store them in an HDFS file. In this example, an email is considered a valid email fit contain: the @ symbol. Print also, on the standard output, the number of invalid emails. tent of the input textual file ASsiGuEZAle (Cemallo.tat") AST VARIABLES = fesd cniy Cadiz riale asia! in fe chien. BROADI Itis stored im ife main mearoy Gi fe chi in c.c nile od it sont oil uom rie Mi cs (op cadi crenitn) defindtion broadcast ( ve) Broaskcest. vele Example: Create an RDD from a textual file containing a dictionary of pairs (word, integer value), one pair for each line. Suppose the content of this first file ìs large but can be stored in main:memory. Create an RDD from a textual file containing a set of words, a sentence (set of words) for each line. “Transform” the content of the second file mapping each word to an integer based on the dictionary contalned in the first file. Store the resultin an HDFS file. First file (dictionary) Java 1 spark 2 test3 Second file (the text to transform): map stringe Java spark spark test]ava Output file: i [word] ia isannisanadicne — Scnsisaadiane:sosialuse * Sura TEBRARBSRRALIARLarziR() 40 and ate them responding int BROADCAST JOIN brass uom i sim i one dttetuo input Detofrume is sno evorfib de stored im tie moin (mento cf eoch cieal es, dfBroadeetr: dfudSport jin (broadiest( dF Persone), SFPersons.vid==FUidSpords vid) SORT + sort(col4, ....colh, ascendim=Tve) Saia GE sant on Re meituoîk REGREGATE FUNCTIONS cre prosidedto compie cganeades cun #e set uolles A columms. 239(0p) to specify Re fomion come cola to which opply #e fomchion 209, Cum, Sum, obs > cad Yme fietunns cre uve by comnsicenio li Me des Gite put column, es. Werageige =dF.apa ( fap: "2191)) Sactome anta) 260 Se si tuole oppose un'opg. Fenim im un stesso stiio mon Barior. fave è un diziorauo BISOGNA USARE QUESTA FUNZIONE : | import pyspark.sp1. functions) as F SROUPBI +grovp Bu(cal4,..., caln) Cormbimed usi a st $ aggiegsie mettods come used t split ie data in groups ord compie copfegsie fandion cur esc cralp NB.Re nesdt & gopBy is nt a Diagome bits a testi ord ord) after Tie cpgfegate cperchigm it becomes o Dataiome ca di.goph (nome). ag ({"ogp *:*a9* “atte”: ‘tour’ Tram 5500 UTO Ginzone. aug('toe*) Example: dfAverage; esdf.agg({“age”:”avg”)}) dfAverageAGe. filter (dfAverageAge . avg (age)>50)- WRONG The correct options: dfaAverageAge. filter (“avg(age)>50”) dfAverageAge=df.agg({\age”:”avg”}).withColumnRenamed(“avg(age)”, “MyAvg”) dfAverageAge. filter (dfAverageAge .MyAvg>50) SET TRANSFORMATIONS UNION + dFiunion(dfa) does mi remore dupficdes INTERSECT + gfi.interseci (dfa) seni dato an Pe mete SBTRACT= dA. subtiact (da) SR Ate iecods must ne ife some dinibies SOL LANGUAGE > sparsa! (fuer) Patate mome musi be assigmed to a Dalafnome + de. cresteOrReplace Empliew (taziellame) USER DEFINED FUNCTIONS (UDFS) > sparr.VAF.reggter [name function, dtge) sar ato type £ e netutned ul # name: length # output: integer value register ("length", lambda x: len(x)) xpr transformation result = inp Use of the defined UD result = spark.sql("SELECT length (name) FROM profiles") (SAVE DATAFRANES -met batafiomes to RODS + dPr.rdd. saeAsTextFile (outputfalder) +10e store ont) Mie dea, not Mie Prede 20 write() Pot netunms è Dataftomeltriter dass instance + dF.write.csu(osiputitth, header=True) + Ti ses db immuttipe Gis nd endh Gite ius a feoder OTION PLAN + explain () com be imored on a DE-to pui on Ne stovdog atat Ne creation ona ie pori d fe cade Mat & ussdt compie He coifenti Re DF Tie Cast DA contains Te antine ereastion Ron ord ul openstions sar aa anita MET Radike. € un'achon, ReduceByltay è oro. trosewatiom O > locaTop localMax context) locaTop r st<> localMax key, value, ((e1114> 39) category = key. count = Integer. value. count > localMax locaTop. 0) locaTop. (category) localMax = count count locaTop. localMax (category) context) ring s : locaTop context .write(Nullwritable. g> acc maxCount ig category, count value count v : values tmp=v. (0) category = tmp. count = tmp.split( value count = Integer. "_")[0] "_")[1] (count) (value count acc. 0) (category) maxCount = value_count maxCount) { acc. (value count (category) maxCount) (i s acc) context.write( (s), Nullwritable. get( localMax)) > values, context > SiD ,Seesontiumber, EpisedeNumber, Title, OriginalAirDete + Number ci lorg end short seasons for cadi tlevision series $0B4 > { > { @ le key, r value, t key, context tion, Int values, context) e ; ) fields value. SID » fields season - fields SID-key. numepi sodes context. (SID:"_"+season), ( ; value: values numepisodes-numepisodesivalue.get() context. (SID), (numEpisodes) key, value, context) fields[]=value. sid-fields number=Integer. number>19 context. { context. (SA values, context numLong: numShort value: values (value. g(). T ) numLong: numShort: context. (numLong+", "+numShort) HID Gay, Country, BeorBuiit + Gontiries witfi on cusoge mumber & fuses per uf gedien iîkam 40000 fouses JOB 7 value, context fields: fields context. country), (City. Gong, 41) (Conttry, num ttnaseRà:CotyOFThatGqattr) ntext v = Integer. context. key, fields = key. ; country = fields i : values sum context. (country), > values, nl context sum count n i : values sum «get() count mean ( ) sum count mean context.write(key, (mean) e(sum)