Category: nice to know

  • Reading and writing in Java

    Reading and writing from and to files is not easy in Java. This can already be seen if one simply googles on “Java Filereader problem”. This generated 477000 hits. Apparently, reading (and writing) is not trivial. I wrote a small program that is able to read a file and copy its contents to another file. It is tested on both Windows and Linux and it seems to work.

    A minor note on using the programme on Windows. To circumvent problems with the backslash, it is preceded by another backslash. Hence the filename is written as “D:\\bla bla”, where one might expect a “D:\bla bla”. The cause is that a backslash is interpreted as an exception character. (and not as a directory seperator. Hence the necessity to use the double backslash “\\” instead of a single one. Then the EOF character. In Windows, this EOF character can be enforced by a “\r\n”, whereas such EOF character is “\n” when it comes down to Linux.

    I use a buffered read to hadle buffers. This enables this programme to be used with large input files.

    import java.io.*;
     
    public class CopyCharacters {
        public static void main(String[] args) throws IOException {
     
        	BufferedReader bufferedReader = null;
            FileWriter outputStream = null;
            String filename = "D:\\Users\\tmaanen\\prive\\java\\invoer.txt";
     
            try {
                bufferedReader = new BufferedReader(new FileReader(filename));
                File file = new File("D:\\Users\\tmaanen\\prive\\java\\characteroutput.txt");
                file.createNewFile();
                outputStream = new FileWriter(file, true);    
                int c;
                while ((c = bufferedReader.read()) != -1) 
                     {
                        outputStream.write(c);
                      }
                }
                catch (Exception e)
                {
                  System.err.format("Exception occurred trying to read '%s'.", filename);
                  e.printStackTrace();
                }
             finally {
                if (bufferedReader != null) 
                {
                	bufferedReader.close();
                }
                if (outputStream != null) 
                {
                	outputStream.write("\r\n");
                	outputStream.close();
                }
                    }
        }
    }
    
  • Another set of keys and values

    Another example on how mapper and reducers are used in a Hadoop context is given below. This programme is created as three classes. One class is an overall class that calls two other classes: a mapper class and a reducer.
    The mapper classer reads a file and creates a series of words. In the first reducer programme, the series is grouped where the frequency of each word is calculated. In the second reducer programme the results are combined. The programme reads as:

    import java.io.IOException;
    import java.util.*;
    
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.conf.*;
    import org.apache.hadoop.io.*;
    import org.apache.hadoop.mapred.*;
    import org.apache.hadoop.util.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.util.Date;
    
    
    @SuppressWarnings("unused")
    public class WordCount {
    
       public static class Map extends MapReduceBase implements Mapper {
         private final static IntWritable one = new IntWritable(1);
         private Text word = new Text();
    
         public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException {
           String line = value.toString();
           StringTokenizer tokenizer = new StringTokenizer(line);
           File file = new File("/home/hduser/example-mapper.txt");
           if (!file.exists()) {
           	file.createNewFile();
           };
           FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
           BufferedWriter output1 = new BufferedWriter(fw);
           Date date = new Date();
           while (tokenizer.hasMoreTokens()) {
             word.set(tokenizer.nextToken());
             output.collect(word, one);
             output1.append("mappert is jaar " + date.toString() +">"+ word + "    " + one + "\n");
           };
           output1.close();
         }
       }
    
       public static class Reduce extends MapReduceBase implements Reducer {
         public void reduce(Text key, Iterator values, OutputCollector output, Reporter reporter) throws IOException {
       	   File file = new File("/home/hduser/example-reducer.txt");
           if (!file.exists()) {
              	file.createNewFile();
              };
           FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
           BufferedWriter output1 = new BufferedWriter(fw);
           int sum = 0;
           while (values.hasNext()) {
             sum += values.next().get();
             output1.write("mappert is gelezen waarde " + " key "+ key + " sum " + sum + "\n");
           }
           output.collect(key, new IntWritable(sum));
           output1.close();
         }
       }
    
       public static void main(String[] args) throws Exception {
         JobConf conf = new JobConf(WordCount.class);
         conf.setJobName("wordcount");
    
         conf.setOutputKeyClass(Text.class);
         conf.setOutputValueClass(IntWritable.class);
    
         conf.setMapperClass(Map.class);
         conf.setCombinerClass(Reduce.class);
         conf.setReducerClass(Reduce.class);
    
         conf.setInputFormat(TextInputFormat.class);
         conf.setOutputFormat(TextOutputFormat.class);
    
         FileInputFormat.setInputPaths(conf, new Path(args[0]));
         FileOutputFormat.setOutputPath(conf, new Path(args[1]));
    
         JobClient.runJob(conf);
       }
    }
    

    The input file looks like:

    dit is van tom tom
    

    In the mapper, this text is split into seperate words:

    mappert is jaar Tue Jun 16 05:31:22 PDT 2015>dit    1
    mappert is jaar Tue Jun 16 05:31:22 PDT 2015>is    1
    mappert is jaar Tue Jun 16 05:31:22 PDT 2015>van    1
    mappert is jaar Tue Jun 16 05:31:22 PDT 2015>tom    1
    mappert is jaar Tue Jun 16 05:31:22 PDT 2015>tom    1
    

    The keys are the seperate words (like “dit”, “is” etc.). The value is always one.
    In the first reducer programme, the frequency is calculated:

    mappert is gelezen waarde  key dit sum 1
    mappert is gelezen waarde  key is sum 1
    mappert is gelezen waarde  key tom sum 1
    mappert is gelezen waarde  key tom sum 2
    mappert is gelezen waarde  key van sum 1
    

    One sees the calculation when the key “tom” is processed. In the first round the value is 1, which is the original value. In the second round, it is detected that “tom” was detected before and the value is incremented with “1”.
    In the second reducer programme, the results are merged:

    mappert is gelezen waarde  key dit sum 1
    mappert is gelezen waarde  key is sum 1
    mappert is gelezen waarde  key tom sum 2
    mappert is gelezen waarde  key van sum 1
    

    This can be found in the output that reads as:

    hduser@ubuntu:~$ /usr/local/hadoop/bin/hadoop dfs -cat /user/output84/part-00000DEPRECATED: Use of this script to execute hdfs command is deprecated.
    Instead use the hdfs command for it.
    
    15/06/16 06:21:09 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    dit	1
    is	1
    tom	2
    van	1
    
  • Hive – connecting from SQL Developer

    In my impression, the big development that takes place now in the world of Big Data is the creation of connectors. Such connectors enable us to continue using standard tools (R for example) with the data being stored in Hadoop. I am very much impressed with Hive. Hive allows us to access data being stored in Hadoop while we use a standard SQL tool.
    (more…)

  • Use Case, Business Events and Time Events

    In a previous post, I showed the context diagramme. I then continued by saying that each of the arrows that flow to and fro the bubble in the middle can be translated as use cases.

    But one may take a slightly different view: each of these arrows are either business events or time events. A business event is then understood as an action from outside the system that invokes a flow of information (=an arrow to/fro the bubble in the context diagramme). Likewise a time event is understood as a time event that invokes an information stream to/fro the bubble.

    Hence in a business event or a time event, one explicitly mentions the reason, why the event starts.

    Suppose, the time vent is (e.g. a monthly moment ) whereby data are sent to the reporting enevironment.

    One has:

    1. Story, begin condition. The time indicates that data must be sent to the reporting environment
      1. step1: Collect data in data warehouse.
      2. step2: System sends data to Reporting Environment.
      3. step3: Reporting System stores the data in its own environment.
      4. end condition. Reporting System contains the data for reporting environment.

    One sees: it a slightly different approach from a use case. The reason, why the event starts is better indicated.

    Why is it important to stress the reason for starting the business event/ time event. Because it shows the boundaries of the system. One is forced to think of what starts a certain flow of information. Is it time that starts a flow of information from the system to the reporting environment. Or is it the availability of data that can be sent to the reporting environment? Or is it a signal of the end user to have the data? Or.. etc..

    When this done, one gets a:

    • clear list of the actors (a user who requires a report, a system that delivers data etc)
    • a clear list of actions that must be covered by the work process (store data, provide reports etc).

     

  • Access odbc

    Just a little note.
    I discovered that one may access the 32 bit ODBC drivers on a 64 bit platform via: C:\Windows\SysWOW64\odbcad32.exe and the 64 bit ODBC drivers via: C:\Windows\System32\odbcad32.exe

    This may be handy if one must access a 32 bit application (like Access 2007) via ODBC in a 64 bit environment. The standard ODBC application doesn’t allow you to directly access the 32 bit ODBC connections on a 64 bit platform. It is bit awkward and one could circumvent this issue via a direct call to the 32 ODBC driver environment.

    One should always use the appropriate version of the ODBC Administrator tool. If you build and then run an application as a 32-bit application on a 64-bit operating system, you must create the ODBC data source by using the ODBC Administrator tool in %windir%\SysWOW64\odbcad32.exe. The 64 bit ODBC drivers can be accessed directly using C:\Windows\System32\odbcad32.exe. To indicate the type of DSN, you can add “_32” to the 32-bit user DSNs and “_64” to the 64-bit user DSNs.

    The 64-bit ODBC Administrator tool can also be invoked from Control Panel to manage user DSNs and system DSNs that are used by 64-bit processes. On a 64-bit operating system, the 32-bit ODBC Administrator tool is used for Windows on Windows 64 (WOW64) processes. You must directly invoke the 32-bit ODBC Administrator tool from the SysWoW64 folder. You can use the 32-bit ODBC Administrator tool to manage user DSNs and system DSNs that are used by WOW64 processes.

    On a 32 bit system, the 64-bit drivers cannot be installed (of course). The 32 bit ODBC driver are the only drivers that can be found; they can be accessed via the Control Panel.

    So, what do we have?
    In a scheme:

    64-bit Windows 32-bit Windows
    64-bit Administrator C:\Windows\odbcad32.exe
    or
    Start -> Control Panels -> Data Sources (ODBC)
    N.A.
    32-bit Administrator C:\Windows\SysWoW64\odbcad32.exe C:\Windows\odbcad32.exe
    or
    Start -> Control Panels -> Data Sources (ODBC)

  • Teradata: what columns to choose as Primary Index?

    A major question with Teradata tables is what columns to choose when a primary index must be created.
    I understand that 4 different arguments might be used:
    1: Is the column often accessed? If it is often accessed, best usage is made of the distibution of records over the different amps.
    2: Is the column used in joins: in that case a similar argument holds. If the column is used in a join condition, usage is made of the distribution of records over the different amps.

     
    TERADATA_FALLBACK

     
    3: Is the column often updated. If a culumn is updated, the record might be re-allocated to another amp. Hence, the less updates, the better it is to have it included in a primary index.
    4: Is the cardinality high. In that case, it is possible to distribute the records over many amps, enabling Teradata to make optimal usage of the primary index capability.

  • Teradata and fall back

    I understand Teradata has a so-called fall back option. The idea is that data are stored twice; each record being stored to two different amps.

    I saw a nice picture that descibes the situation. Each record (Row 1, Row 2 etc) are linked to an amp. It is shown in below scheme as yellow boxes. A seperate copy is made of all records. The copy is shown in an orange box. The records are all linked to another amp as the original record.

    TERADATA_FALLBACK

    Having a fall back, certainly has advantages. If an amp fails, a query may use copies of the original records.

    However, there is a flipside to this. It requires:

    • more table space as copies must be stored
    • more IO time as the copies must be written to disc
    • more CPU time as he copies must be created by the system

    Hence, this option is only used for critical tables where the additional costs are justified. Moreover, this option is advised to be used at table level only. This allows to make a fine distinction between tables for whih such additional costs are warrented and other tables where additional costs are not justified.

     

  • Dynamic SQL

    I must confess I never heard of Dynamic SQL. But suddenly around me everyone started talking on Dynamic SQL. What is dynamic SQL?
    Dynamic SQL is a SQL statement that is created at runtime. Such is the definition.
    I realised that I had already created quite some dynamic SQL without realising that such construction is Dynamic SQL. As an example, I have created a data warehouse that is fed via SQL statements. A number of these statements are created at runtime only. As an example, one may think of a construction like:

    set $targettable = XX
    
    insert into $targettable
      select * from source
    

    In the example above, the SQL that is fired will be “insert into XX select * from source”. However if $targettable is set at YY, the generated SQL will be “insert into YY select * from source”.

    Hence dynamic SQL allows you to write one skeleton SQL statement that can be used in different circumstances. This allows you to write smaller scripts that are easier to maintain.

    Another situation where dynamic SQL can be used, is the handling of user input.

    Suppose one has input fields where a user may insert some data. Such data are then stored in a variable that is subsequently inserted into the database. To accomplish this, the user input is captured in a variable that can be subsequently inserted into the database. Something like:

    set $input = "data from input form"
    
    insert into targettable
      inputfield ($input)
    

    Around me, some pushback on dynamic SQL, could be heard. The main problem is that dynamic SQL might be difficult to maintain as one may not know what SQL is exactly generated. I am inclined to see that as sloppy programming. A good programmer can always capture the generated SQL and show this to the user. This could be handy when the script must be debugged.
    Another issue was that the statements that generate the SQL, can be quite difficult. This can certainly the case. I have seen scripts that were needless complicated to generate a SQL statement. However, good programming techniques should prevent this.

  • Duplicate records in teradata tables

    Teradata offers the user the choice whether of not a check is made on duplicate records. Let’s first look at some code that allows duplicate records to be inserted.
    The code below has two elements that enables duplicate records:

    1. it contains a primary index that is not unique.
    2. the table is a multiset table.
    CREATE MULTISET  TABLE SAN_D_FAAPOC_01.EMPLOYEE
    (
    EMP_NUM INTEGER NOT NULL,
    EMP_NAME CHAR(30) NOT NULL,
    DEPT_NO INTEGER NOT NULL
    )
     PRIMARY  INDEX(EMP_NUM);
     
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123456,'VINAY',101);
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123457,'SACHIN',102);
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123457,'SACHIN',102);
    
    select * from SAN_D_FAAPOC_01.EMPLOYEE;
    

    Two identical records can be inserted.
    The table is a so-called multiset table. This type table allows duplicate records. Note that this is not a Teradata standard. The standard is a table that doesn’t have duplicate records. The standard would be: “CREATE SET TABLE …”. Such a table doesn’t allow duplicate records.

    CREATE SET  TABLE SAN_D_FAAPOC_01.EMPLOYEE
    (
    EMP_NUM INTEGER NOT NULL,
    EMP_NAME CHAR(30) NOT NULL,
    DEPT_NO INTEGER NOT NULL
    )
     PRIMARY  INDEX(EMP_NUM);
     
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123456,'VINAY',101);
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123457,'SACHIN',102);
    INSERT INTO SAN_D_FAAPOC_01.EMPLOYEE VALUES (123457,'SACHIN',102);
    
    select * from SAN_D_FAAPOC_01.EMPLOYEE;
    

    This set of inserts generates an error as an attempt is made to insert two identical records. However it takes time to do such a check. Hence in a data warehouse environment, such a check with its accompanying overhead costs, might be too expensive. This explains why a multiset is preferred above the standard Teradata standard.
    Finally, in most cases the primary index is set to being unique. As the attribute that is used in the primary key in unique, the whole record is always unique as well. In that case an additional check whether the record is unique is not performed. Hence this definition will lead to unique records as the primary index is unique. Again, this uniqueness is enforced without an explicit test on the records.

    CREATE MULTISET  TABLE SAN_D_FAAPOC_01.EMPLOYEE
    (
    EMP_NUM INTEGER NOT NULL,
    EMP_NAME CHAR(30) NOT NULL,
    DEPT_NO INTEGER NOT NULL
    --,CONSTRAINT FOREIGN_EMP_DEPT FOREIGN KEY ( DEPT_NO)  REFERENCES  WITH NO CHECK OPTION DEPARTMENT(DEPT_NO)   
    )
    UNIQUE  PRIMARY  INDEX(EMP_NUM);
    

    Hence, we have two rules that may enforce unicity of records:

    • using the standard set option that prevent duplicate inserting duplicate rows
    • using a unique primary index conditions that prevents usage of duplicate values for attributes that form the primary index.

    It is easier to check the unicity of a primary index as a primary index is only defined on a part of the record. Hence the combination multiset / non unique primary index is most easy to check. In that case, nothing needs to be checked on duplicates. On the other hand, set/ non unique is most difficult to check as the whole record must be checked.

  • Different codepages in SQL Server

    It is possible in SQL Server to create columns in a table that have different codepage. This can be shown in the table below. That table has two attributes: char_unicode with a unicode codepage and char_latin that has a Latin codepage with West European characters only.

    codepage

    The char_latin cannot contain characters like ł, İ or the Φ. Such characters are not part of the Latin codepage as this codepage only contans characters that are in use in Western European languages. To store such characters, we might use the unicode codepage. Let us show how such characters are represented.

    Chars

    The column char_unicode shows the characters İ, Φ , И and the ł. In the columns char_latin, these characters are inserted in the column but (obviously) couldn’t be represented. It is interesting to see what happens: the İ is replaced by an I; a Φ is replaced by the F, the И is replaced by an unknown and ł is replaced by l.
    This allows an easy logical translation from, say İstanbul into Istanbul. This is a very interesting property as we could easy store Polish, Turkish in local characters and store them in a logical understandable way if a Latin codepage is used. Nice.