Борис Гурьев
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Big data. GraphX lab ## Theoretical part Main goals of this part are: * become familiar with Graph Data Bases (graph DBs) * understand index-free adjasency * pros and cons of Relational DBs and Graph DBs * learn basic functions of GraphX * learn Pregel * learn PageRank Please, do not blindly copypaste! --- Ironically, legacy relational database management systems (RDBMS) are poor at handling large volumes of data. Relational databases are great when schema is predetermined and fixed. However, sometimes we want to store too many different types of objects in our database, and it becomes simply infeasible to design a schema for every type of object. This is when graph databases become useful. <details> <summary>Example: Schema</summary> <p> <i>The term relation schema refers to a heading paired with a set of constraints defined in terms of that heading.</i> Creating a table with a specified schema in SQL: </p> <p> ```sql CREATE TABLE List_of_people ( ID INTEGER, Name CHAR(40), Address CHAR(200), PRIMARY KEY (ID) ) ``` </p> </details> In order to leverage data relationships, organizations need a database technology that stores relationship information as a first-class entity. That technology is a graph database. Most of NoSQL databases (and hence Graph databases) were designed at time when *horizontal scaling* problem were described and researched whell. Some of SQL databases were adopted for horizontal scaling as well (such as MySQL  -  Amazon RDS). ### Why relational databases are not enough? ![](https://upload.wikimedia.org/wikipedia/commons/3/3a/GraphDatabase_PropertyGraph.png =400x) *Source: [Wikipedia](https://en.wikipedia.org/wiki/Graph_database)* Consider a database with vertexes and relations between them. In many algorithms we need to traverse relationhip edges or explore a node neighborhood. Both of the tasks are hard and inefficient to compute if we store the data as a relational database that support only SQL queries. First, SQL queries were not designed to handle iterative computation problems. For example, a query "does path between node A and node B exist" requires iterative traversal between nodes. Second, relational databases are not created to ensure locality of connected data. It is very important to locate clusters of connected nodes on the same machine. A lot of social network tasks asympotically optimal to solve using graph DBs. Reason in graph DB approach or deffinition: "A graph database is any storage system that provides index-free adjacency" (c) Marko Rodriguez [[source](https://www.slideshare.net/slidarko/problemsolving-using-graph-traversals-searching-scoring-ranking-and-recommendation/47-Dening_a_Graph_Database_A), slides 47-57] - [Gremlin](https://tinkerpop.apache.org/gremlin.html) contributor and researcher. Hence, such queries as "get all friends of John" (~"get set of neighbours for node John") have lower complexity (in rough order, O(1) instead of O(N)). #### What index-free adjacency means? Technically it means that connected elements are **linked together without using an index** to avoid expensive operations (such as *join*). Enought knowledges are in the source [[5](https://www.scitepress.org/papers/2018/68269/68269.pdf)]. NB: index-free adjacency not implies absence of index at all!!! To apply changes, Graph DB need to reboot system: deletion from graph not frees memory - need restart of DBMS (remind [BASE acronym](https://stackoverflow.com/questions/3342497/explanation-of-base-terminology)). ## Head start in Apache Spark GraphX GraphX is a component for graphs and graph-parallel computation. GraphX reuses Spark RDD concept, simplifies graph analytics tasks, provides the ability to make operations on a directed multigraph with properties attached to each vertex and edge. Your goal for today is become familiar with GraphX. You will run provided examples, discuss how parallel graph processing uses message passing. At the end you will become familiar with PageRank - the easiest algorithm on graphs for parallel computing. Let's start with console example - the easiest way to practice quickly: ```bash # Assumed that you included path to spark/bin in your $PATH spark-shell --master local[2] ``` Read logs. If there are something "java like" error traces, fix it. <details> <summary> <i>Error example </i> </summary> <p>Such an errors mean that environment is not ok. As implication of it, you can not use Spark sensistive imports and objects. Example of **sc** (SparkContext) object initialization error: <img src="https://i.imgur.com/nqWjIRa.png"/> </p> <p>How to check is everything ok:</p> <img src="https://i.imgur.com/Yusczhs.png"/> </details> --- #### Declare our first graph ![](https://i.imgur.com/BkzfhnW.png) ```scala import org.apache.spark.graphx._ val myVertices = sc.makeRDD(Array((1L, "Ann"), (2L, "Bill"), (3L, "Charles"), (4L, "Diane"), (5L, "Went to gym this morning"))) val myEdges = sc.makeRDD(Array(Edge(1L, 2L, "is-friends-with"), Edge(2L, 3L, "is-friends-with"), Edge(3L, 4L, "is-friends-with"), Edge(4L, 5L, "Likes-status"), Edge(3L, 5L, "Wrote-status"))) val myGraph = Graph(myVertices, myEdges) myGraph.vertices.foreach(println(_)) // res1: Array[(org.apache.spark.graphx.VertexId, String)] = Array((4,Diane), (2,Bill), (1,Ann), (3,Charles), (5,Went to gym this morning)) // Try this by yourself: myGraph.edges.foreach(println(_)) myGraph.degrees.foreach(println(_)) myGraph.inDegrees.foreach(println(_)) myGraph.outDegrees.foreach(println(_)) ``` Spark console allow you to preview fields and methods of object: just type **sc.** or **myGraph.** and press TAB. ![](https://i.imgur.com/wxCh1e7.png) --- ## Graph transformation methods: ### Map functions **mapEdges**, **mapVertices** and **mapTriplets** return new Graph object (with modifications). Each method maps given in parameters function on each element (edge, vertex or triplet) and modify it (in case of mapTriplet, result stores in edge attributes) ```scala val tmp = myGraph.mapEdges(e => e.attr == "is-friends-with") tmp.edges.foreach(println(_)) // Edge(1,2,true) // Edge(2,3,true) // Edge(3,4,true) // Edge(3,5,false) // Edge(4,5,false) ``` See [official documentation](https://github.com/apache/spark/blob/master/graphx/src/main/scala/org/apache/spark/graphx/Graph.scala) for exhaustive information on basic map functions. <details> <summary> <i>Triplet</i> </summary> <p>is a tuple of two vertices and edge's attribute: <img src="https://i.imgur.com/NiVwvkb.png"/> </p> <img src="https://i.imgur.com/nCiHsFM.png"/> </details> --- ### aggregateMessages Applies function *sendMsg* for each node and produces message by this action. Each message has direction (edge has 2 nodes - you specify which one is destination). Received message updates values in node by specified *mergeMsg* function. ```scala def aggregateMessages[Msg]( sendMsg: EdgeContext[VD, ED, Msg] => Unit, // argument mergeMsg: (Msg, Msg) => Msg // argument ) : VertexRDD[Msg] // return type ``` #### EdgeContext This class is the same as *EdgeTriplet* (hence it keeps information about source, destination nodes and about edge value that you can use in sendMsg function) class but additionally has methods *sendToSrc*, *sendToDst*. <details> <summary> methods signatures </summary> <a href="https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/graphx/EdgeContext.html">source</a> <img src="https://i.imgur.com/54TSEy9.png"/> </details> #### sendMsg is a function that accepts object of *EdgeContext* type and returns nothing. Here you perform all you needed transforms for data - resulting object acts as container for data. #### mergeMsg All the messages for each vertex are collected together and delivered to the mergeMsg method. This method defines how all the messages for the vertex are reduced down to the answer we’re looking for. As usual, this function must be associative, commutative. #### Usage example Following code counts the out-degree of each vertex—for each vertex, the count of edges leaving the vertex. ```scala myGraph.aggregateMessages[Int](_.sendToSrc(1), _ + _).join(myGraph.vertices).foreach(println(_)) // Or better formatted variant: myGraph.aggregateMessages[Int](_.sendToSrc(1), _ + _).rightOuterJoin(myGraph.vertices).map( x => (x._2._2, x._2._1.getOrElse(0))).foreach(println(_)) ``` **sendMsg** function ![](https://i.imgur.com/3rV3F3B.png) **mergeMsg** function ![](https://i.imgur.com/cj2SZli.png) --- ### [Pregel in Spark](https://github.com/apache/spark/blob/master/graphx/src/main/scala/org/apache/spark/graphx/Pregel.scala) When Google implemented its graph processing framework, [Pregel](http://www.dcs.bbk.ac.uk/~dell/teaching/cc/paper/sigmod10/p135-malewicz.pdf), it used the principles behind [Bulk Synchronous Parallel](http://albert-jan.yzelman.net/education/parco14/A2.pdf) (BSP) processing. Google’s Pregel is the inspiration for Spark’s own Pregel API. ```scala def pregel[A] ( initialMsg: A, maxIter: Int = Int.MaxValue, activeDir: EdgeDirection = EdgeDirection.Out ) // first group of parameters - Scala feature, you know ( vprog: (VertexId, VD, A) => VD, sendMsg: EdgeTriplet[VD, ED] => Iterator[(VertexId, A)], mergeMsg: (A, A) => A ) : Graph[VD, ED] // return type ``` #### pregel review: * Good for propagation algorithms (such as [PageRank](https://en.wikipedia.org/wiki/PageRank)) * Has 2 convergence critera (no new messages sent during iteration, reached maximum iteration) #### Usage example ```scala val g = Pregel( graph = myGraph.mapVertices((vid,vd) => 0), initialMsg = 0, maxIterations = Int.MaxValue, activeDirection = EdgeDirection.Out )( vprog = (id:VertexId,vd:Int,a:Int) => math.max(vd,a), sendMsg = (et:EdgeTriplet[Int,String]) => Iterator((et.dstId, et.srcAttr+1)), mergeMsg = (a:Int,b:Int) => math.max(a,b) ) g.vertices.foreach(println(_)) ``` --- #### Let's compare 3 approaches on concrete single task Task: let's update nodes with rule: if node has relation "is-friends-with", then mark it as "has friend". <details> <summary> <i>map approach spoiler</i> </summary> <p>It easy to do with triplets:</p> <pre><code>myGraph.mapTriplets(t=>t.attr=="is-friends-with").edges.foreach(println(_))}</code></pre> <p>But to update vertices using edge's information we need to do some steps:</p> <pre><code>val friendlyVertices = myGraph.edges.filter(_.attr=="is-friends-with").map(_.srcId).collect.toList myGraph.mapVertices((v,s) => friendlyVertices.contains(v)).vertices.foreach(println(_))</code></pre> </details> <details> <summary> <i>aggregateMessages spoiler</i> </summary> <pre><code>myGraph.aggregateMessages[Boolean](c => c.sendToSrc(c.attr == "is-friends-with"), (a, b) => a || b)</code></pre> <p>Note: <br/> 1) Function returns VertexRDD, if we need Graph, we should create it again using new Vertices and old Edges <br/> 2) Vertices without edges are absent at all in result of funciton (Hint: use join(), example in reference book [1, p. 71] or same code in this tutorial)</p> </details> <details> <summary> <i>pregel spoiler</i> </summary> <pre><code>Pregel(graph = myGraph.mapVertices((vid,vd) => false), initialMsg = false, maxIterations = 1, activeDirection = EdgeDirection.In )( vprog = (id,vd,a) => vd || a, sendMsg = et => Iterator((et.srcId, et.attr=="is-friends-with")), mergeMsg = (a,b) => a||b ).vertices.foreach(println(_))</code></pre> <p>Seems like using AK-47 vs birds</p> </details> Which one is the most relevant? ### PageRank ![](https://i.imgur.com/MVwW1od.png) PageRank is the first algorithm used by Google to order search results. PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is. The underlying assumption is that more important websites are likely to receive more links from other websites. Reference to formula and details on [wiki](https://en.wikipedia.org/wiki/PageRank) (part of the lab excercise). ---- ## Graded part: 1) Using code [docks](https://github.com/apache/spark/blob/master/graphx/src/main/scala/org/apache/spark/graphx/Pregel.scala), provide your explanation in for all parameters of ```pregel``` function 2) Provide 2 examples of aplying GraphX for processing big data (which tasks could be solved). 3) **UPDATED** For current topology, the most popular node (by PageRank metric) is #5 ("Went to gym this morning"). Change graph structure such that in new graph the most popular node will be #1 (Ann). Provide pictures with console output of ``` myGraph.pageRank(0.001).vertices.foreach(println)``` before and after modification. Describe (1-2 sentences) how you achieved it. ## Additional reading 1. [GraphX in Action](https://drive.google.com/file/d/1wztlOHrLihsWNGLnsLfFlVeFWXAoHnB-/view?usp=sharing) 2. Neo4j (NoSQL Graph DB) [binding with Spark](https://neo4j.com/developer/apache-spark/), [usage example](https://medium.com/data-science-school/practical-apache-spark-in-10-minutes-part-7-graphx-and-neo4j-b6b01cffa4fd) 3. [Comparance of RDBMS and Neo4j in GIS production (rus)](https://www.slideshare.net/profyclub_ru/ss-27999513?ref=https://techno.2gis.ru/lectures/7) 4. [Spark and GraphX coupling. Not works with 2.3.2 version of Spark.](https://medium.com/data-science-school/practical-apache-spark-in-10-minutes-part-7-graphx-and-neo4j-b6b01cffa4fd) 5. [Paper where described concepts of Graph DBs](https://www.scitepress.org/papers/2018/68269/68269.pdf) 6. [(rus) Базы данных. Графы и их хранение на примере Neo4J](https://youtu.be/78ucMUzdp5c?t=1021) 7. [Lecture notes of Gremlin and Tinkerpop developer Marko Rodriguez](https://markorodriguez.com/lectures/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully