Category: data warehousing

  • Oracle create loader file

    Creating a loader file is tedious. The syntax is complicated. Moreover, small errors lead to a rejection of records. Luckily, we have the possibility to generate them from SQL Developer.

    One possibility is to use the SQL Loader. This facility has an import/ export module that allows to create such files. If one would like to export data to have them imported elsewhere, one may use the export facility with subsequent parameters:

    One then gets a control file that looks like:

    OPTIONS (ERRORS=50)
    LOAD DATA 
    INFILE 'C:\Users\tmaanen\Downloads\EMPLOYEES_BU_DATA_TABLE_1.ldr' "str '\r\n'"
    APPEND
    CONTINUEIF NEXT(1:1) = '#'
    INTO TABLE "HR"."EMPLOYEES_BU"
    FIELDS TERMINATED BY'|'
    OPTIONALLY ENCLOSED BY '"' AND '"'
    TRAILING NULLCOLS ( 
    "EMPLOYEE_ID" ,
    "FIRST_NAME" CHAR (20),
    "LAST_NAME" CHAR (25),
    "EMAIL" CHAR (25),
    "PHONE_NUMBER" CHAR (20),
    "HIRE_DATE" DATE "YYYY-MM-DD HH24:MI:SS" ,
    "JOB_ID" CHAR (10),
    "SALARY" ,
    "COMMISSION_PCT" ,
    "MANAGER_ID" ,
    "DEPARTMENT_ID" )

    I then truncated the table to see if the system works. I fired a command to load the records. I got:

    Success.

    Another possibility is to use the import facility. This is useful if one has a dataset for which a SQL Loader script is requested. One has several screens. One of them allows to select the SQL Loader.

    The generated script is:

    load data 
    infile 'export.csv' "str '\r\n'"
    append
    into table FLIP
    fields terminated by '|'
    OPTIONALLY ENCLOSED BY '"' AND '"'
    trailing nullcols
               ( EMPLOYEE_ID,
                 FIRST_NAME CHAR(4000),
                 LAST_NAME CHAR(4000),
                 EMAIL CHAR(4000),
                 PHONE_NUMBER CHAR(4000),
                 HIRE_DATE DATE "RRRRMMDD",
                 JOB_ID CHAR(4000),
                 SALARY,
                 COMMISSION_PCT,
                 MANAGER_ID,
                 DEPARTMENT_ID
               )

    This can be executed with desired results:

  • Useful Scala Programme

    I saw a small Scala programme that allows you to calculate subtotals. The idea is that a flat file is provided with a name and a subtotal. A given namen can occur more than one, thus providing a subtotal more than once. The question is to calculate the total per name. Let me provide some records from a file that provides key data.

    ABIGAIL,46
    ABIGAIL,13
    ABDULLAH,11
    

    The programme then looks like:

    val testTom = sc.textFile("/user/training/testTom.txt")
    val filteredRows = testTom.filter(line => !line.contains("Comma")).map(line => line.split(","))
    filteredRows.map ( n => (n(0),n(1).toInt)).reduceByKey((a,b) => a+b).sortBy(_._2).collect.foreach(println _)
    

    The first line reads a file from a Hadoop platform and stores it as a so-called RDD.
    The second line removes the first line and splits the other lines in elements that are split by comma.
    Then, in the third line, the first column is used as a key and the data from the second column are added over the different values from the first column. The results are sorted. Finally the results are printed.
    The results look like:

    (JAYDEN,7807)
    (MATTHEW,7891)
    (MICHAEL,9187)
    
  • Joining files by Pig

    In the previous post, we used scala to merge two files. The interesting feature is that scala bypasses Mapreduce. Pig uses Mapreduce. If we undertake the same example, we will see a serious performance difference.

    fooOriginal = LOAD '/user/prut/foo' USING PigStorage('|')
    AS (id :long, foo:long);
    barOriginal = LOAD '/user/prut/bar' USING PigStorage('|')
    AS (id :long, bar:long);
    joinedValues = JOIN fooOriginal by id, barOriginal by id;
    store joinedValues into '/user/pig' USING PigStorage('|');
    

    The end result will be written to a HDFS file that is stored in the directory /user/pig.
    Of course, the results are the same; on the other hand, we see a serious performance difference. Reason being that under water, mapreduce is used.

  • Joining files by Scala

    In this note, I will provide another script to join two files. The files are foo and bar. They contain lines whereby the elements are separated by a bar (|). One example of such line is 1|110. So the first step is to split the lines. Then the file is indexed on one element. Subsequently, it can be joined.
    As a final step, the results are shown.
    The code looks like:

    var fooTable = sc.textFile("/user/prut/foo")
    var barTable = sc.textFile("/user/prut/bar")
    var fooSplit = fooTable.map(line => line.split('|'))
    var fooKeyed = fooSplit.keyBy(cells => cells(0))
    var barSplit = barTable.map(line => line.split('|'))
    var barKeyed = barSplit.keyBy(cells => cells(0))
    var joinValues = fooKeyed.join(barKeyed)
    joinValues.take(10)
    

    The result looks like

    res0: Array[(String, (Array[String], Array[String]))] = 
    Array((2,(Array(2, 108),Array(2, 98))), 
    (3,(Array(3, 104),Array(3, 101))), 
    (1,(Array(1, 110),Array(1, 96))))
    
  • OBIEE First report

    Oracle has a very nice reporting tool, called OBIEE. It is positioned on top of their database. This allows to exploit the data. To do so, a separate (Weblogic OBIEE) server is created that processes the data for reporting purposes. So on the server side, at least two server processes are running: the DBMS and the weblogic OBIEE server.
    When a report will be created, data must be stored in DBMS. Let us assume, we have this set of tables in the DBMS.

    The first step is to add the metadata on these tables to the repository in the Weblogic server. This repository is maintained by the Oracle BI Administration tool. This tool is a client tool that can be installed on the Windows platform. I noticed that the version number of that tool must exactly match the version of the Weblogic OBIEE version. In my example I used version 12 of both the server and the Oracle BI Administration tool.
    The Oracle BI Administration tool has 3 different layers: a physical layer, a business layer and a presentation layer.
    The physical layer is a mirror from the actual database. We copy the tables, relevant fields and relations from the database. The only difference between the database and the definition in the repository is that irrelevant fields are excluded. Let us show how the definitions look like:

    The model above shows that the table names and relations are a 1 to 1 copy from the database. the tables have less fields as irrelevant fields are omitted.
    The second level is the business layer. In the business layer, we apply the business logic. We have three steps here.

    • The tables are modified to get a proper star like model with a fact table that is surrounded by denormalised tables whereby each dimension has one table only. It is applied here where 4 tables are joined together to form one geographical table. More specifically, winkelfiliaal, countries, topgrenzen_prov_actueel, and topgrenzen_gem_actueel are joined together in one table that contains geographical information.
    • An hierarchy is created. This hierarchy shows that the total can be decomposed into information on countries. On its turn countries can be decomposed into provinces. Further to gemeente. Finally the individual shops are provided.
    • Invidual fields are modified. An an example, some fieldnames are adjusted to make them more descriptive.


    Above, a screenshot is provided that shows the work in the business layer.

    • To create a dimensional table from several physical tables, a so-called logical datasource is created. The definition of the logical data source contains the physical tables and the joins between them.
    • The geographical hierarchy (total>country>provincie>gemeente>shop) is created in several steps. Starting from total each underlying level is explicitly mentioned. On the bottom level a shared detail level must be created. On each level two fields are added: one field is used to indicated the identifiers that are used to link the tables. Another field is used to display the levels. Here a descriptive name can be used.

    The third level is the presentation layer. Here, we only include the fields that will be used to create the reports. This implies that technical fields can be omitted. So, primary keys are only included if they are understandable by the user; the same holds for the foreign key fields. We get:

    Within table “omzet”, the foreign keys are removed. Such fields only have a technical meaning and they can be omitted as they have no relevance for the user.
    Also identifiers for the levels countries, provinces, and gemeentes are omitted for the same reason: no relevance to the end user.
    The tables are collected in a subject area “Voorbeeld2”.

    We have two kinds of data in the presentation layer: fields that be used for the report and an hierarchy the allows to jump from level to the level underneath.

    Now the repository is updated. Now we can turn to the analysis. The analysis can be started. We do this from the internet site that allows to connect to the OBIEE server. The address is something like http://192.168.2.36:7780/analytics. Upon logging in, one may start the analysis. We get:

    On the left side, one sees the items that were created in the presentation layer. As we left out all elements that only have a technical function, we only have items that are understandable by the end user. The user may select from the fields that are indicated with a square. We also see the hierarchy that was created.
    The existence of the hierarchy becomes clear if we look at the results. One sees “country” as a hyperlink:
    .
    Clicking on this hyperlink displays the next level. Clicking again quickly leads you down to the lowest level of detail:

  • ElasticSearch: Restful services

    As we have seen in a previous post, we communicate with the ElasticSearch server via messages that are sent to a server. On the other hand, the server responds in messages that are received by the client. This system of messages are labelled as s “RESTful” structure. This RESTful structure is based om messages that contain all information necessary.

    Such message from a client is composed of 3 elements:

    1. The host that is addressed
    2. The action that is required from the host
    3. All information necessary to be processed by the host

    This information is stored in one message only. This message is complete: it is known by the system which node needs to do what with all necessary information. As an example, let us see how data are stored in ElasticSearch. Within the message, we know which node governs the ElasticSearch database; we know what needs to be done (PUT indicates data must be stored) and with the accompanying json file, se know the data that must be stored.

    The server responds with a message that contains the result of the action, whether the action was successful or not along with additional information if required by the client.

     

    The advantages of this structure is that it provides a stateless situation: the client messages do not depend on other client messages. This allows client messages to be handled in an arbitrary sequence.

    This also allows decoupling: if the server decides to change its programme or if it is decided to distribute the programme over different nodes, no change in the messages are needed. Doing so, it is possible to scale up the server without interruption on the client side. Doing so, complexity is reduced as only the server layers need to be adjusted.

     

     

     

     

     

  • Scala and RDDs

    RDDs are the basic unit in Scala on Spark. The abbreviation stands for Resilient Distributed Dataset, This shows that we are talking on full data sets that are stored persistently on a distributed network. So the unit of work is comparable to a table. We have two different operations on this RDD. These are a filter, where some rows are left out and a map where the rows are manipulated. Below, I collected two sets of examples of scala statements on such RDD. This might then be used as a cookbook for future use.

    The mapping functions:

    val mydata_uc = mydata.map(line => line.toUpperCase())
    val myrdd2 = myrdd1.map(pair => JSON.parseFull(pair._2).get.asInstanceOf[Map[String,String]])
    val myrdd2 = mydata.map(line => line.split(' '))
    val myrdd2 = mydata.flatMap(line => line.split(' '))
    var pipo = logs.map(line => line.length)
    var pipo = log.map(line => (line.split(' ')(0),line.split(' ')(2)))
    val users = sc.textFile("/user/hdfs/keyvalue").map(line => line.split(',')).map(fields => (fields(0),(fields(0),fields(1)))) 
    val users = sc.textFile("/user/hdfs/keyvalue").keyBy(line => line.split(',')(0))
    val counts = sc.textFile("/user/hdfs/keyvalue").flatMap(line => line.split(',')).map(fields => (fields,1))
    val counts = sc.textFile("/user/hdfs/keyvalue").flatMap(line => line.split(',')).map(fields => (fields,1)).reduceByKey((v1,v2) => v1+v2)
    val avglens = sc.textFile("/user/hdfs/naamtoev").flatMap(line => line.split(" ")).map(word => (word,word.length)).groupByKey().map(pair => (pair._1, pair._2.sum/pair._2.size.toDouble)) 
    

    The filter function:

    val mydata_uc = mydata.filter(line => line.startsWith("I"))
    var jpglogs = logs.filter(line => line.contains(".jpg"))
    
  • A python script with many steps

    Pyspark is the python language that is applied to spark. It therefore allows a wonderful merge between spark with its possibilities to circumvent the limitation that are set by the mapreduce framework and python that is relatively simple.

    In the scheme below, some steps are shown that might be used.

    sc.textFile allow to read a file and process its as a RDD (resilient distributed dataset). This stands for a dataset that is distributed over nodes and which can be recreated fast.

     

    flatMap allows to create multiple lines from one line.

    Map processes one line. From one word, two fields are created: the original word and a field with the length of a word.

    filter allows to filter the lines.

    groupByKey aggregates the lines by the first field that acts as a key.

    map then translates the aggregate into something that is human readable.

    collect displays the results.

     

  • Dataflow in Oracle Warehouse Builder

    I know that Oracle Warehouse Builder (OWB) is at end of life. On the other hand, I encounter OWB quite often and it is interesting to see how it works.
    So investigate how it works, I created a dataflow. It it a trivial one: it consists of a file that must be read into Oracle.
    The first step is to create a file and assign it to OWB. The file is quite simple. I created this flow:

    nummer;naam
    1;"tom"
    2;"ine"
    3;"paula"
    4;"stella"
    5;"bart"
    

    The metadata on this file is added to OWB. One must have a so-called location that provides data where the file can be found. From that location, the metadata on the file can be imported. In that process, the screen looks like:
    untitled
    A file is imported via the construct of an external file. This is an object in the database that allows to read a flat file from within the Oracle database.
    The external file is created from within Oracle Warehouse builder. This must be stored within the metadata on the database. After that code can be generated and deployed on the database.
    See:
    untitled
    If it is deployed on the database, one may verify its existence of that table with, say, sql developer. I realise the code and its deployment is steered from OWB.
    Another important element is the target file. Let us assume, we have a target file in the database. The metadata on that table can be imported. If that is done, one may see in OWB:
    untitled
    The sources and the targets are now known. These are the key elements of a mapping. The mapping in this case is almost trivial.
    untitled
    If the mapping is created, it can be generated as an PLSQL script. This can be deployed on Oracle. This package can be run from any client tool (SQL Developer, SQL Plus, OWB). This package is like any other package that you created yourself.

  • reading an HDFS file in Python

    In this note, I show you how to get data from an HDFS platform into a Python programme. The idea is that we have data on HDFS and we would like to use these data in a Python programme. So, we must connect to HDFS from within a Python programme, read the data , transform them and store these.

    One may achieve this from the usage of Spark. This can be started by the command “pyspark” in linux. Hopefully, you see something like:

    untitled

    All in all, getting a file in Python with Spark is a bit complicated. First, we need to import the right library that allows to set a connection to the HDFS platform. We can then access the HDFS platform. Implicitly, a context is created. From that object, the HDFS file can be retrieved. The lines in the file must then be split into fields. Once that is done, the content can shown with the method “collect”. Thhe code is:

    from  pywebhdfs.webhdfs import PyWebHdfsClient
    hdfs = PyWebHdfsClient(user_name="hdfs",port=50070,host="192.168.2.59")
    data = sc.textFile("/Chapter5/uit2")
    parts = data.map(lambda r:r.split(';'))
    datalines = parts.filter(lambda x:x)
    for i in datalines.collect():
      print(i)
    
    tabel = datalines.toDF(['nummer','naam'])
    tabel.select("nummer", "naam").show()
    tabel.filter(tabel['nummer'] == '1').show()
    
    

    The first line “from pywebhdfs” etc. links the programme to the webhdfs service. Within HDFS, one may verify whether this works by looking at the properties of HFDS. One should see something like:
    untitled

    This is taken from Hortonworks that I currently use. The webhdfs allows you to communicate with the hdfs platform. As an example if you want to know the status of hdfs, one may use any browser and type: “http://server:50070/webhdfs/v1/user/hdfs?op=LISTSTATUS”, with server the hdfs server.

    So, the from statement allows the Python programme to communicate with hdfs.

    In the second statement (PyWebHdfsClient) is wrapper around the webhdfs service. This wrapper extends the service and it allows to provide the server and the user.

    The third line (“sc.textfile”) reads the file from the service stream that we just opened up. We must indicate which file to read.

    The fourth line (“map(lambda r: “) is a very concise way of creating a function. Whatever we see after the semi colon is the transformation. Before the semi colon, the expression for an outcome is given. The idea is that a row (“1 tom”) is split along the blank in the row.

    For.. allows to display the different rows in the result we have sofar.

    The subsequent line (“filter(lamda”) is an elegant way of filtering the rows for which the preceding split was successful.

    The next line (“toDF”) is used to change from RDD to DF. RDD stands for Resilient Distributed Dataset that is more of a blackbox of data that cannot be optimized as the operations that can be performed against it, are not as constrained. DF stands for Data Frame which is a table, or two-dimensional array-like structure, in which each column contains measurements on one variable, and each row contains one case.

    The last line selects some columns and shows them to the user whereas the subsequent line filters on a certain value.