Talend For Data Integration Guide

Transcription

Talend for Data Integration guideTable of ContentsIntroduction.2About the author.2Download, install and run.2The first project.3Set up a new project.3Create a new Job.4Execute the job.7Components, data flow and metadata.8Most common components.11Repository.12Working with SQL databases.14Database installation.14Database connection.15Example 1: Create a new table.17Example 2: Subjobs.22Example 3: Clone and synchronize a table.27Example 4: SQL queries and record deletion.29Example 5: Join and map.31Using other SQL and No-SQL database vendors.34Context variables.35Context groups.38Database connection parameters.40Deployment.42Sub Jobs.44FAQ.45Page 1 - www.robertomarchetto.com

IntroductionThis is a short guide about Talend Open Studio for Data Integration, one of themost popular and comprehensive tool for Data Integration. This guide can befreely downloaded and shared under the conditions of the Creative CommonLicense Data Integration involves a collection of tools and techniques which aim toprocess information stored in different sources to create a coherent, clean,unified view of data.Talend provides specific tools for data integration and data quality, avoiding thecomplicated development of custom procedures with traditional programminglanguages.Talend is Open Source and freely downloadable, however the proceduresdeveloped by the final user do not need to be redistributed under an OpenSource license.About the authorRoberto Marchetto is a certified independent consultant with years of expertisein Data Integration projects. He worked as a Java / Talend software engineer forimportant London based companies like Google, Imperial College, Pubblicis. Healso provides coaching and tutoring. For more information seewww.robertomarchetto.com.Download, install and runTalend Open Studio for Data Integration is freely available and can bedownloaded at http://www.talend.com. The version used in this guide is theFree Open Source version 5.5, however the same concepts apply to morerecent versions and to the Enterprise edition as well.Talend Open Studio is developed in the Java programming language and runson Windows, Mac and Linux. The only prerequisite is the Oracle Java JRE or JDK,freely downloadable from the Oracle web site (both the Java SE and Java EEversions are fine, Java SE JRE is the minimum version required to run Talend).Once Talend and Java JRE or JDK has been installed installed, Talend can beexecuted by one of the following files, depending on the platform: In WindowsTOS DI-win-x86 64.exe (64 bit) or TOS DI-win32-x86.exe (32 bit) In Mac and LinuxTOS DI-linux-gtk-x86 64 (64 bit) or TOS DI-linux-gtk-x86 (32 bit)Page 2 - www.robertomarchetto.com

The first projectSet up a new projectDuring the first execution Talend Open Studio prompts a form as in Illustration1 and afterwards a form as in Illustration 2. Basically Talend requires the user toopen an existing project or to create a new one.Illustration 1: Talend first execution formPress “Create.” and in the new form set Project Name to, for example,“TalendTutorial” and then click Finish. In the following form just select the“TalendTutorial” project and press Open.Illustration 2: Project openingTalend Open Studio includes a useful collection of examples, which can beimported by clicking “Demo Project.”. In this guide we will use a new emptyproject however the user can import and explore the demo project as apractical reference.While opening the project Talend shows a registration form. Even if this step isPage 3 - www.robertomarchetto.com

optional the user registration gives access to the Talend support forum andTalend exchange for new components.The loading of the application takes few seconds, if a Welcome page appearsthen click on the cross icon near the Welcome tab on the top, this will close thepage and show the designer.Create a new JobTalend data integration projects are organised in Jobs. To create a new Job rightclick the Job Designs repository and press Create job, as in Illustration 3.Illustration 3: Creation of a new jobOn the form that will appear fill the Name field with “FirstTalendJob” and pressFinish. All the remaining fields are optional. In a real world project however it isuseful to give more information which will be used by Talend to improve theproject documentation.Now we are ready to develop our first job. For example we can generate somerows of data and display the result. Press the left mouse button on thetRowGenerator component which can be found in the Misc category of thePalette, as in Illustration 4.Page 4 - www.robertomarchetto.com

Illustration 4: tRowGenerator component in the PaletteNow drag and drop it in the workspace or just click an empty area of theworkspace, the result should be similar to Illustration 5.Illustration 5: First job with a tRowGeneratorThe new component needs to be configured, just double click on it and theeditor in Illustration 6 will appear.Page 5 - www.robertomarchetto.com

Illustration 6: tRowGenerator configurationtRowGenerator generates a user defined collection of rows. Lets suppose thatwe want to generate 100 rows of data with a sequence from 1 to 100. Justpress the Add ( ) button and fill the first row as follow: Column: id Type: Integer Function: Numeric.sequence Number of Rows for RowGenerator: 100The result should be similar to Illustration 7 and to make sure the output iscorrect press the Preview button in the Preview tab.Page 6 - www.robertomarchetto.com

Illustration 7: tRowGenerator with a numeric sequencePress Ok and we can proceed with the next step. This component will generate100 rows of data with a sequence from 1 to 100. We should do somethingmeaningful with the generated data, for example display the result on console.In the Palette click on the tLogRow component of the category Logs & Errorsand drop it in the workspace. Then right click on the dropped tRowGeneratorcomponent and select Row Main and click on tLogRow 1 as destination of thearrow.Illustration 8: Link two componentsA red arrow linking the two components should appear. Our first exercise iscompleted! In the next chapter we will run the job and display the result.Execute the jobTo run the job press the Run button on the Run tab, the result should be similarPage 7 - www.robertomarchetto.com

to Illustration 9. The black text which appears is the output that this jobproduces in console, this is because we are using a tLogRow component,otherwise the job would not produce any output in console.Illustration 9: Job executionComponents, data flow and metadataTo use Talend Open Studio effectively is it necessary to know three mainconcepts: Components, data flow and metadata.Components are a simple yet powerful way to perform tasks. We can findcomponents for any operation, for example row generator, data baseconnection, file system tools or even network utilities. To configure acomponent we just click on its icon and select the Component tab, as inPage 8 - www.robertomarchetto.com

Illustration 10.Illustration 10: The Component tabIn the designer components are linked each other with an arrow, this meansthat the Data flow runs from a component to the next linked component row byrow. In our example the tRowGrenerator component generates 100 rows andsends them to the tLogRow component, which function is to display the result.The operation of the linked components is repeated for each row of data, in ourcase each record is logged on the console.We can also use other types of links, for example conditional links whichexecute the linked components only after some conditions are true. This will beexplained in the following chapters.The last important concept is meta data, which means how the data flow isstructured. It is important to remember that a component requires thedefinition of the schema while processing the data flow. The data structure inour fist example is a single column named id of type integer. If we click on theComponent tab of tRowGenerator and then click on Edit schema we can see itsdata structure.Page 9 - www.robertomarchetto.com

Illustration 11: Component schemaThe meta data definition is important to make sure that the flow content isalways coherent and to avoid errors which would be hard to recognise.The linked components must have compatible meta data, otherwise Talend willproduce an error. When we change the meta data of any component we canpress the “Sync columns” button of the linked components and automaticallyimport the new data structure.Illustration 12: Sync column buttonPage 10 - www.robertomarchetto.com

Most common componentsNow that we have an overview of the Talend basics we can take a look at howmany components are already available. To search for a component by namewe can use the search box in the Palette and press the search button.Illustration 13: Palette searchSome of the most commonly used components are listed in the following table.Repository entsA comprehensive collection of specificrelational databases componentsData QualitytUniqRowRemoves duplicated rowsESB ResttRESTClientREST web services clientESB Web Services tESBConsumerWeb Services clientFileSeveralcomponentsCollection of file and directory relatedoperationsInternetSeveralcomponentsSeveral components which allow toconnect to several network protocolsCustom CodetJavaRowExecutes a custom Java code for eachrowtLibraryLoadLoad an external Java library whichcan be used in other components, forexample tJavaRowtLogRowPrints the content of a flow to consoletWarnSends a warning, error or infomessage which is captured bytLogCatchertLogCatcherCaptures warning, error and infomessages dispatched by tWarntDieInterrupts the current job executionNoteShows a text note in the workspaceLogs & ErrorsMisctBufferedInput / Save / reads the flow in a temporarytBufferedOutput buffer, useful in some complexworkflowsPage 11 - www.robertomarchetto.com

erates a sequence of fixed rows,useful for example to providepredefined input for a linkedcomponenttRowGeneratorGenerates a dynamic sequence ofrowstReplicateReplicates a flow which can beredirected to two or more componentsat the same timetUniteMerges two or more flows in a singleflowtAggregateRowAggregates a flow by one or morecolumns, similar to a GROUP BY SQLclausetFilterRowFilters a flowtJoinMerges two flows providing look upfunctionalitiestMapOne of the most used multi purposecomponent which allow to map, joinand process flowstReplaceReplaces values in a flow, for exampleY/N with Yes/No valuestSortRowSorts a flow by one or more columnvaluestXMLMapXML version of the tMap componentwhich produces xml compatible outputtRunJobExecutes a subjobtSystemExecutes a console system commandSeveralcomponentsXML manipulation related componentsThe list of components is long, these are just some of the most used ones. Theuser can also download new components from Talend Exchange or, with therequired Java expertise, create new ones.RepositoryBig projects can lead to maintainability issues, this is why Talend provides a setof repositories which allow to share reusable configurations among thecomponents. The repository is shown in Illustration 14 and severalstraightforward directories are available.Page 12 - www.robertomarchetto.com

Illustration 14: Repository tab Business ModelProvides a diagramming tool useful for design and documentation. Job DesignsContains the jobs. The user can also create sub folders by clicking on theJob Designs item and selecting “Create folder” ContextsUser defined parameters can be declared in this repository and sharedamong the jobs. For example a user can create a set of development andproduction parameters and choose which set to use at a specificmoment. CodePage 13 - www.robertomarchetto.com

Contains custom Java routines. Talend is based on Java and the user cancreate custom Java code to perform advanced tasks. SQL TemplatesA deeper level of control over the SQL statements for a specific databasecan be achieved by editing the items in this directory. MetadataThe metadata repository is an important directory in which the userdefines the data connections and schema. A set of useful tools andwizards helps the user during the data mapping. DocumentationExternal documentation files can be saved here. Recycle binThe items once cancelled from the repository are not erased from thedisk but are moved in this recycle bin. This feature is similar to therecycle bin of the operating system.Working with SQL databasesEnterprise data is usually stored in databases, either relational or nonrelational. A common Data Integration task involves the extraction of data froma database, then the data will be transformed and finally loaded in anotherrelational database. This recurring Data Integration workflow is a typicalexample of ETL (Extraction Transformation and Loading).In this chapter we will work with a MySQL database. Talend provides severalconnector for different SQL databases vendors, the choice of MySQL is just forits simplicity and popularity.Database installationThe following examples require a working MySQL database server. MySQL isfreely downloadable at www.mysql.com. For further information on how toinstall and use MySQL the user can find several tutorials and documentation inInternet.Once MySQL has been installed, we need to create a new database, forexample “talend examples”. The simplest way is to open the command promptand digit the following command:mysql -u root -h localhost -pAnd enter the MySQL password when required:Enter password: digit MySQL password Once the connection has been established run the following command:mysql create database talend example;If everything is fine now we have an empty “talend example” database inPage 14 - www.robertomarchetto.com

MySQL.Database connectionThe Repository tab provides an easy method to establish a databaseconnection. Right click on DB connections in the Metadata item of theRepository tab, select Create connection and in the new form digit“LocalMySQL” as connection name.Press Next and fill the form with the following parameters: Db version: MySQL5 (or MySQL4 if using the version 4 of MySQL) Login: The MySQL user name, for example root password: The MySQL user password Server: The host of the server, for example localhost Port: 3306 is the default value DataBase: The previously created database talend example Additional parameters: Leave as defaultPage 15 - www.robertomarchetto.com

Illustration 15: Set up of a SQL connectionCheck the connection with the button Check, if everything works a successfulmessage should appear. Now press Finish and the new connection will be listedin the Repository as in Illustration 16.Page 16 - www.robertomarchetto.com

Illustration 16: The new connection in theRepository tabExample 1: Create a new tableIn this example we will use the Talend database components to create twoMySQL tables and insert some data.Create a new project named for example “SQLDataInsertion” (right click on JobDesigns Create Job). Now drop a tFixedFlowInput component and in theComponent tab click the Edit schema button.Fill the Schema with the values of the following table (also see Illustration IntegerPage 17 - www.robertomarchetto.com

Illustration 17: tFixedFlowInput schema definitionOn the Component tab select “Use Inline Table” and fill the table with thefollowing values (as in Illustration �1“002”“cake”10“003”“coffee”3Page 18 - www.robertomarchetto.com

Illustration 18: tFixedFlowInput data definitionThis component generates a table with 3 rows. Now click the LocalMySQLconnection from Metadata Db connections of the repository (LocalMySQL isthe MySQL connection previously created) and drop it on an empty Job areaand select tMysqlOutput as component.Page 19 - www.robertomarchetto.com

Illustration 19: Database connection drag and dropA new tMysqlOutput component should appear in the job workspace. Now rightclick on the tFixedFlowInput component in the workspace, select Row Mainand connect the flow to the tMysqlOutput component.The connection parameters are already copied from the repository to the newtMysqlOutput. As you can see in Illustration 20 the Property Type is also set toRepository and it is using the LocalMySQL connection.Page 20 - www.robertomarchetto.com

Illustration 20: tMysqlOutput customizationThe user can set specific parameters for the component instead of heRepository one, this can be achieved by setting the Property Type to Built-in.In addition the simple action of connecting the two components populates thetMysqlOutput schema, as you can see by clicking the Edit schema button.Illustration 21: The schema of the components is matchingOnce again it is important to maintain a compatible schema between twolinked components. The input schema of a component should always match theoutput schema of the following component, otherwise Talend will raise an error.The Sync columns button of the tMysqlOutput automatically updates thePage 21 - www.robertomarchetto.com

schema in case of changes.Finally we need to set the following values in the tMysqlOutput Component tab: Table: “inventory” Action on table: “Create if does not exist” Action on data: “Insert or update”The “Create if does not exist” action is rarely used in real World projects,usually the database tables are already created, however in our example thedatabase is empty and we are using Talend to create the new tables.With the Action “Insert or update” Talend tries to insert the record and, if it isalready present (by checking the key values), it will try to update the record.To run the job just open the Run tab and press Run. In case of errors check theconnection and make sure that the talend example database is created andthe user can create tables. In the Illustration 22 there is the output of a typicalconnection error:Illustration 22: MySQL connection errorIf this does not fix the error make sure that the Length field of the Stringcolumns of the tMysqlOutput schema (press Edit schema) is set, otherwiseTalend will not be able to create a MySQL table. Also try to change the Actionon table to “Drop table if exists and create”, this will delete any previous table.If everything is fine the new table will be created and populated with the dataof the tFixedFlowInput component.Example 2: SubjobsIn this example we will extend the previous job with a sub job which creates anPage 22 - www.robertomarchetto.com

“inventory” table. Keep the SQLDataInsertion project open and select both thetFixedFlowInput and tMysqlOutptut components (click on them with the Ctrlbutton pressed). Then right click on one of the two components, select Copyand then paste in a empty area of the workspace.Illustration 23: Copy of a workflowThe two “LocalMySQL” labels can be confusing, however we can rename thesecomponents in a more meaningful way. Click on the first LocalMySQLcomponent, select the View section of the Component tab and update the field“Label format” to “create inventory table” as in Illustration 24. Also set thesecond LocalMySQL component label to “create products table”.Page 23 - www.robertomarchetto.com

Illustration 24: Setting component labelNow update the tFixedFlowInput 2 component with the following schema (justpress on Edit schema of the component tab and remove the “quantity” columnas in Illustration 60descriptionFalseFalseString200Page 24 - www.robertomarchetto.com

Illustration 25: tFixedFlowInput schemaAfter pressing Ok a dialog will appear to propagate the changes to the nextcomponent. Press Yes, this will synchronize the tMysqlOutput 2 component.Now update the Inline Table of the tFixedFlowInput row with the followingvalues:CodeDescription“001”“belgian ack coffee”Illustration 26: tFixedFlowInput dataClick on the tMysqlOutput 2 component and set the Table property to“products”. Also make sure that the Action on table is set to “Create table ifdoes not exist”.Page 25 - www.robertomarchetto.com

Illustration 27: tMysqlOutput settingsOnce again the action “Create table if does not exist” is rarely used in realworld projects but it necessary in these examples.With this configuration tFixedFlowInput 1 and tFixedFlowInput 2 will run inparallel and create two separated tables “inventory” and “products”.If we want to execute the tFixedFlowInput 2 component only after thecompletionoftFixedFlowInput 1weneedtorightclickthe“create inventory table” component and select Trigger On Component Okand link the line to the tFixedFlowInput 2. The result should be similar toIllustration 28.Illustration 28: OnComponentOk triggerBasically we have a project with two processes linked in sequence, the firstcreates a inventory table and the second a products table. The second processstarts only if the first process terminates successfully.Now run the job and in case of errors check the connection, the schema andthe table names. If the table schema was wrong try to change the Action onPage 26 - www.robertomarchetto.com

table to “Drop table if exists and create”, this will delete any previous table.If the error can not be fixed here is the full SQL script that can be used tocreate and populate both tables directly from command line.DROP TABLE IF EXISTS inventory;CREATE TABLE inventory (code varchar(60) NOT NULL DEFAULT '',description varchar(200) DEFAULT NULL,quantity int(11) DEFAULT NULL,PRIMARY KEY (code));INSERT INTO inventory VALUES ffee',3);DROP TABLE IF EXISTS products;CREATE TABLE products (code varchar(60) NOT NULL DEFAULT '',description varchar(200) DEFAULT NULL,PRIMARY KEY (code));INSERT INTO products VALUES ('001','belgian chocolate'),('002','cheescake'),('003','black coffee');Example 3: Clone and synchronize a tableIn this example we will create and synchronize a copy of the products table.First create a new job called SQLDataUpdate. Now right click on theLocalMySQL connection in the Repository and and select Retrieve schema.Illustration 29: Database tables schema import utilityPress Next and in the following form select both inventory and products tablePage 27 - www.robertomarchetto.com

as in Illustration 30.Illustration 30: Database tables selectionPress Next again and then Finish, the imported schema will appear in theMedatada repository.Illustration 31: Table schema imported in therepositoryDrag the products table in the empty workspace and select tMysqlInput. ThetMysqlInput component will load the content of the whole table and send it tothe flow.From the Databases MySQL palette drag a tMysqlOutput component in theworkspace, then link the tMysqlInput component previously created with thetMysqlOutput component (right click on tMysqlInput, select Row Main anddrag the link to tMysqlOutput).Now select the tMysqlOutput and fill the Component tab as follows: Property Type: Repository, click on the “.” and select LocalMySQL asvaluePage 28 - www.robertomarchetto.com

Table: “products copy” Action on table: Create if not exists Action on data: Insert or updateTo check if everything works drag a final tLogRow component linked to thetMysqlOutput component (right on tMysqOutput click, select Row Main). Theresult should be similar to Illustration 32.Illustration 32: Data tables synchronizationNow click Run in the Run tab and a new table named products copy will beupdated with the content of the products table.It is important to remember that new and updated data is always propagatedand synchronized however deleted records from the products table will not bedeleted in the products copy table. To remove deleted records we need toimplement a separated flow, as in the following example.Example 4: SQL queries and record deletionBasically to delete records we use a tMysqlOutput component with Action ondata set to “Delete” and an input flow which contains the keys to be deleted.We can implement several approaches to extract the records deleted from themaster table. Unfortunately there is not just a component or flag to do that, weneed to create a separated flow.Page 29 - www.robertomarchetto.com

In the previous SQLDataSynchronization job right click on the MySQLconnection from the Db connections Repository and select Edit Queries. Fill theblank query area with the following statement:select c.codefrom products copy as cwhere c.code not in (select p.code from products as p)In a real world project it is better to use a separated table which logs thedeleted records rather than using a query like this, which scans the entire twotables.The running man icon on the top of the query tab executes the query and it isuseful to check if the query works. The output should be empty as we do nothave records in the products category table which are not present in theproducts copy table. However if we delete some records in the products tablethe result will appear on the Result tab.Illustration 33: SQL query for deleted recordsPress Ok and digit “products deleted records” as query name when required.The new SQL query appears in the Metadata repository.Now drag the products deleted records in the workspace and selecttMysqlnput as component. Also drag the products copy table from therepository to the workspace and select tMysqlOutput as component.Right click on the products deleted records component, select Row Main andlink the products copy component. Also right click on the tLogRow component,select Trigger On Component Ok and link the products deleted recordsPage 30 - www.robertomarchetto.com

component.Finally set the Action on data value of the products copy component to Delete,the result should be similar to Illustration 34.Illustration 34: Job for records synchronization and deletionPress Run on the Run tab to execute the job. If we delete some records fromthe products table the same records will be deleted from the products copytable as well. Notice that to perform a record deletion just the key column“code” is required.Example 5: Join and mapIn this example we will update the description column of the inventory tablewith the values of products table.In a new job “SQLDataJoinAndMap” drag the following components in theworkspace (see Illustration 35):– the inventory table from the Metadata repository and select tMysqlInputas component– the products table from the repository and select tMysqlInput ascomponent– another inventory table from the repository but this time selecting atMysqlOutptut component– A tMap component from the Processing PaletteRight click on the inventory tMysqlInput component, select Row Main and linkit to the tMap, then right click on the products tMysqlInput component, selectPage 31 - www.robertomarchetto.com

Row Main and link it to the tMap. It is important to link the inventorycomponent first and the products component afterwards.Now right click on the tMap component and select Row New output (Main),link it to the inventory tMysqlOutput component and when required digit“inventory updates” as output name. The result should be similar to Il

Free Open Source version 5.5, however the same concepts apply to more . user can also download new components from Talend Exchange or, with the required Java expertise, create new ones. Repository Big projects can lead t