Category: Uncategorized

  • Oh my God: how good is open source

    A few days ago, I had to write a Python script that would enable us to write some data to an Oracle database. At first, I had no idea how to start. So, I downloaded a simple example script that I tried to run. The script was found via Google. This script looked like:

    import cx_Oracle
    con = cx_Oracle.connect('C##SCOTT/binvegni@localhost/orcl')
    print con.version
    con.close()
    

    I decided to run this script. This provided a clear error message. The error message looked like:

    Traceback (most recent call last):
      File "D:\Users\tmaanen\CloudStation\Drive\Erste\Midas\ora.py", line 1, in 
        import cx_Oracle
    ImportError: No module named cx_Oracle
    

    I then looked in Google how to solve this error message. I then downloaded the module. A subsequent attempt gave another error message. Again a clear error message.

    Traceback (most recent call last):
      File "D:\Users\tmaanen\CloudStation\Drive\Erste\Midas\ora.py", line 2, in 
        con = cx_Oracle.connect('scott/binvegni@127.0.0.1/orcl')
    DatabaseError: ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
    

    It looked like the servicename was wrong. The correct servicename could be found with the command tnsping. Modifying the script and running it again provided an almost trival error message.

    Traceback (most recent call last):
      File "D:\Users\tmaanen\CloudStation\Drive\Erste\Midas\ora.py", line 2, in 
        con = cx_Oracle.connect('scott/binvegni@localhost/orcl.corp.capgemini.com')
    DatabaseError: ORA-01017: invalid username/password; logon denied
    

    Oops: wrong userid. Sorry. The last attempt was succesfull:

    12.2.0.1.0
    

    Al in all, it took me less than half an hour to get this going. I was really impressed with the excellent support from the open source.

  • Curl and elasticSearch

    One of the most useful utilities is “curl”. This wonderful tool can be used to transfer data from one platform to another. It is relatively easy to install in Windows, whereas under linux, it is often already installed. It must be run from the terminal in Linux or the command line in Windows. One example is transfer of data from a webserver. But other protocols can be used as well: ftp, file, pop3 etc.

     

    An example is given below. One sees the command line that is used to invoke the curl utility. Curl is invoked by typing “curl”. The first parameter is the host that must be accessed. In this case I will access a webserver from which the data are retrieved. In this case, I will access www.van-maanen.com, my own website. Doing so, I transfer the html that is generated from the webserver.

     

     

    A similar statement can be user to retrieve data from a FTP server. Take as example: curl ftp://192.168.2.2 –user tom.vanmaanen@wxs.nl:tom24567 . This will open a FTP server.

    We may use curl to add data into ElasticSearch. Doing so, we transfer data from a local platform to the ElasticSearch database. We use this command from the windows platform: curl -XPUT “192.168.2.11:9200/movies/soort/123563458”  -d”{“”title””:””TestTom”” , “”director””:””Tom van Maanen””,””year””: 1957}”. Note: from linux the aspostophes are different. There the command should be curl -XPUT ‘192.168.2.11:9200/movies/soort/123563459′  -d'{“title”:”TestTom” , “director”:”Tom van Maanen”,”year”: 1957}’. On windows, we see:

     

    The reaction from ElasticSearch (“created”:true) indicates that the record is correctly inserted.

     

    In a similar exercise, we may retrieve records from the ElasticSearch database. We use: curl -XGET “192.168.2.11:9200/movies/soort/_search” -d “{“”query”” : {“”match”” : {“”title”” : “”TestTom””}}}”.

     

    We get something like:

     

     

    We see the same records that we inserted.

  • ElasticSearch

    A new and popular nosql database is the Elastic Search database. This database is easy to install en easy to run.
    But is it easy to insert data and extract the outcomes?
    The principle of inserting data into ElasticSearch looks rather straight forward. One inserts json files. On the other hand, with filters, one may retrieve the outcomes as a json file.
    This then shows the strength of ElasticSearch. With json files, one has the possibility to add an additional category without the necessity to add anything to the structure. This is different from the traditional RDBMS. In that case, one must modify the structure of a table in one would to add an additional type of data.
    But is it easy?
    Well, that depends on what you understand by “easiness”. One must be able to address the webserver that comes with ElasticSearch. One must also be able to inject a json file with an address to the webserver.
    The script below privides a way how this can be done with PHP.

     

     

    In the start of the script, the json file is set up. At the end of script the json file is inserted. Moreover, the script also shows how data can be retrieved. One must use an address that contains the index and doctype. As example, one may look at:
    http://192.168.2.11:9200/movies/soort/_search?q=director:%22Zoek%22?fields=title,year . The index is inserted directly after the adres, and the doc_type follows directly after. After the _?search, a field is provided that acts as filter to limit the number of records retrieved. Here. only records are returned for which director:”Zoek”.

    A final remark. HTML allows to insert parameters that can be used to add dynamic content. See below: $Title and $Year are sent as parameters to next page.

     

  • Scala merging files

    In a previous post, I showed how two files can be merged in Scala. The idea was that RDDs were translated as data frames and a join was undertaken on these.
    In this post, the philosophy is slightly different. Now the RDD is rewritten as a key-value pair with a unique key. This then allows a merge on this unique key.
    Let us first see how a RDD can be created with a unique key:

    val counts = sc.textFile("/user/hdfs/keyvalue").flatMap(line => line.split(',')).map(fields => (fields,1)).reduceByKey((v1,v2) => v1+v2)
    

    A file is read (“keyvalue”) that is subsequently split along their comma. Each word is then rewritten as an own record. If the original file contains 6 words, we end up having 6 records. We then create a new RDD with a “1” added to each record. Subsequently the word is seen as a key. The “1” is then aggregated over the records. This result could be used as a wordcount example.
    I created a similar RDD (“counts1”) that also had the words as a key.

    val counts1 = sc.textFile("/user/hdfs/keyvalue").flatMap(line => line.split(',')).map(fields => (fields,2)).reduceByKey((v1,v2) => v1+v2)
    

    The join can then be undertaken as:

    val pipo = counts1.join(counts)
    

    The outcomes can be shown as pipo.foreach(println).

    And a similar scripts runs as

    val kbreqs = sc.textFile("/user/hdfs/keyuser").filter(line => line.contains("KBDOC")).keyBy(line => (line.split(' ')(5)))
    val kblist = sc.textFile("/user/hdfs/keydoc").keyBy(line => (line.split(':')(0)))
    val titlereqs = kbreqs.join(kblist)
    

    A final script:

    val logs=sc.textFile("/user/hdfs/naamtoev")
    val userreqs = logs.map(line => line.split(' ')).map(words => (words(0),1)).reduceByKey((v1,v2) => v1 + v2)
    val accountsdata="/user/hdfs/naamstraat"
    val accounts = sc.textFile(accountsdata).keyBy(line =>  line.split(',')(0))  
    val accounthits = accounts.join(userreqs)
    for (pair <- accounthits) {printf("%s, %s, %s, %s\n",pair._1,pair._2._1," score= ",pair._2._2)}
    
  • Merging files in Scala

    I understand that Scala may be used in an ETL context. In ETL, an important element is the merge of two files. We will get data from different sources and they must be merged in one file only. As an example, we may think of two files, one containing a number and a name, another being a file with a number and age.
    In a previous post, I showed how two files can be merged in PySpark. In this post, I will show how it can be undertaken within Scala.
    In my first step, I read two files. I then split the lines along the delimiter. Subsequently, I identify the different columns:

    val namen=sc.textFile("/user/hdfs/namen")
    case class MatchData(id1: String, id2: Int)
    def parseNamen(line: String) = {
          val pieces = line.split(',')
          val id1 = pieces(0).toString
          val id2 = pieces(1).toInt
          MatchData(id1,id2)
          }
    val parsedNamen = namen.map(line => parseNamen(line)).toDF()
    
    val leeftijd = sc.textFile("/user/hdfs/leeftijd")
    case class MatchLeeftijd(id3: Int, id4: Int)
    def parseLeef(line: String) = {
          val pieces = line.split(',')
          val id3 = pieces(0).toInt
          val id4 = pieces(1).toInt
          MatchLeeftijd(id3,id4)
          }
    val parsedLeef = leeftijd.map(line => parseLeef(line)).toDF()
    

    I can then join the two objects with:

    val samen=parsedLeef.join(parsedNamen,parsedNamen("id2") === parsedLeef("id3"))
    samen.show()
    

    The idea is that a column can be accessed with parsedNamen(“id2”) or parsedLeef(“id3”). For me, the non trivial item is how these columns are compared. A symbol like === is used for that purpose.
    An alternative is a Carthesian product that is subsequently filtered:

    val samen=parsedLeef.join(parsedNamen)
    samen.filter("id2-id3 = 0").show()
    
  • Getting a histogram from Big Data with Scala

    Scala can be used as a tool to manipulate big data. If it is used in the spark context, we have a possibility to combine two strong tools: spark with its possibility to bypass the MapReduce bottleneck and Scala with its short learning curve.

    The idea that Scala can be closely integrated with Spark is already clear when Scala is started. It can be started with the command “spark-shell” from the terminal. After a few seconds the Spark sign is shown with the note “Using Scala version 2.10.4”. A few lines below, one sees “Spark context available as sc”. This is the statement that we will use.

    We have quite a number of files in an HDFS directory. They can be made accessible as a RDD via:

    val rawblocks = sc.textFile("/linkage")
    

    Such a RDD is a dataset that is composed of a number of lines. The number of lines can be seen with rawblocks.count() that yields: res63: Long = 5749142.
    To do anything with this RDD, we must 1/ remove lines that are used as header, 2/ split the lines and 3/identify numbers as numbers. Let us do so.

    Removal of lines that act as a header can be done with this function:

    def isHeader(line: String): Boolean = {
          line.contains("id_1")
          }
    
    followed by
    
    val noheader = rawblocks.filter(x => !isHeader(x))
    

    Splitting the lines and identifying numbers as numbers is a bit cumbersome, but the code looks pretty straightforward:

    def toDouble(s:String) = {
          if ("?".equals(s)) Double.NaN else s.toDouble
          }
    
    case class MatchData(id1: Int, id2: Int,
          scores:Array[Double],matched: Boolean)
    
    def parse(line: String) = {
          val pieces = line.split(',')
          val id1 = pieces(0).toInt
          val id2 = pieces(1).toInt
          val scores = pieces.slice(2, 11).map(toDouble)
          val matched = pieces(11).toBoolean
          MatchData(id1, id2, scores, matched)
          }
    
    followed by 
    
    val parsed = noheader.map(line => parse(line))
    

    Then we are ready to create the histogram:

    val matchCounts = parsed.map(md => md.matched).countByValue()
    val matchCountsSeq = matchCounts.toSeq
    matchCountsSeq.foreach(println)
    

     
    Finally a less complicated script that calculates the mean of a column:

    val famblocks = sc.textFile("/user/hdfs/fam")
    case class MatchData(id1: Int, id2: String)
    def parse(line: String) = {
          val pieces = line.split(',')
          val id1 = pieces(0).toInt
          val id2 = pieces(1).toString
          MatchData(id1,id2)
          }
    val parsed = famblocks.map(line => parse(line))
    val matchCounts = parsed.map(md => md.id1).mean()
    

    with fam an HDFS file containing lines with a number and name, comma separated. (1,tom etc).

     

  • Scala

    Scala is a language that is used for general purposes. One may use it as a statistical tool, a tool to undertake pattern matching etc. Just like any other programming tool like Java, C++, Fortran might do. But on top of that, Scala is used as a means to steer Big Data on a Hadoop platform. For me, being interested in Big Data, Scala is a worthwhile investment.
    Let me first show a screenshot on Scala:

    The programme is quite straightforward. A function is defined with a name codeer. It receives one variable. When this variable is an ‘a’ or ‘b’, it will be translated into a ‘1’or ‘2’. In all other cases, it won’t be translated. The variable ‘kijk’ that contains the resulting character is returned. Subsequently, one may use this function.

    In the Big Data environment, one may start Scala by the command “spark-shell”. If everything is well installed, one sees something like:

     

    It is then clear that the integration between the Big Data environment and Scala is strong in this environment. When the environment is started, one sees that a context variable is created that allows to access the Spark environment:

    This then allows to retrieve a Big Data dataset as an object in Scala:

    val rawblocks = sc.textFile(“linkage”)

    The nice thing is that we may grab all files that are in directory “linkage” and access then as one object that is called rawblocks.

  • Another Pyspark scripts

    In this note, I show yet another Pyspark with slightly different methods to filter. The idea is that file is read in a RDD. Subsequently, it is cleaned. That cleaning process involves a removal of lines that are too long. The lines are split with a character that is on the twentieth position. Then the lines with a number of elements unequal to 14 are filtered out. After that, some columns are kept. Finally, the values are concatenated into a line and written to disk.
    We have:

    devstatus = sc.textFile("/loudacre/devicestatus.txt")
    
    # Filter out lines with < 10 characters, use the 20th character as the delimiter, parse the line, and filter out bad lines
    cleanstatus = devstatus. \
        filter(lambda line: len(line) > 20). \
        map(lambda line: line.split(line[19:20])). \
        filter(lambda values: len(values) == 14)
        
    
    # Create a new RDD containing date, manufacturer, device ID, latitude and longitude
    devicedata = cleanstatus. \
        map(lambda words: (words[0], words[1].split(' ')[0], words[2], words[12], words[13]))
    
    # Save to a CSV file as a comma-delimited string (trim parenthesis from tuple toString)
    devicedata. \
        map(lambda values: ','.join(values)). \
        saveAsTextFile("/loudacre/devicestatus_etl")
    
  • The 1000th wordcount example

    I just discovered the 1000th wordcount example. It is based on Pyspark. The idea is actually quite simple. One creates a script. This script can be written in any editor. The programme can then be run from the terminal by spark-submit [programme]. As an example, one may start the programme below with: spark-submit –master yarn-cluster prog1.py /user/hdfs/fam /user/hdfs/prog1A. The option –master yarn-cluster indicates how the programme is run. In this case the cluster is used. It can also be run locally; in that case –master local is used.

    import sys
    from pyspark import SparkContext
    if __name__ == "__main__":
        if len(sys.argv) < 3:
            print >> sys.stderr, "Usage: WordCount <file>"
            exit(-1)
    sc = SparkContext()
    counts = sc.textFile(sys.argv[1]) \
    .flatMap(lambda line: line.split(',')) \
    .map(lambda word: (word,1)) \
    .reduceByKey(lambda v1,v2: v1+v2)
    counts.saveAsTextFile(sys.argv[2])
    sc.stop()
    
  • Joining files with Pyspark

    Pyspark allows us to process files in a big data/ Hadoop environment. I showed in another post how Pyspark can be started and how it can be used.
    The concept of Pyspark is very interesting. It allows us to circumvent the limitations of the mapreduce framework. Mapreduce is somewhat limiting as we have two steps: the map phase where records are processed and a reduce phase where aggregates are processed.
    Pyspark has more flexibility as we may mix both phases: first a mapping, then reduce, then going back to mapping.

    To show how it works, we start with two files. One file is called “namen” and it has next content:

    tom,1
    ine,2
    paula,3
    stella,4
    bart,5
    

    A second file is called leeftijd with subsequent content:

    1,59
    2,58
    3,28
    4,26
    5,22
    

    The two files both have a key (‘1′,’2’,’3’etc.). In the first file, we have a name with the key. In the second file, we have a key with the age attached.
    The purpose of my exercise is a join the two files on their key. The results should be a file that contains the name and the age. The programme reads like:

    namen=sc.textFile('/user/hdfs/namen')
    namen1 = namen.map(lambda line: line.split(',')).map(lambda fields: (fields[1],(fields[1],fields[0])))
    leeftijd = sc.textFile('/user/hdfs/leeftijd')
    leeftijd1 = leeftijd.map(lambda line: line.split(',')).map(lambda fields: (fields[0],(fields[0],fields[1])))
    samen=leeftijd1.join(namen1)
    samen1=samen.map(lambda x: (x[1][1][1],x[1][0][1]))
    samen1.saveAsTextFile('/user/hdfs/naamleeftijd')
    

    Pyspark works with RDD. Very roughly stated, these are tables with rows that may contain data elements or structures with data elements. On these RDD, we have mapping and filter functions that allow to modify a RDD. There are several ways to create such RDD. One possibility is to make use of the “sc” object. It has a method textFile that allows to read a file and store the content as a RDD.

    When a file is read, each line is an element. As we have a key and a name in the file namen, we would like to be able to access the key and the name as two separate elements. So the line is split into two fields. in a subsequent step, the key is separated from the remainder of the line.

    The same exercise is repeated for the leeftijd file. Also there, we would like to have a key and something that contains the remainder of the values.

    We then have 2 RDD, both with a key and additional information. That can then be joined into a new RDD.

    We then take the relevant items and write the content to a file on Hadoop.