Sunday, 10 July 2022

Create, Insert and query data from hive table

Step 1: Create a table employee with fields id, name, list of hobbies, technology_experience and gender, age details.

CREATE TABLE employee (
	id INT,
	name STRING,
	hobbies ARRAY<STRING>,
	technology_experience MAP<STRING,STRING>,
	gender_age STRUCT<gender:STRING,age:INT>
 )
 ROW FORMAT DELIMITED
 FIELDS TERMINATED BY '|'
 COLLECTION ITEMS TERMINATED BY ','
 MAP KEYS TERMINATED BY ':'
 STORED AS TEXTFILE;

hive> CREATE TABLE employee (
    > Display all 633 possibilities? (y or n)
    > ame STRING,
    > Display all 633 possibilities? (y or n)
    > ology_experience MAP<STRING,STRING>,
    > Display all 633 possibilities? (y or n)
    > der_age STRUCT<gender:STRING,age:INT>
    >  )
    >  ROW FORMAT DELIMITED
    >  FIELDS TERMINATED BY '|'
    >  COLLECTION ITEMS TERMINATED BY ','
    >  MAP KEYS TERMINATED BY ':'
    >  STORED AS TEXTFILE;
OK
Time taken: 0.213 seconds

Execute the command ‘show create table employee;’ to get where exactly the data is stored for employee table in HDFS. 

hive> show create table employee;
OK
CREATE TABLE `employee`(
  `id` int, 
  `name` string, 
  `hobbies` array<string>, 
  `technology_experience` map<string,string>, 
  `gender_age` struct<gender:string,age:int>)
ROW FORMAT SERDE 
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' 
WITH SERDEPROPERTIES ( 
  'collection.delim'=',', 
  'field.delim'='|', 
  'mapkey.delim'=':', 
  'serialization.format'='|') 
STORED AS INPUTFORMAT 
  'org.apache.hadoop.mapred.TextInputFormat' 
OUTPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'hdfs://localhost:9000/user/hive/warehouse/employee'
TBLPROPERTIES (
  'bucketing_version'='2', 
  'transient_lastDdlTime'='1610696478')
Time taken: 0.278 seconds, Fetched: 22 row(s)

From the output, I can confirm, information is stored in /user/hive/warehouse/employee folder of HDFS.

 

Step 2: Create empInfo.txt file and move it to HDFS location /user/hive/warehouse/employee.

 

empInfo.txt

 

1|Hari|Football,Cricket|Java:3.4Yrs,C:4.5Yrs|Male,30
2|Chamu|Trekking,Watching movies|Selenium:5.6Yrs|Feale,38
3|Sailu|Chess,Listening to music|EmbeddedC:9Yrs|Femle,32
4|Gopi|Cricket|Datastage:11Yrs|Male,32

Step 3: Add empInfo.txt file to hdfs location /user/hive/warehouse/employee. Any content you place in the directory /user/hive/warehouse/employee will be the content of the table employee.

$ hdfs dfs -put empInfo.txt /user/hive/warehouse/employee
$ 
$ hdfs dfs -cat /user/hive/warehouse/employee/empInfo.txt
1|Hari|Football,Cricket|Java:3.4Yrs,C:4.5Yrs|Male,30
2|Chamu|Trekking,Watching movies|Selenium:5.6Yrs|Feale,38
3|Sailu|Chess,Listening to music|EmbeddedC:9Yrs|Femle,32
4|Gopi|Cricket|Datastage:11Yrs|Male,32bash-3.2

Step 4: Go to hive prompt and execute the query ‘select * from employee;’ to list out all the contents of employee table.

hive> select * from employee;
OK
1 Hari  ["Football","Cricket"]  {"Java":"3.4Yrs","C":"4.5Yrs"}  {"gender":"Male","age":30}
2 Chamu ["Trekking","Watching movies"]  {"Selenium":"5.6Yrs"} {"gender":"Feale","age":38}
3 Sailu ["Chess","Listening to music"]  {"EmbeddedC":"9Yrs"}  {"gender":"Femle","age":32}
4 Gopi  ["Cricket"] {"Datastage":"11Yrs"} {"gender":"Male","age":32}
Time taken: 0.158 seconds, Fetched: 4 row(s)

Query specific elements of array hobbies

hive> select hobbies[0] as first_hobby, hobbies[1] as second_hobby from employee;
OK
Football  Cricket
Trekking  Watching movies
Chess Listening to music
Cricket NULL
Time taken: 0.085 seconds, Fetched: 4 row(s)

Query struct attributes

hive> select name, gender_age.gender, gender_age.age from employee;
OK
Hari  Male  30
Chamu Feale 38
Sailu Femle 32
Gopi  Male  32
Time taken: 0.1 seconds, Fetched: 4 row(s)

Query map elements

hive> select name, technology_experience['Java'], technology_experience['Datastage'] from employee;
OK
Hari  3.4Yrs  NULL
Chamu NULL  NULL
Sailu NULL  NULL
Gopi  NULL  11Yrs
Time taken: 0.102 seconds, Fetched: 4 row(s)

 

 

Previous                                                    Next                                                    Home

Atlas client: Create a type, where attribute type is a map

By specifying the typeName as ‘map<string,string>’, we can set an attribute to take map of values.

"attributeDefs": [
    {
      "name": "myMap",
      "typeName": "map<string,string>",
      "isOptional": false,
      "cardinality": "SINGLE",
      "valuesMinCount": 1,
      "valuesMaxCount": 1,
      "isUnique": false,
      "isIndexable": false,
      "includeInNotification": false,
      "searchWeight": -1
    }
  ]

 

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties
atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

 

Define AttributeTypeMap class.

 

AttributeTypeMap.java

 

package com.sample.app.attributes;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasTypesDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;

import com.fasterxml.jackson.core.JsonProcessingException;

public class AttributeTypeMap {

  private static final String TYPE_NAME = "DemoType4";

  private static void createType(AtlasClientV2 atlasClient) throws AtlasServiceException {
    AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
    attributeDef1.setName("myMap");
    attributeDef1.setTypeName("map<string,string>");
    attributeDef1.setIsIndexable(false);
    attributeDef1.setIsUnique(false);

    AtlasEntityDef atlasEntityDef = new AtlasEntityDef();
    atlasEntityDef.setName(TYPE_NAME);
    atlasEntityDef.setCreatedBy("Krishna");
    atlasEntityDef.setUpdatedBy("krishna");
    atlasEntityDef.setDescription("Represent a demo specification");
    atlasEntityDef.setAttributeDefs(Arrays.asList(attributeDef1));

    Set<String> superTypes = new HashSet<>();
    superTypes.add("DataSet");
    atlasEntityDef.setSuperTypes(superTypes);

    AtlasTypesDef atlasTypesDef = new AtlasTypesDef();

    atlasTypesDef.getEntityDefs().add(atlasEntityDef);

    atlasClient.createAtlasTypeDefs(atlasTypesDef);
  }

  private static void createEntity(AtlasClientV2 atlasClient) throws AtlasServiceException {

    AtlasEntity atlasEntity = new AtlasEntity();

    atlasEntity.setTypeName(TYPE_NAME);

    Map<String, Object> map = new HashMap<>();
    map.put("name", "Krishna");
    map.put("age", "23");

    Map<String, String> address = new HashMap<>();
    address.put("city", "Bangalore");
    address.put("state", "Karnatka");

    map.put("address", address);

    atlasEntity.setAttribute("myMap", map);

    // Following are the mandatory attributes
    atlasEntity.setAttribute("qualifiedName", "AttributeTypeMap_DEMO1");
    atlasEntity.setAttribute("name", "AttributeTypeMap_DEMO1");

    AtlasEntity.AtlasEntityWithExtInfo atlasEntityWithExtInfo = new AtlasEntity.AtlasEntityWithExtInfo();
    atlasEntityWithExtInfo.setEntity(atlasEntity);

    atlasClient.createEntity(atlasEntityWithExtInfo);
  }

  public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {

    AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
        new String[] { "admin", "admin" });

    createType(atlasClient);
    createEntity(atlasClient);

  }
}

 

Run above application.

 

Open Atlas UI and query for the type ‘DemoType4’.

Click on the link ‘AttributeTypeMap_DEMO1’ to view the entity attributes.

 


Previous                                                    Next                                                    Home

Saturday, 9 July 2022

Can enum implement an interface in Java?

Enum can implement an interface in Java (Enum can have abstract methods too).

 


Example

enum StringConverters implements Converter<String> {
		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		}
}

 

Find the below working application.

 

EnumImplementInterface.java

package com.sample.app;

public class EnumImplementInterface {

	interface Converter<T> {
		T convert(T data);
	}

	public static enum StringConverters implements Converter<String> {
		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		},
		UPPER {

			@Override
			public String convert(String str) {
				return str.toUpperCase();
			}

		},
		CAMELCASE {

			@Override
			public String convert(String str) {
				return toCamelCase(str);
			}

		};

		private static String toCamelCase(final String str) {
			if (str == null || str.isEmpty())
				return null;

			final StringBuilder builder = new StringBuilder();

			for (final String word : str.split(" ")) {
				if (!word.isEmpty()) {
					builder.append(Character.toUpperCase(word.charAt(0)));
					builder.append(word.substring(1).toLowerCase());
				}
				if (!(builder.length() == str.length()))
					builder.append(" ");
			}

			return builder.toString();
		}
	}

	public static void main(String[] args) {
		String str = "Hi Krishna, how are you";

		System.out.println(StringConverters.LOWER.convert(str));
		System.out.println(StringConverters.UPPER.convert(str));
		System.out.println(StringConverters.CAMELCASE.convert(str));
	}

}

Output

hi krishna, how are you
HI KRISHNA, HOW ARE YOU
Hi Krishna, How Are You



 

 

  

You may like

Interview Questions

How to read the file content using an iterator in Java?

Implement a Closeable iterator in Java

Quick guide to generate random data in Java

What are the different cache eviction strategies?


How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can an enum has abstract methods in Java?

Enum can have abstract methods in Java. This feature is useful, when you need to provide different implementation for the enum constants.


 

Example

public static enum StringConverters {

	LOWER {

		@Override
		public String convert(String str) {
			return str.toLowerCase();
		}

	},
	CAMELCASE {

		@Override
		public String convert(String str) {
			return toCamelCase(str);
		}

	};

	abstract public String convert(String str);
};

 

Find the below working application.

 

EnumAbstractMethod.java

package com.sample.app;

public class EnumAbstractMethod {

	public static enum StringConverters {

		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		},
		UPPER {

			@Override
			public String convert(String str) {
				return str.toUpperCase();
			}

		},
		CAMELCASE {

			@Override
			public String convert(String str) {
				return toCamelCase(str);
			}

		};

		private static String toCamelCase(final String str) {
			if (str == null || str.isEmpty())
				return null;

			final StringBuilder builder = new StringBuilder();

			for (final String word : str.split(" ")) {
				if (!word.isEmpty()) {
					builder.append(Character.toUpperCase(word.charAt(0)));
					builder.append(word.substring(1).toLowerCase());
				}
				if (!(builder.length() == str.length()))
					builder.append(" ");
			}

			return builder.toString();
		}

		abstract public String convert(String str);
	};

	public static void main(String[] args) {
		String str = "Hi Krishna, how are you";

		System.out.println(StringConverters.LOWER.convert(str));
		System.out.println(StringConverters.UPPER.convert(str));
		System.out.println(StringConverters.CAMELCASE.convert(str));
	}

}

 

Output

hi krishna, how are you
HI KRISHNA, HOW ARE YOU
Hi Krishna, How Are You

 

If you have this kind of use case, you may prefer the enum which implements an interface.

 

EnumImplementInterface.java

package com.sample.app;

public class EnumImplementInterface {

	interface Converter<T> {
		T convert(T data);
	}

	public static enum StringConverters implements Converter<String> {
		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		},
		UPPER {

			@Override
			public String convert(String str) {
				return str.toUpperCase();
			}

		},
		CAMELCASE {

			@Override
			public String convert(String str) {
				return toCamelCase(str);
			}

		};

		private static String toCamelCase(final String str) {
			if (str == null || str.isEmpty())
				return null;

			final StringBuilder builder = new StringBuilder();

			for (final String word : str.split(" ")) {
				if (!word.isEmpty()) {
					builder.append(Character.toUpperCase(word.charAt(0)));
					builder.append(word.substring(1).toLowerCase());
				}
				if (!(builder.length() == str.length()))
					builder.append(" ");
			}

			return builder.toString();
		}
	}

	public static void main(String[] args) {
		String str = "Hi Krishna, how are you";

		System.out.println(StringConverters.LOWER.convert(str));
		System.out.println(StringConverters.UPPER.convert(str));
		System.out.println(StringConverters.CAMELCASE.convert(str));
	}

}

Output

hi krishna, how are you
HI KRISHNA, HOW ARE YOU
Hi Krishna, How Are You




 

 

 

You may like

Interview Questions

Quick guide to race condition in Java with examples

How to read the file content using an iterator in Java?

Implement a Closeable iterator in Java

Quick guide to generate random data in Java

What are the different cache eviction strategies?


How to call super class method from sub class overriding method?

How to download a binary file in Java?

Approach 1: Using InputStream, we can read the data from the given url and OutputStream can be used to write the binary data to disk.

 


 

Find the below working application.

 

BinaryDownloaderDemo.java

package com.sample.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class BinaryDownloaderDemo {

	private static void downloadFile(final String urlToDownload, final String filePath) {
		
		// Create parent folders if not exists
		final File file = new File(filePath);
		file.getParentFile().mkdirs();

		try {
			final URL url = new URL(urlToDownload);
			final URLConnection urlConnection = url.openConnection();

			try (final InputStream inputStream = urlConnection.getInputStream();
					final OutputStream outputStream = new FileOutputStream(filePath);) {
				byte[] buffer = new byte[65535];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		final String urlToDownlaod =  "https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip";
		
		downloadFile(urlToDownlaod, "/Users/Shared/softwares/maven/apache-maven-3.8.6-bin.zip");
		
	}

}

 

Approach 2: Using nio FileChannel# transferFrom method.

 

BinaryDownloaderDemo2.java

package com.sample.app;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class BinaryDownloaderDemo2 {

	private static void downloadFile(final String urlToDownload, final String filePath) {

		// Create parent folders if not exists
		final File file = new File(filePath);
		file.getParentFile().mkdirs();

		try {
			URL website = new URL(urlToDownload);

			try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
					FileOutputStream fos = new FileOutputStream(filePath);) {
				fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		final String urlToDownlaod = "https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip";

		downloadFile(urlToDownlaod, "/Users/Shared/softwares/maven/apache-maven-3.8.6-bin.zip");

	}

}

 

 

 

You may like

File programs in Java

Count number of lines in a file

Download file from Internet using Java

Get the content of resource file as string

Copy the content of file to other location

Write byte array to a file