Category: Uncategorized

  • Read and write by Python

    Python seems to be a very convenient way to transfer data to and fro Oracle. It has capabilities to set up a connection and it seems quite capable to transfer a matrix into a table and vice versa. Next code shows this. It first retrieves the content of a table. In a second step some data from a matrix are stored into a table.

    import cx_Oracle
    con = cx_Oracle.connect('scott/bunvogni@van-maanen.com/orcl')
    cur = con.cursor()
    cur.execute('select * from departments order by department_id')
    res = cur.fetchall()
    print res
    rows = [ (1, "First" ),
             (2, "Second" ),
             (3, "Third" ),
             (4, "Fourth" ),
             (5, "Fifth" ),
             (6, "Sixth" ),
             (7, "Seventh" ) ]
    cur = con.cursor()
    cur.setinputsizes(int, 20)
    cur.executemany("insert into mytable(id, data) values (:1, :2)", rows)
    con.commit()
    con.close()
    
  • Python in a map reduce environment

    I have written a very small python programme that follows the mapper / reducer sequence. This works as a replacement of a more complicated set of Java programmes that might be created to generate a mapper / reducer sequence. The idea is relatively simple. We create a stream from an input file. That stream is processed by a mapper programme (written in Python) that produces a series of name, value pairs. These value pairs are written to disk. That must then be sorted and subsequently streamed to a reducer programme (written in Python). That programme then produces the final outcome. This is also written to disk.
    Such logic is used on a hadoop platform. The idea to stream data to a mapper is translated on a hadoop platform as something that can be run concurrently on different nodes. After that the intermediate output stream is sent a stream of name, value pairs to a reducer where the final calculations are made. These results are sent as a file with name, value pairs.
    Let us first look at an input file that is used to be analysed. It looks like:

    2013-10-09	13:22	Gouda	Wafels	2.98	Visa
    2013-10-09	13:22	New York	Iphone	455.76	tMasterCard
    2013-10-09	13:22	New York	Rommel	354.76	tMasterCard
    2016-10-09	I/O error
    

    This input set is processed by this Python programme:

    #!/usr/bin/python
    # Your task is to make sure that this mapper code does not fail on corrupt data lines,
    # but instead just ignores them and continues working
    import sys
    
    def mapper():
        # read standard input line by line
        for line in sys.stdin:
            # strip off extra whitespace, split on tab and put the data in an array
            data = line.strip().split("\t")
    
            # This is the place you need to do some defensive programming
            # what if there are not exactly 6 fields in that line?
            if len(data) != 6:
                continue
    
            # this next line is called 'multiple assignment' in Python
            # this is not really necessary, we could access the data
            # with data[2] and data[5], but we do this for conveniency
            # and to make the code easier to read
            date, time, store, item, cost, payment = data
    
            # Now print out the data that will be passed to the reducer
            print "{0}\t{1}".format(store, cost)
    
    
    def main():
    
    	mapper()
    	sys.stdin = sys.__stdin__
    
    main()
    

    One might test whether it actually work by a command cat test | ./mapper.py. This should produce a set of name, value pairs. I got as outcome:

    [training@localhost ~]$ cat test | ./mapper.py
    Gouda	2.98
    New York	455.76
    New York	354.76
    

    Next programme is a reducer programme that looks like:

    #!/usr/bin/python
    
    import sys
    
    
    salesTotal = 0
    oldKey = None
    
    # Loop around the data
    # It will be in the format key\tval
    # Where key is the store name, val is the sale amount
    #
    # All the sales for a particular store will be presented,
    # then the key will change and we'll be dealing with the next store
    
    for line in sys.stdin:
        data_mapped = line.strip().split("\t")
        if len(data_mapped) != 2:
            # Something has gone wrong. Skip this line.
            continue
    
        thisKey, thisSale = data_mapped
    
        if oldKey and oldKey != thisKey:
            print oldKey, "\t", salesTotal
            oldKey = thisKey;
            salesTotal = 0
    
        oldKey = thisKey
        salesTotal += float(thisSale)
    
    if oldKey != None:
        print oldKey, "\t", salesTotal
    

    This can also be run on Linux:

    [training@localhost ~]$ cat test | ./mapper.py | ./reducer.py
    Gouda 	2.98
    New York 	810.52
    

    A next step is to run everything on hadoop as a streaming set:

    hadoop jar /usr/lib/hadoop-0.20-mapreduce/contrib/streaming/hadoop-streaming-2.0.0-mr1-cdh4.1.1.jar -mapper mapper.py -reducer reducer.py -file mapper.py -file reducer.py -input /myinput/test -output joboutput
    

    which generates:

    packageJobJar: [mapper.py, reducer.py, /tmp/hadoop-training/hadoop-unjar5879319460019186346/] [] /tmp/streamjob1136107035137838419.jar tmpDir=null
    16/08/27 12:01:12 WARN mapred.JobClient: Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.
    16/08/27 12:01:12 WARN snappy.LoadSnappy: Snappy native library is available
    16/08/27 12:01:12 INFO snappy.LoadSnappy: Snappy native library loaded
    16/08/27 12:01:12 INFO mapred.FileInputFormat: Total input paths to process : 1
    16/08/27 12:01:12 INFO streaming.StreamJob: getLocalDirs(): [/var/lib/hadoop-hdfs/cache/training/mapred/local]
    16/08/27 12:01:12 INFO streaming.StreamJob: Running job: job_201608271023_0015
    16/08/27 12:01:12 INFO streaming.StreamJob: To kill this job, run:
    16/08/27 12:01:12 INFO streaming.StreamJob: UNDEF/bin/hadoop job  -Dmapred.job.tracker=0.0.0.0:8021 -kill job_201608271023_0015
    16/08/27 12:01:12 INFO streaming.StreamJob: Tracking URL: http://0.0.0.0:50030/jobdetails.jsp?jobid=job_201608271023_0015
    16/08/27 12:01:13 INFO streaming.StreamJob:  map 0%  reduce 0%
    16/08/27 12:01:16 INFO streaming.StreamJob:  map 100%  reduce 0%
    16/08/27 12:01:19 INFO streaming.StreamJob:  map 100%  reduce 100%
    16/08/27 12:01:21 INFO streaming.StreamJob: Job complete: job_201608271023_0015
    16/08/27 12:01:21 INFO streaming.StreamJob: Output: joboutput10
    

    The output can be inspected as

    [training@localhost ~]$ hadoop fs -cat /user/training/joboutput10/part-00000
    Gouda 	2.98
    New York 	810.52
    
  • Three little handy Oracle statements

    I have three little Oracle statements that I us quite often. I realise I use these statements in most programmes I write. But at the same time, I often forget the exact syntax. Therefore this entry in this blog. It will act as a look-up whenever I once again forgot the precise syntax.

    The first retrieves the hour from a datefield. It looks like:

    select to_number(substr(numtodsinterval( sysdate - trunc(sysdate), 'day' ),12,2)) as hour from dual;
    

    The second one provides a row number to each row. This row number is reset at 1 whenever one field changes value.

    select tel1, tel2, ROW_NUMBER () OVER (PARTITION BY  tel1 ORDER BY  tel2) AS RN
    from
    (select 1 as tel1, 1 as tel2 from dual union
    select 1 as tel1, 2 as tel2 from dual union
    select 2 as tel1, 1 as tel2 from dual union
    select 2 as tel1, 2 as tel2 from dual)A;
    

    A third handy Oracle statement is generating a number that is recognised in Excel as a date. Excel starts its date range by stating 01 January 1900 being equal to 1, 02 January 1900 being equal to 2, and so forth. This goes on and 42602 equals 20 August 2016. The statement is:

    select to_date(sysdate) - to_date('19000101','yyyymmdd')+2 as datum from dual;
    

    Why this “2” in this statement? This happens as Excel knows 29 Feb 1900 that never existed. Therefore 59 is 28 Feb 1900, 60 is 29 Feb 1900 and 61 is 1 March 1900. Excel thus assumes 1900 is a leap year, whereas this is never included in the Georgian calendar. This is a well-known issue with Excel. It is a bug that is maintained as to support backward compatability with Lotus 123.

  • Reading XML in Oracle -3

    I now have a project where I need to write the content of an XML file into an Oracle table. The idea is actually quite simple. An XML file might be seen as a document that had an hierachical structure. It is composed of several seperate subdocuments, that could be seen as several trees.   Each tree is a trunk  with branches, where a brach is translated into a table. The content of one branch is one record. A subdocument may have one or multiple branches and it thus generates one or more records. As we have one or more subdocuments in the document, we end up having one or more records in a table. The records stem from a branch in the subdocument and we may have more than one subdocument in the document.

    I created two procedures to read this XML file.

    The first procedure is a SQL LDR job that adds the XML document to an Oracle table. The XML document is stored as an object in an Oracle table.

    The second procedure retrieves the information from the XML object into records.

    Let me go in some detail here.

    Reading the XML object

    I created a table that may contain the XML objects. Its DDL is:

     CREATE TABLE "SCOTT"."XML_TAB_CONTRACT" 
       (	"XML_DATA" "XMLTYPE", 
    	"ID" NUMBER(*,0), 
    	"CONTRACT" NUMBER
       )
    

    The XML will be stored in XML_DATA which is a field of XMLTYPE.

    The CTL file that actually loads the XML file reads as:

    load data
    infile *
    append
    into table XML_TAB_CONTRACT
    fields terminated by ';' 
    (
     filename FILLER char(52),
     XML_DATA  lobfile(filename) terminated by eof,
     id,
    CONTRACT 
    )
    
    begindata
    C:\Users\Tom\Dropbox\Uitwisseling\Voorbeeld2078a.xml;201608131;2078
    
    

    And the command to start the loading process is as:SQLLDR CONTROL=C:\Users\Tom\Dropbox\Uitwisseling\xml.ctl LOG=sample.log, BAD=baz.bad, USERID=scott/binvegni, ERRORS=999, LOAD=500000, DISCARD=toss.dsc, DISCARDMAX=5. This starts the SQL LDR process which uses the CTL file to know which xml file must be loaded into which table.

    Reading the XML objects.

    The code to read the XML object is composed of two loops.
    One loop reads the XML file and looks for the branches that must be translated as records into the table. The branches are indicated by “/Message/PayLoad/ShipmentAsn4”. A cursor is defined that retrieves the set of XML objects. After that a loop is created that processes each object, one by one.
    The second loop actually translates the branch into a record. In the second loop, we retrieve the actual value one by one and store it as an attribute in an object that is indicated by “r” .

    reate or replace PROCEDURE SEARCH_XML
    AS
    v_waarde integer;
    name varchar(100);
    flip varchar(10);
    Lcntr integer:=0;
    docu varchar(9999);
    CURSOR c1
    IS
    SELECT EXTRACT(SYS_MAKEXML(0,"A1"."SYS_NC00002$"),'/Message/PayLoad/ShipmentAsn4') "AAPJE" FROM "SCOTT"."XML_TAB_CONTRACT" "A1"  ;
    l_aantal   c1%ROWTYPE;
    BEGIN
     dbms_output.enable;
     OPEN c1;
     LOOP
       Lcntr := Lcntr + 1;
       FETCH c1 INTO l_aantal;
       EXIT WHEN c1%NOTFOUND;
        FOR r IN (
        SELECT ExtractValue(Value(p),'/ShipmentAsn4/GlnShipTo/text()') as flip
        FROM TABLE(XMLSequence(Extract(XMLTYPE(''||l_aantal.aapje.getClobVal()||''),'     /totaal/ShipmentAsn4'))) p
       ) LOOP
       v_waarde := adresseq.nextval;
       dbms_output.put_line(Lcntr ||' ' || v_waarde||' '||r.flip );
      END LOOP; --rij in tak XML
      END LOOP; --vrsch XML in tabel
    
    END SEARCH_XML;
    

     

     

  • Bash script to upload file

    In many environment, we have a situation whereby a file must be transmitted via a script from one server to another. Assume we have a linux environment where Bash is installed. In that case, a sftp connection can be used. The principle is relatively simple: a sftp session is started from one machine to another. Via ftp commands, the file is transferred. But one may prefer to have a batch script that takes care of setting up the connection, transferring the file and closing the connection.
    I assume that the two machines have set up a connection via private/ public keys. This avoids the necessity of having to provide a password.
    One might use:

    #!/usr/bin
    
    sftp_user="pi"
    sftp_machine="192.168.2.11"
    
    eval sftp -b ftpregel $sftp_user@$sftp_machine
    
    rc=$?
    echo $rc
            if [ $rc -ne 0 ]
            then
                    echo "$PROGNAME: ERROR in sftp!"
            fi
    

    and the ftpregel that contains the ftp command looks like:

    put GeileBeer.log
    quit
    
  • A simple introduction into creating spatial report

    I write this to show you how to use Oracle Map Builder and Map Viewer to create spatial reports within Oracle BIEE.
    I assume you have a set of tables that can be used to generate future spatial reports. I use three tables:
    [1] Edge that contain a filiaal_num as an identifier and a point geographical object (geometry_pcode) that indicates the longitude/ latitude of that object. This object stored in a field with a special spatial type “MDSYS”.”SDO_GEOMETRY”.
    [2] Block_Groups that contain a code as an identifier and a polygon geographical object (geometry) that provide a series of longitude/ latitudes on an area. This object is also stored in a field with a a special type “MDSYS”.”SDO_GEOMETRY”.
    [3] Omzet, which has two foreign keys, one referring to filiaal_num and one referring to code along with a numeric value omzet.
    Here for a table creation file.
    I also assume that one has created special indices on the table EDGE and Block_Groups. To create such indices, one must verify if the view USER_SDO_GEOM_METADATA contains the required metadata. This can be verified with this query: select * from USER_SDO_GEOM_METADATA where table_name in (‘EDGE’,’BLOCK_GROUPS’); If that returns two rows, you are fine to create the index. If not, such content must be created by:
    Insert into USER_SDO_GEOM_METADATA (TABLE_NAME,COLUMN_NAME,DIMINFO,SRID) values (‘BLOCK_GROUPS’,’GEOMETRY’,MDSYS.SDO_DIM_ARRAY(MDSYS.SDO_DIM_ELEMENT(‘X’,-180,180,0.5),MDSYS.SDO_DIM_ELEMENT(‘X’,-90,90,0.5)),’8307′);
    Insert into USER_SDO_GEOM_METADATA (TABLE_NAME,COLUMN_NAME,DIMINFO,SRID) values (‘EDGE’,’GEOMETRY_PCODE’,MDSYS.SDO_DIM_ARRAY(MDSYS.SDO_DIM_ELEMENT(‘LONG’,-180,180,0.005),MDSYS.SDO_DIM_ELEMENT(‘LAT’,-90,90,0.005)),’8307′);
    After that the indices can be created by (example):
    CREATE INDEX edge_idx ON obiee_navteq.edge(geometry_pcode) INDEXTYPE IS mdsys.spatial_index;

    I also assume you have created the necessary objects in the presentation layer (screenshot from OBIEE Administration tool.
    Untitled

    One then starts creating the layers. One layer for the filiaal_num with its corresponding point geographical object and one layer for the code with its corresponding polygon geographical object.
    We use mapbuilder to create these layers. The layers are indicated as geometry themes in mapbuilder.
    Mapbuilder is a jar file that can be downloaded on your client machine. One must first create a connection to OBIEE. I used a custom string to do so (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST =192.168.2.36)(PORT =1521)) ) (CONNECT_DATA = (SERVICE_NAME =pdborcl))).

    Right click on geometry theme opens the possibility to create a new theme. You see some base tables. This list corresponds to the entries in the USER_SDO_GEOM_METADATA view. As EDGE and BLOCK_GROUPS are entered in that view, we must recognize them. One must create a geometry theme by clicking on a table. Right click opens the possibility to create a geometry theme. I created two geographical themes: themSIM1 for BLOCK_GROUPS and themeSIM2 for EDGE. I understand that under “Advanced”, we must indicate the identifier that will be used to link the OBIEE data as shown in the presentation layer to the geographical theme. In total I have:
    For themeSIM1 (on Block_Groups) ;
    Rendering: Color = CB_SEQ4_Orange_1
    Labelling: column = Gemeente
    Advanced; Info Column = Code
    For themeSIM2 (on EDGE)
    Rendering: Color=C.RED
    Labelling:column = Straatnaam
    Advanced:Info_Column = Filiaal_Num

    The layers are now created, time to position them on a predefined map.
    Open in the BI Analytics environment in Administration “Manage Map Data”. It will be opened with something like https://archief.van-maanen.com/analytics/saw.dll?ManageMapData.
    Import the layers (themeSIM1 and themeSIM2).
    Then edit the layers and create the link between the presentation layer and the geographical themes.
    For themeSIM1:
    Layer key = code
    Geometry Type = Polygon
    BI Key Columns = Subject Area Tom; BI key = code
    For themeSIM1:
    Layer key = code
    Geometry Type = Polygon
    BI Key Columns = Subject Area Tom; BI key = code
    Layer Key = Filiaal_num
    Geometry Type = Point
    BI Key Columns = Subject Area Tom; BI key = Filiaal_Num

    In Background Maps, import a background map. Let us take Bing, which is a predefined map.
    Then, add the two layers within that background map.
    Indicate on which zoomlevels the information must be made visible.

    Click ok.

    Did it work?
    Yes: it did (see below:)
    Untitled2

    However, note that labels nor the colours that we have chosen are shown in the map. This can only be shown if we return to map builder.
    We left off in map builder when the geographical themes were created. We now create a base map from them in map builder.
    Create a base map in map builder. As we work in the Netherlands, we must take 10 000 000 as minimum scale for themeSIM1 and a much lower figure (say 250000) for themeSIM2.
    Then create a so-called tile in either mapviewer or mapbuilder.
    Bring it online in mapviewer.
    Then, switch back back to manage map data in the administration console in BI Analytics. Import the tile that has been created. Click on edit to verify that both geometric layers are included.
    Did it work?
    Yes: it did (see below:)
    Untitled3

  • How to find a file on Linux

    There are zillions of small little Linux commands that make life easy. Those tiny little commands may save you hours of time and tons of frustration. Wheneever I look as the terminal of one of my colleagues, I discover yet another trick that they use to make life easy. May I present a little command from my side:

    find / -name post*.* 2>/dev/null
    

    This tiny little command help you to find a file. It starts with the command find. Its first parameter is the root from where to start. If you have nu clue where to look “/” might be a good idea as it is the root of the file system. Then we have parameter -name post*.*. This indicates that we use a name to fin d file, followed by the name. Wild card characters may be used such as the *. In this case, we are looking for a file that starts with post. Then “2>/dev/null” indicates that error messages are ignored. Otherwise, every map that provides no access generates an error message which precludes rapid analysis of the results.

  • Dropping a table in Oracle

    To drop a table is straightforward in Oracle. One might simply issue a drop table statement. Let us assume we have table HH. When “drop table HH” is fired, the table is removed. However, an error is returned if the stable doesn’t exist. Again: if table HH doesn’t exist and a SQL “drop table HH” is fired, an error is returned: .ORA-00942 is generated. In itsself, this is understable as a non-existent table is attempted to drop. Understably, such error is generated to warn us that something weird happened. In other DMBS, one might use use a statement like “drop if exists table HH”. However, Oracle doesn’t provide us with this facility.
    In Oracle, one needs to write a small PL SQL procedure to circumvent the error. The code reads like:

    create or replace PROCEDURE DROP_TABLE(NAAM IN STRING) AS
    BEGIN
       EXECUTE IMMEDIATE 'DROP TABLE '||NAAM;
    EXCEPTION
       WHEN OTHERS THEN
          IF SQLCODE != -942 THEN
             RAISE;
          END IF;
    END DROP_TABLE;
    /
    

    This procedure can be called by “EXEC DROP_TABLE(‘HH’);”.
    The procedure calls the statement DROP TABLE HH. Howver if HH doesn’t exist, an error is raised. Howver such error is handled as an exception that doesn’t lead to an error generated by the procedure.

  • R – the shortest name possible

    For some reason, short names are popular as computer languages. Think of “C”. Another example is “R”.
    R reminds me a bit of Matlab; it is an easy to learn language with immense statistical possibilities. It is compared to nowadays giants like SAS.
    The advantage of R is that it is widely accepted by the academic community. This community contributes to R by adding new components to it. As R is open source, such additions can then be integrated into the R programme.

    To test R, I tested how much time it took me to install R, set up a connection to Oracle and retrieve data from it.
    (more…)

  • Hive, SQL on Hadoop

    In a previous post, I discussed the difficulty to use Hadoop with its Big Data structure. One must write two different Java programmes. One programme is a so-called mapping programme; another is the reduce programme. (more…)