{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TF6hemCHdnG9"
      },
      "source": [
        "# Exercise Session 8 - Old Exam Questions"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KNSfyoQydnHH"
      },
      "source": [
        "## Spark"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zRKRVCNSdnHI"
      },
      "source": [
        "##### For more information on Spark (e.g. for creation functions), use ``help``:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "fHMkRlEFdnHH"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[Info] Using RumbleDB jar file at: file:///usr/local/lib/python3.11/site-packages/jsoniq/jars/rumbledb-2.1.7.jar\n"
          ]
        },
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "WARNING: Using incubator modules: jdk.incubator.vector\n",
            "26/11/11 14:38:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\n",
            "Using Spark's default log4j profile: org/apache/spark/log4j2-defaults.properties\n",
            "Setting default log level to \"WARN\".\n",
            "To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n"
          ]
        }
      ],
      "source": [
        "import json\n",
        "\n",
        "from pyspark import SparkContext, RDD\n",
        "from jsoniq import RumbleSession\n",
        "\n",
        "spark = RumbleSession \\\n",
        "    .builder \\\n",
        "    .master(\"local[*]\") \\\n",
        "    .getOrCreate()\n",
        "\n",
        "sc = spark.sparkContext"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Help on method textFile in module pyspark.core.context:\n",
            "\n",
            "textFile(name: str, minPartitions: Optional[int] = None, use_unicode: bool = True) -> pyspark.core.rdd.RDD[str] method of pyspark.core.context.SparkContext instance\n",
            "    Read a text file from HDFS, a local file system (available on all\n",
            "    nodes), or any Hadoop-supported file system URI, and return it as an\n",
            "    RDD of Strings. The text files must be encoded as UTF-8.\n",
            "    \n",
            "    .. versionadded:: 0.7.0\n",
            "    \n",
            "    Parameters\n",
            "    ----------\n",
            "    name : str\n",
            "        directory to the input data files, the path can be comma separated\n",
            "        paths as a list of inputs\n",
            "    minPartitions : int, optional\n",
            "        suggested minimum number of partitions for the resulting RDD\n",
            "    use_unicode : bool, default True\n",
            "        If `use_unicode` is False, the strings will be kept as `str` (encoding\n",
            "        as `utf-8`), which is faster and smaller than unicode.\n",
            "    \n",
            "        .. versionadded:: 1.2.0\n",
            "    \n",
            "    Returns\n",
            "    -------\n",
            "    :class:`RDD`\n",
            "        RDD representing text data from the file(s).\n",
            "    \n",
            "    See Also\n",
            "    --------\n",
            "    :meth:`RDD.saveAsTextFile`\n",
            "    :meth:`SparkContext.wholeTextFiles`\n",
            "    \n",
            "    Examples\n",
            "    --------\n",
            "    >>> import os\n",
            "    >>> import tempfile\n",
            "    >>> with tempfile.TemporaryDirectory(prefix=\"textFile\") as d:\n",
            "    ...     path1 = os.path.join(d, \"text1\")\n",
            "    ...     path2 = os.path.join(d, \"text2\")\n",
            "    ...\n",
            "    ...     # Write a temporary text file\n",
            "    ...     sc.parallelize([\"x\", \"y\", \"z\"]).saveAsTextFile(path1)\n",
            "    ...\n",
            "    ...     # Write another temporary text file\n",
            "    ...     sc.parallelize([\"aa\", \"bb\", \"cc\"]).saveAsTextFile(path2)\n",
            "    ...\n",
            "    ...     # Load text file\n",
            "    ...     collected1 = sorted(sc.textFile(path1, 3).collect())\n",
            "    ...     collected2 = sorted(sc.textFile(path2, 4).collect())\n",
            "    ...\n",
            "    ...     # Load two text files together\n",
            "    ...     collected3 = sorted(sc.textFile('{},{}'.format(path1, path2), 5).collect())\n",
            "    \n",
            "    >>> collected1\n",
            "    ['x', 'y', 'z']\n",
            "    >>> collected2\n",
            "    ['aa', 'bb', 'cc']\n",
            "    >>> collected3\n",
            "    ['aa', 'bb', 'cc', 'x', 'y', 'z']\n",
            "\n"
          ]
        }
      ],
      "source": [
        "help(sc.textFile)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sFTaSN9PdnHI"
      },
      "source": [
        "### Movies Dataset\n",
        "\n",
        "We will use a dataset that contains an array of movies with respective genres, actors, etc. Each movie has all of the following attributes:\n",
        "\n",
        "- `name`: string containing the name of the movie.\n",
        "- `genres`: string containing comma-delimited ganres of the movie.\n",
        "- `year`: integer year of the movie\n",
        "- `votes`: integer with number of votes of the movie\n",
        "- `rating`: string containing the rating of the movie\n",
        "- `actors`: an array representing a set of actors, where each element is a dictionary with the following key-value pairs:\n",
        "    - `name`: string with the name of the actor\n",
        "    - `birth`: integer with year of birth of the actor\n",
        "    - `death`: integer with the year of death of the actor\n",
        "\n",
        "You can use the RDD interface or the DataFrame interface below."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fqvDWyHWdnHH"
      },
      "source": [
        "### RDD interface\n",
        "\n",
        "Run the code below to import the JSON lines file as an RDD:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "Yku1ArdUdnHI"
      },
      "outputs": [],
      "source": [
        "movies:RDD = sc.textFile(\"movies.jsonl\", 10).map(json.loads)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Inspect the dataset by printing the first row:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "bemI1rbWdnHI"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "                                                                                \r"
          ]
        },
        {
          "data": {
            "text/plain": [
              "[{'genres': 'Thriller',\n",
              "  'actors': [{'birth': '1920', 'name': 'Mickey Rooney', 'death': '2014'},\n",
              "   {'birth': '1916', 'name': 'Keenan Wynn', 'death': '1986'}],\n",
              "  'name': 'The Manipulator',\n",
              "  'year': '1971',\n",
              "  'votes': '248',\n",
              "  'rating': '3.8'}]"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.take(1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zRKRVCNSdnHI"
      },
      "source": [
        "Below are some examples of Spark queries on the Movies dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Vt_lSNTYdnHI"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['The Manipulator', 'The Return of the Ancient Mariner', 'Last Request']\n",
            "['The Manipulator', 'The Return of the Ancient Mariner', 'Last Request']\n"
          ]
        }
      ],
      "source": [
        "def helper(s):\n",
        "    return s['name']\n",
        "\n",
        "res1 = movies.map(lambda s: s[\"name\"]).take(3)\n",
        "# same as\n",
        "res2 = movies.map(helper).take(3)\n",
        "\n",
        "print(res1)\n",
        "print(res2)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "ao-4qcyjdnHI"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'genres': 'Documentary,Short',\n",
              "  'actors': [{'birth': '1908', 'name': 'Michael Redgrave', 'death': '1985'}],\n",
              "  'name': 'Kyoto',\n",
              "  'year': '1969',\n",
              "  'votes': '13',\n",
              "  'rating': '8.2'}]"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.filter(lambda s: s[\"name\"][0] == \"K\").take(1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "1tVcjD3LdnHJ"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'birth': '1920', 'name': 'Mickey Rooney', 'death': '2014'},\n",
              " {'birth': '1916', 'name': 'Keenan Wynn', 'death': '1986'},\n",
              " {'birth': '1923', 'name': 'Don Adams', 'death': '2005'}]"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.flatMap(lambda s: s[\"actors\"]).take(3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9P-_-uKSdnHJ"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "78890"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.count()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "movies_kv = movies.map(lambda v: (v['name'], float(v['rating'])))\n",
        "movies_num = movies.map(lambda v: float(v['rating']))\n",
        "\n",
        "# Common transformations\n",
        "movies.filter(lambda v: int(v['year']) > 1960) # f: v -> bool\n",
        "movies.map(lambda v: float(v['rating'])) # f: v -> v'\n",
        "movies.flatMap(lambda v: v['actors']) # f: v -> [v', v', ...]\n",
        "movies.distinct()\n",
        "movies.sortBy(lambda v: int(v['year'])) # f: v -> Comparable\n",
        "\n",
        "# Common kv-transformations\n",
        "movies_kv.reduceByKey(lambda a, b: a + b)  # Commutative and associative\n",
        "movies_kv.sortByKey(ascending=False)\n",
        "movies_kv.groupByKey()\n",
        "movies_kv.mapValues(lambda v: v + 1) # f: v -> v'\n",
        "\n",
        "# Common actions\n",
        "movies_kv.collect()\n",
        "movies_kv.count()\n",
        "movies_kv.take(5)\n",
        "movies_num.takeOrdered(2) # Min 2 elements\n",
        "movies_num.top(2) # Max 2 elements\n",
        "movies_num.count()\n",
        "movies_num.sum()\n",
        "movies_num.min()\n",
        "movies_num.mean()\n",
        "movies_num.reduce(lambda a, b: a + b) # Commutative and associative\n",
        "\n",
        "# Common kv-actions\n",
        "movies_kv.countByKey()\n",
        "movies_kv.lookup(\"American Pie\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zRKRVCNSdnHI"
      },
      "source": [
        "##### For more information on RDD transformers (e.g. ``filter``), use ``help``:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[31mSignature:\u001b[39m movies.filter(f: Callable[[~T], bool]) -> \u001b[33m'RDD[T]'\u001b[39m\n",
            "\u001b[31mDocstring:\u001b[39m\n",
            "Return a new RDD containing only the elements that satisfy a predicate.\n",
            "\n",
            ".. versionadded:: 0.7.0\n",
            "\n",
            "Parameters\n",
            "----------\n",
            "f : function\n",
            "    a function to run on each element of the RDD\n",
            "\n",
            "Returns\n",
            "-------\n",
            ":class:`RDD`\n",
            "    a new :class:`RDD` by applying a function to each element\n",
            "\n",
            "See Also\n",
            "--------\n",
            ":meth:`RDD.map`\n",
            "\n",
            "Examples\n",
            "--------\n",
            ">>> rdd = sc.parallelize([1, 2, 3, 4, 5])\n",
            ">>> rdd.filter(lambda x: x % 2 == 0).collect()\n",
            "[2, 4]\n",
            "\u001b[31mFile:\u001b[39m      /usr/local/lib/python3.11/site-packages/pyspark/core/rdd.py\n",
            "\u001b[31mType:\u001b[39m      method"
          ]
        }
      ],
      "source": [
        "# help(movies.filter)\n",
        "movies.filter?\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'genres': 'Thriller',\n",
              "  'actors': [{'birth': '1920', 'name': 'Mickey Rooney', 'death': '2014'},\n",
              "   {'birth': '1916', 'name': 'Keenan Wynn', 'death': '1986'}],\n",
              "  'name': 'The Manipulator',\n",
              "  'year': '1971',\n",
              "  'votes': '248',\n",
              "  'rating': '3.8'}]"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.take(1) # peek the structure!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9bcBmB9PdnHJ"
      },
      "source": [
        "Now it's your turn: you can write all your queries in new cells below. Feel free to add as many cells as needed."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FE7Te6WUdnHJ"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "36806"
            ]
          },
          "execution_count": 12,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Snooze Copilot. ;)\n",
        "# What is the number of movies that were released after the year 1960\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'genres': 'Thriller',\n",
              "  'actors': [{'birth': '1920', 'name': 'Mickey Rooney', 'death': '2014'},\n",
              "   {'birth': '1916', 'name': 'Keenan Wynn', 'death': '1986'}],\n",
              "  'name': 'The Manipulator',\n",
              "  'year': '1971',\n",
              "  'votes': '248',\n",
              "  'rating': '3.8'}]"
            ]
          },
          "execution_count": 26,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# What is the average rating of all movies in the dataset?\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[(1829, 'Joseph Jefferson', '1905'),\n",
              " (1830, 'Charles Manley', '1916'),\n",
              " (1830, 'Eadweard Muybridge', '1904')]"
            ]
          },
          "execution_count": 32,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# What is the year of death of the actor who was born in the earliest year? (In case of a tie, return the lexicographically smallest name.)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# What is the total number of votes for all the movies with more than 200 votes?\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "h8WWt8KndnHJ"
      },
      "outputs": [],
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Solutions"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'genres': 'Thriller',\n",
              "  'actors': [{'birth': '1920', 'name': 'Mickey Rooney', 'death': '2014'},\n",
              "   {'birth': '1916', 'name': 'Keenan Wynn', 'death': '1986'}],\n",
              "  'name': 'The Manipulator',\n",
              "  'year': '1971',\n",
              "  'votes': '248',\n",
              "  'rating': '3.8'}]"
            ]
          },
          "execution_count": 16,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "movies.take(1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "36806"
            ]
          },
          "execution_count": 17,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# What is the number of movies that were released after the year 1960\n",
        "movies.filter(lambda v: int(v['year']) > 1960).count()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "Xhfhmfh5dnHP"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "6.673361642793764"
            ]
          },
          "execution_count": 18,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# What is the average rating of all movies in the dataset?\n",
        "movies.map(lambda v: float(v['rating'])).mean()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "50NWS2podnHP"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "                                                                                \r"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[((1829, 'Joseph Jefferson'), (1905, 'Joseph Jefferson')), ((1830, 'Charles Manley'), (1916, 'Charles Manley')), ((1830, 'Eadweard Muybridge'), (1904, 'Eadweard Muybridge'))]\n",
            "{'birth': '1829', 'name': 'Joseph Jefferson', 'death': '1905'}\n"
          ]
        }
      ],
      "source": [
        "# What is the year of death of the actor who was born in the earliest year? (In case of a tie, return the lexicographically smallest name.)\n",
        "v1 = (movies\n",
        "    .flatMap(lambda v: v['actors'])\n",
        "    .map(lambda v: ((int(v['birth']), v['name']), (int(v['death']), v['name'])))\n",
        "    .distinct()\n",
        "    .sortByKey()\n",
        "    .take(3)\n",
        ")\n",
        "print(v1)\n",
        "v2 = (movies\n",
        "    .flatMap(lambda v: v['actors'])\n",
        "    .min(lambda v: (int(v['birth']), v['name']))\n",
        ")\n",
        "print(v2)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "42413013\n",
            "42413013\n",
            "42413013\n"
          ]
        }
      ],
      "source": [
        "# What is the total number of votes for all the movies with more than 200 votes?\n",
        "v1 = movies.filter(lambda v: int(v['votes']) > 200).map(lambda v: int(v['votes'])).sum()\n",
        "print(v1)\n",
        "# Readability++\n",
        "v2 = movies.map(lambda v: int(v['votes'])).filter(lambda v: v > 200).sum()\n",
        "print(v2)\n",
        "# For the jokes\n",
        "v3 = movies.flatMap(lambda v: [int(v['votes'])] if (int(v['votes']) > 200) else []).sum()\n",
        "print(v3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "ZmHKrz59dnHM",
        "fp8TtfF6dnHN"
      ],
      "name": "HS2020_Files_Big_Data_HS_2020_-_Cheat_Sheet.ipynb",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.15"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": false,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": false
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}
