Big Data

Formula cheatsheet

Every key formula and rule from the course, one table per lecture. Click a heading to open the full lecture.

Introduction to big dataSearch on YouTube

TopicFormulaMeaning
Unit ladderKB MB GB TB PB EB ZB YBEach step is ×1000\times 1000; KB =103= 10^3 up to YB =1024= 10^{24}
Bytes from a unitbytes=value×103k\text{bytes} = \text{value} \times 10^{3k}kk counts steps above bytes (MB uses k=2k = 2, GB uses k=3k = 3)
Scale up (vertical)stronger hardware on one nodeUpgrades one machine; hits a limit with no fault tolerance
Scale out (horizontal)more nodes in the clusterAdds many small machines; gives true scalability with fault tolerance

Big data foundationsSearch on YouTube

TopicFormulaMeaning
Schema-on-write vs schema-on-readstructure first, then store vs store first, then structureWrite enforces ACID schema; read applies schema per query
Data model familieskey-value, document, columnar, graphRedis, MongoDB, Cassandra/HBase, Neo4j/GraphX
Storage homesHDFS blocks, object store, NoSQLReplicas across nodes; lakehouse backbone; fixed access patterns
Columnar formatsParquet, ORC over row formatsFast analytical reads with better compression
DescriptiveCOUNT, AVG, GROUP BYWhat happened; Hive and Pig summaries
DiagnosticJOIN + correlate + drill downWhy it happened; split the spike by segment
Predictivefeatures, train/test split, model, evaluationWhat will happen; Spark MLlib forecasts
Prescriptiveminimise cost under constraintsWhat to do; cheapest mix fills cheap capacity first

Hadoop and HDFSSearch on YouTube

TopicFormulaMeaning
Block countblocks=⌈file/block⌉\text{blocks} = \lceil \text{file} / \text{block} \rceil542/128→5542 / 128 \to 5 blocks: 128, 128, 128, 128, 30 MB
Raw storageraw=file×replication\text{raw} = \text{file} \times \text{replication}542×3=1626542 \times 3 = 1626 MB stored
NameNode entries5 blocks × 3 replicas = 15 locationsOne location per replica
Replica placementlocal node, different rack, same rack as second3 copies over at least 2 racks
Daemon timersheartbeat 3 s, block report 10 s, checkpoint 1 hNameNode detects dead nodes by missing heartbeat
Read pathlocations from NameNode, data from DataNodesBulk data never passes through the NameNode
Write path`create(), pipeline, acks, complete()`Packets flow down the chain, acks return up it
Configdfs.replication 3, blocksize 268435456 = 256 MBWeb UI port is 50070

MapReduce and YARNSearch on YouTube

TopicFormulaMeaning
Phase ordersplit, map, shuffle and sort, reduceS-M-S-R; shuffle groups by key, reduce sums each group
Map task countmap tasks = input splits3 splits give 3 map tasks; a split is the work unit, not a block
Partition rulepartition=hash(key) mod R\text{partition} = \text{hash}(\text{key}) \bmod ROne key lands whole in one partition; partitions == reducers
Combinerpre-sum on the mapper nodeCuts network pairs (9 to 8 in the Deer example); final sums stay equal
Sentence split trace(data, 3), (in, 2), rest 1data occurs once plus twice; in occurs twice
Deer traceBear 2, Car 3, Deer 2, River 2Sums of 9 map pairs: 2+3+2+2=92 + 3 + 2 + 2 = 9
Hadoop v1JobTracker plans, TaskTracker runsOne JobTracker per cluster; TaskTracker heartbeats the master
YARN daemonsScheduler, Applications Manager, NodeManager, ApplicationMaster, containerScheduler allocates; Manager accepts jobs; NodeManager launches containers
Execution ordersubmit, container, register, negotiate, launch, run, report, release8 steps from client submit to ApplicationMaster shutdown

Pig data model and operatorsSearch on YouTube

TopicFormulaMeaning
Nesting orderfield → tuple → bag → relationField is one value, tuple is a row, bag holds tuples, relation is a named bag
Map[key#value, ...]Keys are unique chararray, values hold any type
LOADA = LOAD 'f' USING PigStorage(',') AS (n:chararray, a:int);Read a file into a relation with schema
STORESTORE A INTO 'out';Write a relation, fails if the output dir exists
CROSS∣X∣=m×n\vert X \vert = m \times nEach tuple of A pairs with each tuple of B
DISTINCTX = DISTINCT A;Keep one copy of each full tuple
ORDER BYX = ORDER A BY a3 DESC;Sort on fields, direction is ASC or DESC
LIMITX = LIMIT A 3;Keep at most 3 tuples, order not promised
FILTERX = FILTER A BY f3 == 3;Keep tuples that pass the test
FOREACHX = FOREACH A GENERATE f1;Project columns, like SELECT
GROUPB = GROUP A BY age;One (group key, inner bag) tuple per key
COUNTFOREACH B GENERATE COUNT(A);Count tuples per bag, skips NULL
MAXFOREACH B GENERATE group, MAX(A.a3);Largest value per bag, skips NULL
TOKENIZEFOREACH A GENERATE TOKENIZE(a1);Split each line into a bag of words
Word countFLATTEN(TOKENIZE(line)) then GROUP then COUNTOne row per word, group equal words, count bags
UNIONstudent = UNION student1, student2;Stack all tuples, schemas need not match
SPLITSPLIT d INTO s1 IF age < 23, s2 IF age > 25;Route tuples by IF tests, drop the rest

Pig statements, types and joinsSearch on YouTube

TopicFormulaMeaning
Statement shapeLOAD -> transforms -> DUMP or STORE;Every statement ends with ;; output action triggers the run
Keywords vs namesLOAD = load; students != StudentsKeywords ignore case; relation, field and function names keep case
REGISTERREGISTER ./tutorial.jar;Loads a JAR of UDFs for the script
NULL testFILTER s BY city is not null;is null / is not null only; == and != miss NULLs
Arithmeticb mod a=0b \bmod a = 0 for b=20b = 20, a=10a = 10+ - * / %; 10+20=3010 + 20 = 30, 10−20=−1010 - 20 = -10, 10×20=20010 \times 20 = 200, 20/10=220 / 10 = 2
Bincond(a == 1) ? 20 : 30True branch before :, false branch after it
CASE parityCASE f2 % 2 WHEN 0 THEN 'even' WHEN 1 THEN 'odd' ENDCleaner than nested binconds for many branches
Regex testf1 matches '.*tutorial.*'True when f1 holds tutorial anywhere
Constructors(Raju, 30), {(Raju,30),(Md,45)}, [name#Raja, age#30]( ) tuple, { } bag, [ ] map
Inner JOINJOIN students BY id, fees BY id;Keeps only keys in every relation; key 2 drops out
LEFT OUTERJOIN students BY id LEFT OUTER, fees BY id;Keeps every left row; missing fees fields are NULL
RIGHT OUTERJOIN students BY id RIGHT OUTER, fees BY id;Keeps every right row; missing students fields are NULL
FULL OUTERJOIN students BY id FULL OUTER, fees BY id;Keeps every row of both sides
COGROUPCOGROUP students BY id, fees BY id;Returns (key, bag1, bag2); unmatched side is {}
STREAMSTREAM raw_logs THROUGH `normalize.py`;Pipes tuples through an external program
DESCRIBEDESCRIBE enriched;Shows schema; Grunt shortcut \de
EXPLAINEXPLAIN revenue;Shows logical, physical, MapReduce plans; shortcut \e
ILLUSTRATEILLUSTRATE enriched;Traces a sample through the pipeline; shortcut \i
Revenue patternFILTER > GROUP > SUM > ORDER DESC > LIMITHyderabad 450.0+220.5=670.5450.0 + 220.5 = 670.5 beats Delhi 180.0180.0
Inactive patternJOIN customers BY id LEFT OUTER, valid BY id;Keeps customers 2 and 4 with NULL order fields

Pig UDFs and scriptingSearch on YouTube

TopicFormulaMeaning
UDF kindsEval / Filter / Aggregate / Load-StoreEval per tuple, Filter boolean, Aggregate whole bag, Load/Store custom format
Java UDF baseclass UPPER extends EvalFunc<String>Override exec(Tuple input); return value is the new field
REGISTERREGISTER myudfs.jar;Makes the jar visible to the script
DEFINE aliasDEFINE UPPER myudfs.UPPER();Short name for the full class name
Call a UDFFOREACH students GENERATE UPPER(name);Runs exec() once per tuple
PiggybankDEFINE ISOToUnix org.apache.pig.piggybank.evaluation.datetime.convert.ISOToUnix();Ready string, math and date UDFs
Scripting UDFREGISTER 'myfuncs.py' USING jython AS myfuncs;Python via Jython; also Rhino, JRuby, Groovy
MAPREDUCE operator`com.example.LegacyScoringJob mr-input mr-output`Backtick launch command inside MAPREDUCE 'job.jar' STORE ... LOAD ...
MAPREDUCE I/OSTORE cleaned_orders INTO 'mr-input' / LOAD 'mr-output' AS (customer_id:int, score:double)Pig writes the input dir, reads the output dir with a declared schema
Local prototypepig -x local script.pigFast sample runs without cluster queues
DESCRIBEDESCRIBE emp;Shows schema; runs no job
DUMP (safe)DUMP (LIMIT emp 5);Prints rows; every DUMP runs a mini job, so limit first
STORE clashhadoop fs -rm -r dept_summary_outputPig never overwrites output dirs; delete or use a fresh path
Generate patternf-string builds .pig textParametrizes thresholds and paths
Subprocess patternsubprocess.run(['pig', '-x', 'local', 'f.pig'])Check returncode; 0 means success
Embed patternP = Pig.compile(t) / P.bind({...}) / bound.runSingle()Adds loops and conditions; run with pig, not python
PigUnittest.assertOutput("students", input, "upper_names", output);In-memory test with no cluster
Lab summaryEngineering 4, 59000.0, 71000 / Sales 3, 50666.67, 53000 / Marketing 3, 42000.0, 45000GROUP emp BY dept then COUNT, AVG, MAX

Hive architecture and HiveQLSearch on YouTube

TopicFormulaMeaning
Query pathClient → Driver → Metastore → Engine → HDFSDriver checks Metastore before compiling the plan
ServicesHiveServer2 / CLI / Web UIMulti-user JDBC/ODBC/Thrift entry points
Metastoreschemas + partitions + HDFS pathsCatalog metadata; never holds the data
ARRAY accesstags[0]Zero-indexed item lookup
MAP accessattributes['color']Key lookup in a map column
STRUCT accessdimensions.lengthDot notation into a struct field
Format pickSTORED AS ORCHive-only analytics and ACID tables
Cross-engineSTORED AS PARQUETShared reads by Spark, Trino, Presto
Evolving schemaSTORED AS AVROJSON schema travels with row data
Raw landingSTORED AS TEXTFILEStaging only; convert before querying
DATABASE synonymCREATE SCHEMA = CREATE DATABASEFull synonyms everywhere
DROP DATABASEDROP DATABASE x CASCADE;CASCADE drops every table inside
Managed DROPDROP TABLE managed;Deletes schema and files
External DROPDROP TABLE ext;Deletes metadata; files stay at LOCATION
TRUNCATETRUNCATE TABLE t;Clears rows, keeps schema; managed tables
PartitionPARTITIONED BY (order_date STRING)One HDFS dir per value; prune on filter
BucketCLUSTERED BY (customer_id) INTO 4 BUCKETSbucket = hash(col) mod n; INT hash is the value
LOADLOAD DATA LOCAL INPATH 'f.csv' INTO TABLE t;Copies files as-is; runs no job
Append vs replaceINSERT INTO / INSERT OVERWRITEAppend rows vs replace table or Hive partition
ACID recipeSTORED AS ORC + ('transactional'='true')Required for UPDATE / DELETE
UPDATE / DELETEUPDATE t SET b = b - 100 WHERE id = 42;ACID tables; else error 10294
Query shapeWHERE → GROUP BY → HAVING → ORDER BY → LIMITHAVING filters aggregates
ORDER BYORDER BY total DESCOne global order; slow on huge results
SORT BYSORT BY amount;Sorted within each reducer
DISTRIBUTE BYDISTRIBUTE BY customer_id;Same reducer, unsorted
CLUSTER BYCLUSTER BY customer_id;DISTRIBUTE BY x SORT BY x
Plain viewCREATE VIEW v AS SELECT ... WHERE amount > 400;Reruns each read; always fresh; read-only
Materialized viewCREATE MATERIALIZED VIEW v AS SELECT ...;Stored result; optimizer can auto-rewrite
REBUILDALTER MATERIALIZED VIEW v REBUILD;Refreshes stale stored results
Index removalHIVE-18448 (Hive 3.0)No CREATE INDEX; use MVs, ORC stats, pruning
StatisticsANALYZE TABLE t COMPUTE STATISTICS;Feeds the cost-based optimizer

Partitioning, bucketing and joinsSearch on YouTube

TopicFormulaMeaning
Managed createCREATE TABLE t (...) STORED AS ORC;No LOCATION; Hive owns the warehouse path
External createCREATE EXTERNAL TABLE t (...) LOCATION '/path';Hive keeps metadata plus pointer; files stay
DROP managedDROP TABLE t;Deletes metadata AND data
DROP externalDROP TABLE t;Deletes metadata ONLY; files survive
Partition dirsorder_date=2026-08-10/ ...One dir per value; partition column not in files
Static loadPARTITION (course='java')Name each value by hand per load
Dynamic enableSET hive.exec.dynamic.partition = true; + SET hive.exec.dynamic.partition.mode = nonstrict;Lets Hive create dirs from row values
Dynamic insertPARTITION (course) SELECT ..., coursePartition column last in SELECT
PruningWHERE order_date = '2026-08-11'Opens only that dir; rest never touched
Good partition colorder_date, region, statusLow cardinality, often in WHERE
Bad partition colcustomer_id, order_id, timestampHigh cardinality; use bucketing instead
Bucket rulebucket_number = hash(value) mod nINT: hash is value, so Id mod 3
Bucket createCLUSTERED BY (customer_id) INTO 4 BUCKETSFixed file count at CREATE TABLE time
Bucket enableSET hive.enforce.bucketing = true;Older decks set this before insert
Bucket map joinSET hive.optimize.bucketmapjoin = true;Needs same join col + multiple counts
SampleTABLESAMPLE(BUCKET 1 OUT OF 4 ON customer_id)Reads one file, about 1/4 of rows
CombinePARTITIONED BY (d) CLUSTERED BY (c) INTO 4 BUCKETSDir from partition col, file from bucket col
Inner joinJOIN ... ON a.id = b.idOnly matching rows; slide tables give 4
Left / right / fullLEFT / RIGHT / FULL OUTER JOINKeeps left / right / both sides; NULLs fill gaps
Cross joinrows = m x n10 x 13 = 130; slide tables 7 x 4 = 28
Id 5 in 3 buckets5 mod 3 = 2Bucket 2

Hive views and indexingSearch on YouTube

TopicFormulaMeaning
View ideaview = saved SELECT, no stored dataVirtual table; reruns query on every read
CREATE VIEWCREATE VIEW v AS SELECT c1, c2 FROM t;Save any result set; subset rows or columns
Filter viewCREATE VIEW v AS SELECT * FROM t WHERE s > 35000;Strict test drops rows equal to the limit
ALTER queryALTER VIEW v AS SELECT col1 FROM t;Replace the defining query; base table kept
RENAME viewALTER VIEW v RENAME TO w;New name, same rows
When to indexlarge data + slow query + frequent WHEREIndex lives in a separate table; can partition it
Compact storevalue + block idGo straight to the block holding the value
Bitmap storevalue + bit vector (1 bit per row)1 means the row holds the value
CREATE INDEXCREATE INDEX i ON TABLE t(c) AS 'BITMAP';Type is handler class or BITMAP / COMPACT
Deferred rebuildWITH DEFERRED REBUILDIndex starts empty until ALTER rebuilds it
SHOW INDEXSHOW FORMATTED INDEX ON t;Lists every index on the table
REBUILDALTER INDEX i ON t REBUILD;Runs a MapReduce job; rebuild after append
ALTER syntaxALTER INDEX i ON t REBUILD;Missing ON raises ParseException
AND query0110 AND 0100 = 0100Intersect vectors bit by bit; row 2 wins
OR query1001 OR 0100 = 1101Union of row sets
NOT queryNOT 0110 = 1001Complement of the vector
Timing result276.815s compact vs 197.424s bitmapSaving 79.391 s; ratio 1.40; same answer
Skip indexingsmall data / unique rows / rare WHEREBuild cost beats the gain
DROP INDEXDROP INDEX i ON t;Deletes index and its table
Hive 3.0CREATE INDEX removed (HIVE-18448)Use materialized views, ORC/Parquet stats
Cardinalitybucket high / Hive-partition lowBuckets need spread; partitions need few values

ScalaSearch on YouTube

TopicFormulaMeaning
REPL divide10/6 gives 1Two Int values divide to Int; remainder dropped
Compile + runscalac F.scala then scala FCompile the file, run the class
Mutablevar data: Int = 100Reassignable; data = 101 works
Immutableval myVal: String = "Foo"Fixed; reassignment is an error
Inferencevar myVar = 10Becomes Int by default
Multi-assignval (a, b) = Pair(40, "Foo")Tuple split into two val variables
String lengthpalindrome.length()"Dot saw I was Tod" gives 17
Concat"a".concat("b") or "a" + "b"New string with second added at end
Array literalArray("Zara", "Nuha", "Ayan")Fixed-size, one type
Array index exprz(4/2) = "Ayan"Index 2; any whole-number expression works
MatrixArray.ofDim[Int](3, 3)3×33 \times 3 matrix; needs import Array._
Arithmetica+b=30 / a-b=-10 / a*b=200 / b/a=2 / b%a=0 / c%a=5With a=10, b=20, c=25
Range loopfor (a <- 1 to 10)Inclusive range, 10 passes
Multi-rangefor (a <- 1 to 3; b <- 1 to 3)3×3=93 \times 3 = 9 pairs, 18 print lines
Yield filterfor { a <- L if a != 3; if a < 8 } yield aDrops 3 and values >= 8
Basic classclass Student { var id: Int = 0 }All fields need initial values
Anonymous objectnew Arithmetic().add(10, 10)No reference name; output sum = 20
Inheritanceclass Location(...) extends Point(xc, yc)One superclass only; adds z, move gives 20, 30, 20
Privateprivate def f()Visible only inside defining class; (new Inner).f() fails
Protectedprotected def f() in SuperVisible in subclasses only; Other fails, Sub works
Functiondef addInt(a: Int, b: Int): IntaddInt(5, 7) returns 12
Proceduredef printMe(): UnitReturns nothing, like void
List buildList(1, 2, 3, 4) or 1 :: (2 :: Nil):: prepends, Nil is empty
head / tailList(a, o, p).head is atail is List(o, p); Nil.isEmpty is true
Concat listsfruit1 ::: fruit2Joins lists; .::: binds right so order flips
SetSet(1, 3, 5, 7)Pairwise different elements, one type
Map lookupcolors("red")Value for key; keys unique, values repeat
Concat mapscolors1 ++ colors2Duplicate keys collapse to one
Tuple accesst._1 + t._2 + t._3 + t._4(4, 3, 2, 1) sums to 10
Iteratorit.hasNext / it.next()One-by-one walk; hasNext false ends loop

Apache SparkSearch on YouTube

TopicFormulaMeaning
MapReduce passes2k passes for k iterationsOne read plus one write per iteration
Cached Spark passes1 passInitial read, then reuse from RAM
10 iters on 50 GB20 x 50 GB = 1000 GB = 1 TB vs 50 GBSpark moves 20x less disk data
In-memory claimSpark time = Hadoop time / 1002014-era claim, varies by workload
On-disk claimSpark time = Hadoop time / 102014-era claim, varies by workload
GraySort time72 / 23 = 3.13Same 100 TB, one third of time
GraySort nodes2100 / 206 = 10.19Same 100 TB, one tenth of nodes
Deployment modesStandalone / YARN / KubernetesOwn manager / shared / pods, no Hadoop
Removed optionsMesos removed in 4.0; SIMR obsoleteDo not list them as current
Spark Corescheduling, memory, recovery, storageBase for SQL, Streaming, MLlib, GraphX
Catalyst + AQEplan + runtime re-optimizeAQE GA since Spark 3.0
Streaming nowStructured Streaming (DataFrame)DStreams is legacy maintenance
ML nowspark.ml (DataFrame Pipelines)spark.mllib is legacy maintenance
GraphGraphX via Pregel; GraphFrames alternativeGraphX stable, little new work
SparkR statusdeprecated in Spark 4.0Use PySpark or Spark SQL
Word countflatMap(_.split(" ")).groupBy("value").count()Two Scala lines vs dozens of Java
Line countspark.read.textFile("data/sample.txt").count()Prints The file has 100000 lines.
Local run.master("local[*]")All cores; test and dev only
SetupJava 17+ and Scala 2.13 for Spark 4.xCheck with java -version

Machine learning with Spark MLlibSearch on YouTube

TopicFormulaMeaning
Iterative disk costpasses ≈ 2kEach of k iterations writes plus reads HDFS
Cached Spark cost1 disk pass, k memory passesLoad once, cache, iterate in memory
K-means 20 iters2 x 20 = 40 vs 1MapReduce 40 passes; cached Spark 1
Lineage recoveryreplay DAG for lost partitionRecompute only lost partition from source
Mahout vs MLlib100x memory, 10x diskCited speedup; workload-dependent
DataFramespark.read.format("libsvm").load(path)Table-like source for spark.ml
Transformer.transform(df)Appends columns; feature step or fitted model
Estimator.fit(df)Learns on train data; returns a Transformer
Pipeline.setStages(Array(...))Ordered chain of Transformers and Estimators
PipelineModelpipeline.fit(train)Same stage count; Estimators became Transformers
MinMax rangerescaled = min + (max-min)(v-min_i)/(max_i-min_i)Defaults min 0.0, max 1.0, shared by features
MinMax slide rows[1,0.1,-1] -> [0,0,0]Minima map to 0; maxima [3,10.1,3] -> [1,1,1]
StandardScalerz = (x - mu) / sigmawithStd divides; withMean subtracts
VectorAssembler.setInputCols(Array("hour","mobile","userFeatures"))Merges columns into one vector
StringIndexer.setInputCol("category").setOutputCol("categoryIndex")Most frequent label gets index 0
Slide indicesa -> 0, c -> 1, b -> 2Counts 3, 2, 1
OneHotEncoderone binary col per categoryAt most one 1 per row group
Binarizer1.0 if value > threshold else 0.0Threshold 0.5: 0.8 -> 1.0; rest 0.0
VectorSlicer.setIndices(Array(1))Keeps positions 1-2: [-2,2.3,0] -> [2.3,0]
VectorIndexer.setMaxCategories(4)Above 4 distinct values stays continuous
Pearsonr = sum((xi-xbar)(yi-ybar)) / sqrt(sum(xi-xbar)^2 sum(yi-ybar)^2)Linear fit on raw values
Spearmanrho = 1 - 6 sum(d^2) / n(n^2-1)Monotonic fit on ranks
Slide ranks rho1 - 120/990 = 0.879Ten ranks; sum d² = 20
Age ranks rho1 - 48/504 = 0.905Eight people; sum d² = 8
Outlier effectpearson -0.205 vs spearman 0.697One x=1000 point flips Pearson
Outlier removedpearson 0.943 vs spearman 0.992Both agree without the extreme point
LogisticRegression.setMaxIter(10).setRegParam(0.3).setElasticNetParam(0.8)Seed 5043; tune threshold by max F-Measure
Decision tree.setMaxCategories(4)Index labels and features; 70/30 split
Random forest.setNumTrees(10)Same stages as tree with rf swapped in
K-means legacyKMeans.train(data, 2, numIterations = 20)RDD API; reports sum of squared errors
K-means modern.setK(2).setSeed(1L)Score with Silhouette, squared euclidean
Naive BayesrandomSplit(Array(0.7, 0.3), 1234L)Fit, predict, score accuracy
LinearSVC.setMaxIter(10).setRegParam(0.1)Inspect coefficients and intercept
MLP layersArray(4, 5, 4, 3)Block 128, seed 1234, maxIter 100, 60/40 split

Graph processing with GraphXSearch on YouTube

TopicFormulaMeaning
Property graphdirected multigraph + properties on every vertex and edgeParallel edges allowed; immutable, distributed, fault-tolerant
VertexIdtype VertexId = Long (64-bit)One entry per vertex in VertexRDD
Graph buildGraph(verRDD, edgeRDD)Parallelize vertex and edge arrays, then build
Imports`import org.apache.spark.graphx._`Plus Edge, Graph, GraphLoader as needed
Vertex filter`graph.vertices.filter { case (id, (city, pop)) => pop > 50000 }`Keeps 5 cities; drops Harrisburg (49528)
Edge filter`graph.edges.filter { case Edge(a, b, d) => d < 150 }`Keeps 5 edges: 113, 106, 128, 39, 130
Triplets`graph.triplets.collect`One record per edge: srcAttr, attr, dstAttr
Degreesdeg(v) = indeg(v) + outdeg(v)inDegrees, outDegrees, degrees; sums equal numEdges
Neighbour sum`ugraph.aggregateMessages[Int](ectx => ectx.sendToSrc(ectx.dstAttr._2), _ + _)`Union with graph.reverse.edges first for both directions
Neighbour totals(4,2251352)(4,2251352) (1,8322073)(1,8322073) (5,1706480)(5,1706480) (2,120379)(2,120379) (6,9805524)(6,9805524) (3,8943034)(3,8943034)Vertex 3 =620961+70851+8175133+76089= 620961+70851+8175133+76089
Basic operators`numEdges` `numVertices` `inDegrees` `outDegrees` `degrees`5 basic operators
Property operators`mapVertices` `mapEdges` `mapTriplets`New graph, same structure
reverse`graph.reverse`Flip every edge direction; count and properties unchanged
subgraph`graph.subgraph(epred, vpred)`Keep vertices and edges that pass the predicates
mask`graph.mask(other)`Keep vertices and edges also present in other
groupEdges`graph.groupEdges(merge)`Merge parallel edges with merge
joinVertices`graph.joinVertices(table)(map)`Update matched vertices only; same vertex type
outerJoinVertices`graph.outerJoinVertices(table)(map)`Update all vertices (Some/None); may change type
PageRankPR(v) = (1-d)/N + d\sum PR(u)/\text{outdeg}(u)graph.pageRank(0.0001); tolerance on rank change
Connected components`graph.connectedComponents().vertices`Each piece labelled with an id
Triangle count`graph.triangleCount().vertices`Needs canonical orientation (srcId<dstId\text{srcId} \lt \text{dstId}) plus partitionBy

Stream concepts and algorithmsSearch on YouTube

TopicFormulaMeaning
Batch vs streambounded + exact vs unbounded + per-windowMinutes-hours exact vs ms-s incremental
Stream traitsContinuous, Unbounded, Time-ordered, Fast, TransientCut Fast Traffic; seen once
Tumbling counts[0,5):3, [5,10):2, [10,15):38 events, no overlap
Sliding counts[0,6),[3,9),[6,12),[9,15): 3 eachSize 6 s, slide 3 s
Session countsgap 7.5->11 = 3.5s closes: 5 + 33 s gap rule
WatermarkW = max(event time) - 10 minAccept > W, drop < W
Reservoir keepP(keep i) = k/i; P(in sample) = k/nk=2, n=5 gives 2/5 each
Bloom hashesh1 = x mod 10; h2 = (2x+3) mod 1025->bits 5,3; 42->bits 2,7
Bloom rule0 bit = absent; all 1 = possibly presentNo false negatives
FM distinctn-hat = 2^RR = longest trailing-zero run
DGIMsum buckets except oldest + oldest/2Powers of two, at most two per size
Count-Minquery = min over rowsNever undercounts
Lambdabatch + speed -> mergeLogic twice, batch fixes errors
Kappaone log + one job, replay from 0Logic once, swap when caught up
Record vs micro-batchms (Flink/Storm) vs ~interval (Spark)Snapshots vs lineage recovery
At-most-oncecommit offset before processingLoss possible, no duplicates
At-least-oncecommit offset after processingDuplicates possible, no loss
Exactly-oncecheckpoints + replay + idempotent sinkAtomic output and offset
Checkpoint recoveryrestore at 120, re-read 120->150No loss, no double count
Scalingpartition by key; 1 Kafka partition -> 1+ taskSame key stays ordered
BackpressuremaxOffsetsPerTrigger; Flink flow controlSlow intake, Kafka buffers bursts

Streaming pipelines and KafkaSearch on YouTube

TopicFormulaMeaning
Pipeline stagessources / ingest / process / store / serveS-I-P-S-S; log gives decoupling, fan-out, replay
Fraud rulesamount > 5x avg OR two cities in 10 minKey by card; watermark on ts; alerts + Delta Lake
DStreamone RDD per batch intervalLegacy spark.streaming; reduceByKey is per batch
Unbounded tablegroupBy(word).count()Spark keeps counts as state per trigger
Complete modewrite entire result tableSmall aggregate tables
Update modewrite only changed rowsLarge aggregate tables
Append modewrite only new final rowsNeeds watermark for aggregates
Watermarkmax event time seen - delayOlder events drop to late-data path
Slide windowstumbling 3-2-3; sliding 3-3-3-3; sessions 5-38 events at 1..14 s; sliding double-counts
Kafka partitionhash(key) mod pOne key stays in one partition, in order
Orderingwithin partition onlyNo order across partitions
Retentiondelete by age or sizeReads never delete events
Groupsshare within, broadcast acrossExtra consumers in a group sit idle
Replicationleader + followers; ISRmin.insync.replicas = 2, acks = all survives 1 failure
acks0 = nothing / 1 = leader / all = in-syncN-L-E: safest is all, fastest is 0
Exactly-once writesenable.idempotence + transactionsKill retry duplicates; atomic across partitions
Compactionkeep latest value per keyTombstone (null) deletes a key
ksqlDB windowWINDOW TUMBLING (SIZE 1 MINUTE)Per-sensor 1-min AVG(temp) table