Category: Allgemein

  • Analysing JSON and database tables in Spark

    In a previous note, I showed how CSV files can be analysed. One may use the same technique to analyse JSON files or tables in a database. First, analysing JSON files can be analysed with code that looks like:

    val jsonRDD = sc.wholeTextFiles("/user/tom/baby_names.json").map(x => x._2)
    val namesJson = sqlContext.read.json(jsonRDD)
    namesJson.registerTempTable("names")
    sqlContext.sql("select * from names").collect.foreach(println)
    

    Going to a table in a database, requires an additional jar, that allows to access a database. in case of MySQL, we may use mysql-connector-java-5.0.8-bin.jar, that must be stored in a directory next to other jars. We can then fire spark with spark-shell –jars lib/mysql-connector-java-5.0.8-bin.jar.
    The code looks like:

    val df1 = sqlContext.read.format("jdbc").option("url","jdbc:mysql://van-maanen.com/wordpress").option("driver","com.mysql.jdbc.Driver").option("dbtable","wp_comments").option("user","tom").option("password","filpso").load()
    df1.registerTempTable("names")
    sqlContext.sql("select * from names").collect.foreach(println)
    
  • Install Spark on windows

    I found a beautiful YouTube movie that showed how Spark can be installed on windows. I found this on https://www.youtube.com/watch?v=WlE7RNdtfwE . The movie provided a clear guide how to this up. It provides a step by step approach.

    The first step is install JDK. I installed this from https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html. This allowed me install version 8, that was also used in the YouTube movie. The file that contains JDK is called jdk-8u181-windows-x64.exe. It will be installed in C:\Program Files\Java\jdk1.8.0_181 . This installation path will be used as environment variable for JAVA_HOME, that is then set to C:\Program Files\Java\jdk1.8.0_181 . The path must be changed as %JAVA_HOME%\bin must be added to the path.

    The second step is to add winutils.exe to the system. It can be downloaded from GitHub or here. This can be stored in c:\winutils\bin. Create an environment variable HADOOP_HOME, that refers to c:\winutils. The path must be changed as %HADOOP_HOME%\bin must be added to the path.

    The third step is to download Spark from spark.apache.org . I downloaded version 1.6.3. I downloaded the pre built version for Hadoop 2.6, which is the closest to the versions used in the YouTube movie. This must unzipped. I unzipped this into c;\spark-1.6.3-bin-hadoop2.6 . An environment variable SPARK_HOME was set to c:\spark-1.6.3-bin-hadoop2.6 . The path must be updated to %SPARK_HOME%\bin .

    We then have as environment:

    and the bin directories to HADOOP_HOME, JAVA_HOME and SPARK_HOME being added to the path.

    The last step is install the scala IDE from scala-ide.org. This provides a directory eclipse that must stored on a disk.

    We then can boot up SPARK with spark-shell that produces:

    He, got Spark on windows now. Nice.

  • The tango between Hive and Impala

    An interesting tango exists between Hive and Impala.
    The situation is as follows. Hive acts as an layer upon map reduce. It provides an interface whereby table definitions can be stored in a so-called metadata store. See below:

    This metastore allows us to interpret directories on HDFS as tables. As they can be interpreted as tables, we may apply SQL on them. The SQL statements are somehow translated into a map reduce procedure and they return results as we expect from SQL.
    The advantage is obvious: we may use SQL instead of writing map reduce programmes.
    However, as SQL statements are translated into map reduce items, we stick to the issue that map reduce regularly writes data to disk and it is somewhat slow in starting.
    Impala circumvents this map reduce bottlenecks. It nevertheless uses the Hive SQL dialect and it also uses the Hive metadata store. So it is relatively easy to switch from Hive to Impala.
    But the idea to circumvent Mapreduce bottlenecks is exactly what is undertaken in the newer versions of Hive. Hive now uses Tez is stead of of map reduce. This makes Hive faster than Impala. So we may return from Impala to Hive.

    Etc. To be continued.

  • Flume used for logs

    In an earlier post, I showed how one may send a stream via netcat to hdfs using flume. Another possibility is to set up a stream that is received by a server whereby the data are directly shown. The idea is that the client starts with telnet or netcat whereby data are sent. On the server side, the data are shown directly.
    Let us set up the flume. The config file is:

    # example.conf: A single-node Flume configuration
    # Name the components on this agent
    a1.sources = r1
    a1.sinks = k1
    a1.channels = c1
    # Describe/configure the source
    a1.sources.r1.type = netcat
    a1.sources.r1.bind = 192.168.2.25
    a1.sources.r1.port = 12345
    # Describe the sink
    a1.sinks.k1.type = logger
    # Use a channel which buffers events in memory
    a1.channels.c1.type = memory
    a1.channels.c1.capacity = 1000
    a1.channels.c1.transactionCapacity = 100
    # Bind the source and sink to the channel
    a1.sources.r1.channels = c1
    a1.sinks.k1.channel = c1
    

    Flume is then started with flume-ng agent –conf /etc/flume-ng/conf –conf-file /home/training/netcat_log.conf –name a1 -Dflume.root.logger=INFO,console.

    On the client, we start either telnet: telnet 192.168.2.25 12345. Or we start netcat with: netcat 192.168.2.25 12345. This looks like:

    On the client, we started a stream with “tom”.
    Whereas on the serverside, we see:

    On the server, this “tom” is received.

  • Datamodelling in Hadoop

    Before data modelling in Hadoop can be discussed, one needs to realise that Hadoop is about files. It is not about tables and relations – it is the files that is central. This implies that we have other means at our disposal than we have in a traditional RDMBS.
    As Hadoop is about files, we have to realise that data that are stored in two different tables are difficult to retrieve. One has to read two different files, combine the two files on some common denominator and subsequently deliver the end result.
    Therefore, a first lesson can be drawn. The concept of full normalisation doesn’t work with Hadoop as we have no efficient means to combine data from different files. Therefore, it is good to denormalise the data. This generates a situation whereby data are stored redundantly, each time is a different context. In case of an order, the customer information is stored with the order. If the same customer opens up another order, the customer information is repeated with the new order.
    A second lesson is that it is beneficial to create small files instead of large one. If one needs to join information from two different files, it is better to have small files to be read than large ones. This can be implemented by storing information in tables that are split by day. Instead of taking a large files with data from all days, one only the taken the file that pertain to a certain date for which the join must be made.
    A third lesson is that directory structure must be clear. The same holds for filenames. Clear directory structure and clear filenames allow you to retrieve the data quickly.

    It is good to realise that this data modelling is necessary to retrieve the data. In traditional RDBMS, we need a data model to ingest the data. With Hadoop, data can be ingested without a model; just create a set of files. It is possible. However, the price to be paid is that is difficult to retrieve the information. If one would have created to set of unrelated files, modelling will be done by the end user upon the moment he starts using the data.

  • HBase

    HBase is a database system that is built on top of HDFS. However the term ‘database’ might be a bit misleading. It is not a traditional SQL database that can be accessed by a traditional SQL type client, such as SQL developer.
    HBase is a technique that falls in the area of no SQL, – Not Only SQL. This implies that other techniques must be used as we know from SQL type database.
    One possible way to access this environment is via a shell. This shell can be invoked via “hbase shell”. If everything is set up correctly, one sees something like:

    A command to see which tables are available is given via “list”:

    hbase(main):004:0> list
    TABLE                                                                                                                                                        
    emp                                                                                                                                                          
    1 row(s) in 0.1520 seconds
    
    => ["emp"]
    

    Here, we see that a table “emp” exists. On may investigate the content via “scan ’emp’”:

    hbase(main):005:0> scan "emp"
    ROW                                      COLUMN+CELL                                                                                                         
     1                                       column=naam:, timestamp=1528294868410, value=tom                                                                    
     1                                       column=naam:voornaam, timestamp=1528294898266, value=jan                                                            
     1                                       column=nummer:, timestamp=1528294834043, value=1                                                                    
     2                                       column=naam:voornaam, timestamp=1528296099663, value=flip                                                           
    2 row(s) in 0.0320 seconds
    
    hbase(main):006:0> 
    

    One may subsequently insert new data via a put command. In this command, we must mention the table (here emp), the row (here 2), the field (here naam:voornaam) and the actual value.

    hbase(main):002:0> put 'emp',2,'naam:voornaam','flip'
    0 row(s) in 0.0840 seconds
    
    
  • Write an AVRO file

    Below, I provide some Python code to write an AVRO file. An AVRO file consists of a scheme and a set of records. The records are written in binary format. The scheme is as follows:

    {"type": "record",
     "name": "StringPair",
     "doc": "A pair of strings.",
     "fields": [
         {"name": "left", "type": "string"},
         {"name": "right", "type": "string"}]}
    

    The code to write such file is as follows:

    import sys
    from avro import schema
    from avro import io
    from avro import datafile
    if __name__ == '__main__':
        if len(sys.argv) != 2:
                sys.exit('Usage: %s ' % sys.argv[0])
    avro_file = sys.argv[1]
    writer = open(avro_file, 'wb')
    datum_writer = io.DatumWriter()
    schema_object = schema.Parse(open(b'C:\\Users\\tmaanen\\.spyder-py3\\tom.avsc', "r").read())
    dfw = datafile.DataFileWriter(writer, datum_writer, schema_object)
    for line in sys.stdin.readlines():
        (left, right) = line.split(',')
        dfw.append({'left':left, 'right':right});
    dfw.close()
    

    The script can be run on the command line as C:\ProgramData\Anaconda3\python.exe C:\Users\tmaanen\.spyder-py3\TomHdfs.py C:\Users\tmaanen\.spyder-py3\a.avro

  • Copying content of an Oracle table into an avro file

    Below, you will find a listing on how to copy the content of an Oracle table into an avro file. The trick is quite straight forward. A table is read via a cursor. Each record is then appended to an avro file. The scheme is:

    {
    
      "namespace": "example.avro",
      "type": "record",
      "name": "User",
      "fields": [
          {"name": "name", "type": "string"},
          {"name": "number",  "type": ["int", "null"]},
          {"name": "local", "type": ["string", "null"]}
      ]
    }
    

    So:

    import avro.schema
    from avro.datafile import DataFileWriter
    from avro.io import DatumWriter
    import cx_Oracle
    teller =0
    
    schema = avro.schema.Parse(open("user.avsc").read())
    writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema)
    con = cx_Oracle.connect('C##HR/xxx12345@van-maanen.com/orcl')
    
    cur = con.cursor()
    cur.execute('select name, local from countries')
    for result in cur:
        teller = teller + 1
        writer.append({"name": result[0], "number": teller, "local": result[1]})
        
    cur.close()
    con.close()
    writer.close()
    
  • Sending Avro file via HTTP

    It is possible to send an AVRO file via HTTP. The idea is that one sets up a server process. Once the server process runs, a client call is made.
    I found a neat scheme how such process works.

    We see on the server side, a socket must be set up. This set-up must also be undertaken with an indication which type of network is utilized. The most common network in the IP4 system: 4 numbers, indicating the position in a network. This is indicated with “AF_INET”. Once the socket is set up, it must be linked to an (internal) IP address. This link is indicated with the port. After that the server can be instructed to start listening to a particular port.
    The system will be instructed to receive AVRO files. Therefore the avro modules are imported.

    One is then able to see how the server reacts upon the client call. We use Python3 to work this out. The server process runs as;

    import avro.datafile
    import avro.io
    import io
    import socket
    
    def handle_client(connection, address):
        data = connection.recv(1024)
        message_buf = io.BytesIO(data)
        reader = avro.datafile.DataFileReader(message_buf, avro.io.DatumReader())
        for thing in reader:
            print(thing)
        reader.close()
    
    def main():
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('archief.van-maanen.com/', 54321))
        sock.listen(10)
    
        while True:
            conn, addr = sock.accept()
            handle_client(conn, addr)
            conn.close()
    
    if __name__ == '__main__':
        main()
    

    A more extended programme can be seen here:

    The client programme then looks like:

    import io
    import json
    import socket
    import avro.datafile
    import avro.schema
    import avro.io
    import avro.ipc
    
    SCHEMA = avro.schema.Parse(json.dumps({
     "namespace"    : "example.avro",
     "type"         : "record",
     "name"         : "User",
     "fields"       : [
         {"name": "name"            , "type": "string"},
         {"name": "favorite_number" , "type": ["int", "null"]},
         {"name": "favorite_color"  , "type": ["string", "null"]}
     ]
    }))
    
    def send_message(connection, message):
        buf = io.BytesIO()
        writer = avro.datafile.DataFileWriter(buf, avro.io.DatumWriter(), SCHEMA)
        writer.append(message)
        writer.flush()
        buf.seek(0)
        data = buf.read()
        connection.send(data)
    
    def main():
        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connection.connect(('192.168.2.25', 54321))
        send_message(connection, {'name': 'Eli', 'favorite_number': 42, 'favorite_color': 'black'})
    
    if __name__ == '__main__':
        main()
    

    A more extended programme can be seen here:

    Another elaborate programme can be seen here:

  • Show content of an AVRO file with Python

    This note describes how we can show the content of an AVRO file with Python.
    We use python3 as tool here. We use this from an Anaconda framework. I checked whether this installation already contained an AVRO package, but this wasn’t the case. Therefore, AVRO was downloaded (as avro-python3-1.8.2.tar.gz) and next command was issued: C:\ProgramData\Anaconda3\python.exe -m pip install C:\ProgramData\Anaconda3\avro-python3-1.8.2.tar.gz. The screen then looked like:
    .
    Once, AVRO was installed, an AVRO file can be created with:

    import avro.schema
    from avro.datafile import DataFileWriter
    from avro.io import DatumWriter
    
    schema = avro.schema.Parse(open('file.avsc', "r").read())
    
    writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema)
    writer.append({"name": "Alyssa", "favorite_number": 256})
    writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"})
    writer.close()
    

    Here use was made of a file that contained the schema:

    {"namespace": "example.avro",
     "type": "record",
     "name": "User",
     "fields": [
         {"name": "name", "type": "string"},
         {"name": "favorite_number",  "type": ["int", "null"]},
         {"name": "favorite_color", "type": ["string", "null"]}
     ]
    }
    

    When a file was created, it can be read as:

    from avro.datafile import DataFileReader
    from avro.io import DatumReader
    
    reader = DataFileReader(open("users.avro", "rb"), DatumReader())
    for user in reader:
        print (user)
    reader.close()
    

    This latter programme is nice: another avro file can be read. I downloaded another avro file (called twitter.avro) and the corresponding outcome looked like:

    
    runfile('C:/Users/tmaanen/.spyder-py3/avroTomLees.py', wdir='C:/Users/tmaanen/.spyder-py3')
    {'username': 'miguno', 'tweet': 'Rock: Nerf paper, scissors is fine.', 'timestamp': 1366150681}
    {'username': 'BlizzardCS', 'tweet': 'Works as intended.  Terran is IMBA.', 'timestamp': 1366154481}