Aggregate and Index Data into Elasticsearch using Logstash, JDBC


In my previous posts here and here I showed you how to index data into Elasticsearch from a SQL DB using JDBC and Elasticsearch JDBC importer library. In the first article here I mentioned some of the shortcomings of using the importer library which I have copied here:

  • No support for ES version 5 and above
  • There is a possibility of duplicate objects in the array of nested objects. But de-duplication can be handled at the application layer.
  • There can be a possibility of delay in support for latest ES versions.

All the above shortcomings can be overcome by using Logstash and its following plugins:

Creating Elasticsearch Index

I will be using the latest ES version i.e 5.63 which can be downloaded from Elasticsearch website here. We will create an index world_v2 using the mapping available here.

$ curl -XPUT --header "Content-Type: application/json" 
    http://localhost:9200/world_v2 -d @world-index.json

or using Postman REST client as shown below:

To confirm that the index has been created successfully, open this URL http://localhost:9200/world_v2 in the browser to get something similar to as shown below:

Creating Logstash Configuration File

We should be picking the equivalent logstash version which would be 5.6.3 and it can be downloaded from here. And then we need to install the JDBC input plugin, Aggregate filter plugin and Elasticsearch output plugin using the following commands:

bin/logstash-plugin install logstash-input-jdbc
bin/logstash-plugin install logstash-filter-aggregate
bin/logstash-plugin install logstash-output-elasticsearch

We need to copy the following into the bin directory to be able to run our configuration which we will define next:

  1. Download the MySQL JDBC jar from here.
  2. Download the file containing the SQL query for fetching the data from here.

We will copy the above into Logstash’s bin directory or any directory where you will have the logstash configuration file, this is because we are referring to these two files in the configuration using their relative paths. Below is the Logstash configuration file:

input {
  jdbc {
    jdbc_connection_string => "jdbc:mysql://localhost:3306/world"
    jdbc_user => "root"
    jdbc_password => "mohamed"
    # The path to downloaded jdbc driver
    jdbc_driver_library => "mysql-connector-java-5.1.6.jar"
    jdbc_driver_class => "Java::com.mysql.jdbc.Driver"
    # The path to the file containing the query
    statement_filepath => "world-logstash.sql"
filter {
  aggregate {
    task_id => "%{code}"
    code => "
      map['code'] = event.get('code')
      map['name'] = event.get('name')
      map['continent'] = event.get('continent')
      map['region'] = event.get('region')
      map['surface_area'] = event.get('surface_area')
      map['year_of_independence'] = event.get('year_of_independence')
      map['population'] = event.get('population')
      map['life_expectancy'] = event.get('life_expectancy')
      map['government_form'] = event.get('government_form')
      map['iso_code'] = event.get('iso_code')
      map['capital'] = {
        'id' => event.get('capital_id'), 
        'name' => event.get('capital_name'),
        'district' => event.get('capital_district'),
        'population' => event.get('capital_population')
      map['cities_list'] ||= []
      map['cities'] ||= []
      if (event.get('cities_id') != nil)
        if !( map['cities_list'].include? event.get('cities_id') ) 
          map['cities_list'] << event.get('cities_id')
          map['cities'] << {
            'id' => event.get('cities_id'), 
            'name' => event.get('cities_name'),
            'district' => event.get('cities_district'),
            'population' => event.get('cities_population')
      map['languages_list'] ||= []
      map['languages'] ||= []
      if (event.get('languages_language') != nil)
        if !( map['languages_list'].include? event.get('languages_language') )
          map['languages_list'] << event.get('languages_language')
          map['languages'] << {
            'language' => event.get('languages_language'), 
            'official' => event.get('languages_official'),
            'percentage' => event.get('languages_percentage')
    push_previous_map_as_event => true
    timeout => 5
  mutate { 
    remove_field => ["cities_list", "languages_list"]
output {
  elasticsearch {
    document_id => "%{code}"
    document_type => "world"
    index => "world_v2"
    codec => "json"
    hosts => [""]

We place the configuration file in the logstash’s bin directory. We run the logstash pipeline using the following command:

$ logstash -w 1 -f world-logstash.conf

We are using 1 worker because multiple workers can break the aggregations as the aggregation happens based on the sequence of events having a common country code. We will see the following output on successful completion of the logstash pipeline:

Open the following URL http://localhost:9200/world_v2/world/IND in the browser to view the information for India indexed in Elasticsearch as shown below:

3 thoughts on “Aggregate and Index Data into Elasticsearch using Logstash, JDBC”

  1. Hi MOHAMED SANAULLA I am also facing the same problem as you mentioned in artice.My problem is I need to add array of json and it is not happening with the above logstash.conf file.Please find the below configuration file.

    input {
    jdbc {
    jdbc_driver_library => “c:\drivers\sqljdbc4”
    jdbc_driver_class => “”
    jdbc_connection_string => “jdbc:sqlserver://localhost\SAILS-DM29:1433;databasename=I9”

    jdbc_user => “sa”
    jdbc_password => “sails123”
    statement => “SELECT i9.Id AS i9FormId,
    emp.AccountId, emp.FirstName, emp.LastName, emp.MiddleName, emp.MaidenName, emp.Alias,
    emp.AddressId, emp.SSNEnc, emp.SSNHash, emp.SSNLast4, emp.Email, emp.Phone, emp.CreatedOn,
    emp.ModifiedOn, emp.UserId, emp.EGuid, emp.LocationId, emp.OriginalHireDate, emp.MostRecentHireDate,
    emp.TerminationDate, emp.DOB, emp.CitizenshipTypeId, emp.StoreId, emp.WOTCLocationId, emp.PayrollLocationId,
    emp.UHRR, emp.ClientEmployeeId, emp.IsInvalidEmail, sd.DocListId, sd.I9FormId, sd.Id As supoortId
    FROM Employee emp
    INNER JOIN I9Form i9 ON emp.Id = i9.EmployeeId
    LEFT JOIN SupportDoc sd ON sd.I9FormId = i9.Id
    WHERE emp.Id = 1 ”
    use_column_value => false
    tracking_column => “ModifiedOn”
    tracking_column_type => “timestamp”
    clean_run => false
    # The filter part of this file is commented out to indicate that it is
    # optional.
    filter {
    aggregate {
    task_id => “%{i9FormId}”
    code => ”
    map[’employee’] = {
    ‘id’ => event.get(‘Id’),
    ‘accountId’ => event.get(’emp.AccountId’),
    ‘firstName’ => event.get(’emp.FirstName’),
    ‘lastName’ => event.get(’emp.LastName’),
    ‘middleName’ => event.get(’emp.MiddleName’),
    ‘maidenName’ => event.get(’emp.MaidenName’),
    ‘alias’ => event.get(’emp.Alias’),
    ‘addressId’ => event.get(’emp.AddressId’),
    ‘sSNEnc’ => event.get(’emp.SSNEnc’),
    ‘sSNHash’ => event.get(’emp.SSNHash’),
    ‘sSNLast4′ => event.get(’emp.SSNLast4′),
    ’email’ => event.get(’emp.Email’),
    ‘phone’ => event.get(’emp.Phone’),
    ‘createdOn’ => event.get(’emp.CreatedOn’),
    ‘modifiedOn’ => event.get(’emp.ModifiedOn’),
    ‘userId’ => event.get(’emp.UserId’),
    ‘eGuid’ => event.get(’emp.EGuid’),
    ‘locationId’ => event.get(’emp.LocationId’),
    ‘originalHireDate’ => event.get(’emp.OriginalHireDate’),
    ‘mostRecentHireDate’ => event.get(’emp.MostRecentHireDate’),
    ‘terminationDate’ => event.get(’emp.TerminationDate’),
    ‘dob’ => event.get(’emp.DOB’),
    ‘citizenShipTypeId’ => event.get(’emp.CitizenshipTypeId’),
    ‘storeId’ => event.get(’emp.StoreId’),
    ‘wotcLocationId’ => event.get(’emp.WOTCLocationId’),
    ‘payrollLocationId’ => event.get(’emp.PayrollLocationId’),
    ‘uhrr’ => event.get(’emp.UHRR’),
    ‘clientEmployeeId’ => event.get(’emp.ClientEmployeeId’),
    ‘isInvaliedEmail’ => event.get(’emp.IsInvalidEmail’)
    map[‘supportdocs’] ||= []
    map[‘supportdocs’] < event.get(‘sd.I9FormId’),
    ‘doclistid’ => event.get(‘sd.DocListId’)}

    push_previous_map_as_event => true
    timeout => 10
    mutate {
    #if needed remove/ delete fields
    #remove_field => [“ssnenc”,”ssnhash”] # if needed
    remove_field => [“support_docs_List”]

    date {
    match => [ “sql_last_value”, “YYYY-MM-dd HH:mm:ss.SSS” ] #2018-01-29 22:16:59.537
    timezone => “Etc/UTC”
    output {
    stdout { codec => rubydebug }
    index => “i91”
    codec => “json”
    #action =>”update” #if want to update existing index data based on ID column
    #ssl=>true # if node is on SSL
    hosts => [“localhost:9200”]
    manage_template => false
    document_type => “i9details”
    document_id => “%{sd.docListId}”
    doc_as_upsert => true
    action => “update”

  2. Tried logstash and elasticsearch 7.3 but i am getting the below error.

    logstash::Event:0x5262d586>], :response=>{“index”=>{“_index”=>”world_v2”, “_type”=>”world_v3”, “_id”=>”ZWE”, “status”=>400, “error”=>{“type”=>”illegal_argument_exception”, “reason”=>”Rejecting mapping update to [world_v2] as the final mapping would have more than 1 type: [_doc, world_v2]”}}}}


Leave a Reply

%d bloggers like this: