Thursday, 27 July 2017

Missing Number In Array using java

import java.util.Arrays;
import java.util.BitSet;
 
/**
 * Java program to find missing elements in a Integer array containing 
 * numbers from 1 to 100.
 *
 * @author Rajdeo Singh
 */
public class MissingNumberInArray {
 
    public static void main(String args[]) {

        // one missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
 
        // two missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
 
        // three missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
 
        // four missing number
        printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
 
        // Only one missing number in array
        int[] iArray = new int[]{1, 2, 3, 5};
        int missing = getMissingNumber(iArray, 5);
        System.out.printf("Missing number in array %s is %d %n"
                           Arrays.toString(iArray), missing);
    }

   /**
    * A general method to find missing values from an integer array in Java.
    * This method will work even if array has more than one missing element.
    */
    private static void printMissingNumber(int[] numbers, int count) {
        int missingCount = count - numbers.length;
        BitSet bitSet = new BitSet(count);
 
        for (int number : numbers) {
            bitSet.set(number - 1);
        }
 
        System.out.printf("Missing numbers in integer array %s, with total number %d is %n",
        Arrays.toString(numbers), count);
        int lastMissingIndex = 0;

        for (int i = 0; i < missingCount; i++) {
            lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
            System.out.println(++lastMissingIndex);
        }
 
    }

   /**
    * Java method to find missing number in array of size n containing
    * numbers from 1 to n only.
    * can be used to find missing elements on integer array of 
    * numbers from 1 to 100 or 1 - 1000
    */
    private static int getMissingNumber(int[] numbers, int totalCount) {
        int expectedSum = totalCount * ((totalCount + 1) / 2);
        int actualSum = 0;
        for (int i : numbers) {
            actualSum += i;
        }
 
        return expectedSum - actualSum;
    }
 
}
 
Output
Missing numbers in integer array [1, 2, 3, 4, 6], with total number 6 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 7, 9, 8, 10], with total number 10 is
5
Missing numbers in integer array [1, 2, 3, 4, 6, 9, 8], with total number 10 is
5
7
10
Missing numbers in integer array [1, 2, 3, 4, 9, 8], with total number 10 is
5
6
7
10
Missing number in array [1, 2, 3, 5] is 4

IndexMerger java implemention

package ucy.cs.hpcl.minerSoft.indexmanipulation;

/*This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Author: Asterios Katsifodimos (http://www.asteriosk.gr)
*/
import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexMerger {

 
 /** Index all text files under a directory. */
 public static void main(String[] args) {

  if(args.length != 2){
   System.out.println("Usage: java -jar IndexMerger.jar " +
                "existing_indexes_dir merged_index_dir");
   System.out.println(" existing_indexes_dir: A directory where the " +
                  "indexes that have to merged exist");
   System.out.println("   e.g. indexes/");
   System.out.println("   e.g.         index1");
   System.out.println("   e.g.         index2");
   System.out.println("   e.g.         index3");
   System.out.println(" merged_index_dir: A directory where the merged " +
                                    "index will be stored");
   System.out.println("   e.g. merged_indexes");
   System.exit(1);
  }
  
  File INDEXES_DIR  = new File(args[0]);
  File INDEX_DIR    = new File(args[1]);

  INDEX_DIR.mkdir();
  
  Date start = new Date();

  try {
   IndexWriter writer = new IndexWriter(INDEX_DIR, 
            new StandardAnalyzer(), 
            true);
   writer.setMergeFactor(1000);
   writer.setRAMBufferSizeMB(50);
   
   Directory indexes[] = new Directory[INDEXES_DIR.list().length];

   for (int i = 0; i < INDEXES_DIR.list().length; i++) {
    System.out.println("Adding: " + INDEXES_DIR.list()[i]);
    indexes[i] = FSDirectory.getDirectory(INDEXES_DIR.getAbsolutePath() 
             + "/" + INDEXES_DIR.list()[i]);
   }

   System.out.print("Merging added indexes...");
   writer.addIndexes(indexes);
   System.out.println("done");

   System.out.print("Optimizing index...");
   writer.optimize();
   writer.close();
   System.out.println("done");

   Date end = new Date();
   System.out.println("It took: "+((end.getTime() - start.getTime()) / 1000) 
           + "\"");

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

search on specific field in mongodb/Mongodb-java

mongoDB : Java : Find documents where field is equal to value

Below snippet gets all documents where “firstName” is “Gopi”.

BasicDBObject query = new BasicDBObject();
query.put("firstName", "Gopi");
             
DBCursor cursor = collection.find(query);

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class FindDocument {

/* Step 1 : get mongoClient */
public static MongoClient getMongoClient(){
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mongoClient;
}

public static void main(String args[]){
MongoClient mongoClient = getMongoClient();

/* Step 2: Connect to DB */
DB db = mongoClient.getDB("sample");

/*Step 3 : Get collection */
DBCollection collection = db.getCollection("employee");

/* Step 4 : Create Query object */
BasicDBObject query = new BasicDBObject();
query.put("firstName", "Gopi");

/* Step 5 : Get all documents */
DBCursor cursor = collection.find(query);

/* Step 6 : Print all documents */
while(cursor.hasNext()){
System.out.println(cursor.next());
}
}

}


Output

{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu"}

MongoDB-Java : Java : Get specific fields from the document from Java/MongoDb

MongoDB-Java : Java : Get specific fields from the document from Java/MongoDb

usually “find()” method returns all the fields of document. You can restrict the fields returned be find query by passing “keys” document as a parameter.

Example
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("firstName", 1);
fields.put("lastName", 1);
fields.put("_id", 0);
             
DBCursor cursor = collection.find(query, fields);

Above snippet returns "firstName" and "lastName" fields of the documents. Result documents will not contain "_id" field.

> db.employee.find()
{ "_id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }

Let’s say I had above data in my employee collection.

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class FindDocument {

 /* Step 1 : get mongoCLient */
 public static MongoClient getMongoClient(){
  MongoClient mongoClient = null;
   try {
    mongoClient = new MongoClient( "localhost" , 27017 );
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
   return mongoClient;
 }

 public static void main(String args[]){
  MongoClient mongoClient = getMongoClient();

  /* Step 2: Connect to DB */
  DB db = mongoClient.getDB("sample");

  /*Step 3 : Get collection */
  DBCollection collection = db.getCollection("employee");

  /* Step 4 : Create keys to get in result */
  BasicDBObject query = new BasicDBObject();
  BasicDBObject fields = new BasicDBObject();
  fields.put("firstName", 1);
  fields.put("lastName", 1);
  fields.put("_id", 0);

  /* Step 5 : Get all documents */
  DBCursor cursor = collection.find(query, fields);

  /* Step 6 : Print all documents */
  while(cursor.hasNext()){
   System.out.println(cursor.next());
  }
 }

}


Output
{ "firstName" : "Joel" , "lastName" : "chelli"}
{ "firstName" : "Ananad" , "lastName" : "Bandaru"}
{ "firstName" : "Gopi" , "lastName" : "Battu"}
{ "firstName" : "Ritwik" , "lastName" : "Mohenthy"}

Get all Documents in mongodb using java

mongoDB : Java : Get all Documents

“find” method of collection(without any arguments) returns all the documents in given collection.

> db.employee.find()
{ "_id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }

Let’s say I had above data in my employee collection.

import java.net.UnknownHostException;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class FindDocument {

 /* Step 1 : get mongoCLient */
 public static MongoClient getMongoClient(){
  MongoClient mongoClient = null;
   try {
    mongoClient = new MongoClient( "localhost" , 27017 );
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
   return mongoClient;
 }

 public static void main(String args[]){
  MongoClient mongoClient = getMongoClient();

  /* Step 2: Connect to DB */
  DB db = mongoClient.getDB("sample");

  /*Step 3 : Get collection */
  DBCollection collection = db.getCollection("employee");

  /* Step 4 : Get all documents */
  DBCursor cursor = collection.find();

  /* Step 5 : Get all documents */
  while(cursor.hasNext()){
   System.out.println(cursor.next());
  }
 }

}


Output

{ "_id" : 1.0 , "firstName" : "Joel" , "lastName" : "chelli"}
{ "_id" : 2.0 , "firstName" : "Ananad" , "lastName" : "Bandaru"}
{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu"}
{ "_id" : 4.0 , "firstName" : "Ritwik" , "lastName" : "Mohenthy"}

get a document from mongodb using java

mongoDB : Java : Get one document


“findOne()” method of DBCollection class returns a single object from this collection.

Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

Step 2: Connect to database
DB db = mongoClient.getDB("sample");

Step 3 : Get collection
DBCollection collection = db.getCollection("employee");
Step 4 : Get one document using findOne() method.
DBObject doc = collection.findOne();

Step 5 : Close client
mongoClient.close();

Sample data

> db.employee.find()

{ "_id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram", "salary" : 12345, "hobbies" : [ "writing blogs", "playing cricket", "watching movies", "reading books" ], "address" : { "office" : { "
street" : "Koramangala BDA Complex", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "560034" }, "home" : { "street" : "Near panchayat office", "city" : "Ongole", "state" : "
Andhra Pradesh", "country" : "India", "PIN" : "523169" } } }
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram", "salary" : 54321, "hobbies" : [ "playing cricket", "reading books", "travelling" ], "address" : { "office" : { "street" : "Rupena Agra
hara", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "560068" }, "home" : { "street" : "Near panchayat office", "city" : "Ongole", "state" : "Andhra Pradesh", "country" : "
India", "PIN" : "523169" } } }
{ "_id" : 3, "firstName" : "Jigar", "lastName" : "Shah", "salary" : 52456, "hobbies" : [ "travelling", "watching movies" ], "address" : { "office" : { "street" : "TNagar", "city" : "Chennai", "state"
: "Tamilnadu", "country" : "India", "PIN" : "341234" }, "home" : { "street" : "Ganghi Nagar", "city" : "Delhi", "state" : "Delhi", "country" : "India", "PIN" : "110037" } } }
{ "_id" : 4, "firstName" : "Piyush", "lastName" : "Rai", "salary" : 65432, "hobbies" : [ "travelling", "reading philosophy", "climbing hills" ], "address" : { "office" : { "street" : "Ameerpet", "city
" : "Hyderabad", "state" : "Andhra Pradesh", "country" : "India", "PIN" : "564321" }, "home" : { "street" : "BDA street", "city" : "Patna", "state" : "Bihar", "country" : "India", "PIN" : "324123" } }
 }
{ "_id" : 5, "firstName" : "Keerthi", "lastName" : "Parush", "salary" : 49000, "hobbies" : [ "shopping", "trecking" ], "address" : { "office" : { "street" : "Domlur", "city" : "Bangalore", "state" : "
Karnataka", "country" : "India", "PIN" : "564921" }, "home" : { "street" : "BTM Layout", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "234135" } } }

<pre>
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoDBEx {
/* Step 1 : get mongoCLient */
public static MongoClient getMongoClient() {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient("localhost", 27017);
} catch (Exception e) {
e.printStackTrace();
}
return mongoClient;
}

public static void main(String[] args) throws Exception {
MongoClient mongoClient = getMongoClient();

/* Step 2: Connect to DB */
DB db = mongoClient.getDB("test");

/* Step 3 : Get collection */
DBCollection collection = db.getCollection("employee");

/* Step 4: Get one document */
DBObject doc = collection.findOne();
System.out.println(doc);
/* Close client */
mongoClient.close();
}
}
</pre>

Output
{ "_id" : 1.0 , "firstName" : "Hari Krishna" , "lastName" : "Gurram" , "salary" : 12345.0 , "hobbies" : [ "writing blogs" , "playing cricket" , "watching movies" , "reading books"] , "address" : { "office" : { "street" : "Koramangala BDA Complex" , "city" : "Bangalore" , "state" : "Karnataka" , "country" : "India" , "PIN" : "560034"} , "home" : { "street" : "Near panchayat office" , "city" : "Ongole" , "state" : "Andhra Pradesh" , "country" : "India" , "PIN" : "523169"}}}

Insert a document in Mongodb using java

mongoDB : java : Insert a document


Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

Step 2: Connect to database
DB db = mongoClient.getDB("sample");

Step 3 : Get collection
DBCollection collection = db.getCollection("employee");
Step 4 : Create a document
BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");

Step 5 : Insert document
collection.insert(doc);


import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class InsertDocument {

 /* Step 1 : get mongoCLient */
 public static MongoClient getMongoClient(){
  MongoClient mongoClient = null;
   try {
    mongoClient = new MongoClient( "localhost" , 27017 );
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
   return mongoClient;
 }
 
 public static void main(String args[]){
  MongoClient mongoClient = getMongoClient();
  
  /* Step 2: Connect to DB */
  DB db = mongoClient.getDB("sample");
  
  /*Step 3 : Get collection */
  DBCollection collection = db.getCollection("employee");
  
  /* Step 4 : Create a document */
  BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");
  
  /* Step 5 : Insert document */
  collection.insert(doc);
  
  System.out.println("Document inserted");
 }
}

MongoDb java client, Create a collection in MongoDb using java

mongoDB : java : Create a collection

Creating a collection is a three step process.

Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

Step 2: Connect to database
DB db = mongoClient.getDB("sample");

Step 3: Use the create collection method, to create collection.
DBCollection collection = db.createCollection("employee", null);

import java.net.UnknownHostException;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;


public class DatabaseConnect {

/* Step 1 : get mongoCLient */
public static MongoClient getMongoClient(){
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mongoClient;
}

public static void main(String args[]){
MongoClient mongoClient = getMongoClient();

/* Step 2: Connect to DB */
DB db = mongoClient.getDB("sample");

DBCollection collection = db.createCollection("employee", null);

System.out.println("Collection created ");
System.out.println("Collection employee belongs to db " + collection.getDB());
}
}


Output
Collection created
Collection employee belongs to db sample

Bulk API: To perform bulk operations in elasticsearch using java

Elasticsearch: Java: Bulk API: To perform bulk operations

Bulk api allows us to perform multiple operations at a time. One way to create bulk request is using BulkRequestBuilder class.

String _index = "organization";
String _type = "employee";
String _id1 = 1;
String _id2 = 2;

BulkRequestBuilder bulkRequest = client.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex(_index, _type, _id1)
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "Krishna")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        );

bulkRequest.add(client.prepareIndex(_index, _type, _id2)
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "PYR")
                        .field("postDate", new Date())
                        .field("message", "another post")
                    .endObject()
                  )
        );

BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
    // process failures by iterating through each bulk response item
}

Using BulkProcessor
The BulkProcessor class offers a simple interface to flush bulk operations automatically based on the number or size of requests, or after a given period.

import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;

String _index = "organization";
String _type = "employee";
String _id1 = 1;
String _id2 = 2;

BulkProcessor bulkProcessor = BulkProcessor.builder(
        client,
        new BulkProcessor.Listener() {
            @Override
            public void beforeBulk(long executionId,
                                   BulkRequest request) { ... }

            @Override
            public void afterBulk(long executionId,
                                  BulkRequest request,
                                  BulkResponse response) { ... }

            @Override
            public void afterBulk(long executionId,
                                  BulkRequest request,
                                  Throwable failure) { ... }
        })
        .setBulkActions(10000)
        .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
        .setFlushInterval(TimeValue.timeValueSeconds(5))
        .setConcurrentRequests(1)
        .build();
     
bulkProcessor.add(new IndexRequest(_index, _type, _id1).source(/* your doc here */));
bulkProcessor.add(new DeleteRequest(_index, _type, _id2));


@Override
public void beforeBulk(long executionId,BulkRequest request) { ... }
This method is called just before bulk is executed.

@Override
public void afterBulk(long executionId, BulkRequest request,BulkResponse response) { ... }
This method is called after bulk execution. You can check for some failing requests with response.hasFailures().

@Override
public void afterBulk(long executionId,BulkRequest request,Throwable failure) { ... }
This method is called when the bulk failed and raised a Throwable

setBulkActions(10000)
We want to execute the bulk every 10000 requests

setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
We want to flush the bulk every 1gb

setFlushInterval(TimeValue.timeValueSeconds(5))
We want to flush the bulk every 5 seconds whatever the number of requests

.setConcurrentRequests(1)
Set the number of concurrent requests. A value of 0 means that only a single request will be allowed to be executed. A value of 1 means 1 concurrent request is allowed to be executed while accumulating new bulk requests.

By default, BulkProcessor:
    sets bulkActions to 1000
    sets bulkSize to 5mb
    does not set flushInterval
    sets concurrentRequests to 1

Following application demonstrates simple Bulk utility.

Step 1:Define simple model class Employee.

package com.self_learn.model;

import java.util.ArrayList;
import java.util.List;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@EqualsAndHashCode()
@ToString
public class Employee {
@Getter @Setter private String age;
@Getter @Setter private String firstName;
@Getter @Setter private String lastName;
@Getter @Setter private List<String> hobbies = new ArrayList<>();
}


Step 2: Define Utility class to get Client instance.

package com.self_learn.util;

import static com.self_learn.util.IPUtil.isValidHosts;
import static com.self_learn.util.IPUtil.isValidPorts;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.google.common.base.Preconditions;

public class TransportClientUtil {
private static Map<Map<String, Integer>, Client> localMap = new HashMap<>();

/**
* Take machine name and port addresses as map and return transport client.
* Key is host name, value is port number
*
* @throws UnknownHostException
*/
public static Client getTransportClient(String clusterName,
Map<String, Integer> map) throws UnknownHostException {

Preconditions.checkNotNull(clusterName,
"clusterName shouldn't be empty");
Preconditions.checkNotNull(map, "Map shouldn't be empty");

if (localMap.containsKey(map))
return localMap.get(map);

Preconditions.checkState(isValidHostPorts(map),
"Map contains invalid host (or) port");

Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", true).build();

TransportClient client = new TransportClient(settings);

InetSocketTransportAddress addresses[] = getInetSocketTransportAddresses(map);
client.addTransportAddresses(addresses);
localMap.put(map, client);
return client;
}

/**
* @param map
* @return true, if all the entries in map are valid host, ports. Else
*         false.
*/
private static boolean isValidHostPorts(Map<String, Integer> map) {
Set<String> hostNames = map.keySet();
Set<Integer> ports = new HashSet<>(map.values());

if (!isValidHosts(hostNames.toArray(new String[hostNames.size()])))
return false;

if (!isValidPorts(ports.toArray(new Integer[ports.size()])))
return false;

return true;
}

private static InetSocketTransportAddress[] getInetSocketTransportAddresses(
Map<String, Integer> map) throws UnknownHostException {
InetSocketTransportAddress addresses[] = new InetSocketTransportAddress[map
.size()];
int count = 0;

Set<String> keys = map.keySet();
for (String key : keys) {
InetAddress addr = InetAddress.getByName(key);
InetSocketTransportAddress address = new InetSocketTransportAddress(
addr, map.get(key));
addresses[count] = address;
}

return addresses;
}

/**
* Get transport client for localhost.
*
* @param clusterName
* @param port
* @return
* @throws UnknownHostException
*/
public static Client getLocalTransportClient(String clusterName, int port)
throws UnknownHostException {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", true).build();

TransportClient client = new TransportClient(settings);
InetAddress addr = InetAddress.getByName("127.0.0.1");
InetSocketTransportAddress address = new InetSocketTransportAddress(
addr, port);

client.addTransportAddress(address);
return client;
}

}


Following is the IPUtil class to validate hostnames, ports.

package com.self_learn.util;

import org.apache.commons.validator.routines.InetAddressValidator;

import com.google.common.base.Preconditions;

/**
 * Validate IPaddresses, ports
 *
 * @author harikrishna_gurram
 */
public class IPUtil {
private static InetAddressValidator inetAddressValidator = InetAddressValidator
.getInstance();

/**
* @param ipAddress
* @return true if ip address is valid, else false
*/
public static boolean isValidIPAddress(String ipAddress) {
Preconditions.checkNotNull(ipAddress, "IP address should not be null");
return inetAddressValidator.isValid(ipAddress);
}

/**
* @param port
*            : Port number
* @return true if port number is valid, else false
*/
public static boolean isValidPort(int port) {
if (port > 0 && port < 65536)
return true;
return false;
}

/**
* @param hostNames
* @return true if all the elements of array represents valid hosnames, else
*         false.
*/
public static boolean isValidHosts(String[] hostNames) {
Preconditions.checkNotNull(hostNames, "Host names shouldn't be empty");
for (String hostName : hostNames) {
if (!isValidIPAddress(hostName)) {
return false;
}
}
return true;
}

/**
*
* @param ports
* @return true if all the elements of array represents valid ports, else
*         false.
*/
public static boolean isValidPorts(Integer[] ports) {
Preconditions.checkNotNull(ports, "ports shouldn't be empty");
for (int port : ports) {
if (!isValidPort(port)) {
return false;
}
}
return true;
}

}


Step 3: BulkRequestType class defines constants to identify type of the request like Index, update, upsert update, and delete.

package com.self_learn.constants;

/**
 * Specifies the type of BulkRequest
 *
 * @author harikrishna_gurram
 */
public enum BulkRequestType {
INDEX, UPDATE, UPSERT_UPDATE, DELETE
}


Step 4: Define BulkModelObject. Each BulkObject instance represents a request like INDEX, UPDATE, UPSERT_UPDATE,DELETE.

package com.self_learn.model;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.self_learn.constants.BulkRequestType;

@EqualsAndHashCode()
@ToString
public class BulkObject {

@Getter
@Setter
private String _index;
@Getter
@Setter
private String _type;
@Getter
@Setter
private String _id;
@Getter
@Setter
private String _source;
@Getter
@Setter
private String _upsertSource;
@Getter
@Setter
private BulkRequestType type;

public BulkObject(String _index, String _type, String _id,
BulkRequestType type) {
this._index = _index;
this._type = _type;
this._id = _id;
this.type = type;
}

public BulkObject(String _index, String _type, String _id,
BulkRequestType type, String _source) {
this(_index, _type, _id, type);
this._source = _source;
}

public BulkObject(String _index, String _type, String _id,
BulkRequestType type, String _source, String _upsertSource) {
this(_index, _type, _id, type, _source);
this._upsertSource = _upsertSource;
}
}


Step 5: Define BulkUtil class, which takes set of BulkObjects and process them.

package com.self_learn.util;

import java.util.Set;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.base.Preconditions;

import com.self_learn.constants.BulkRequestType;
import com.self_learn.model.BulkObject;

/**
 * Utility class to execute bulk requests.
 *
 * @author harikrishna_gurram
 */
public class BulkUtil {

private static BulkObject getBulkObject(String _index, String _type,
String _id, BulkRequestType type) {
return new BulkObject(_index, _type, _id, type);
}

private static BulkObject getBulkObject(String _index, String _type,
String _id, BulkRequestType type, String _source) {
return new BulkObject(_index, _type, _id, type, _source);
}

private static BulkObject getBulkObject(String _index, String _type,
String _id, BulkRequestType type, String _source,
String _upsertSource) {
return new BulkObject(_index, _type, _id, type, _source, _upsertSource);
}

public static BulkObject getIndexObject(String _index, String _type,
String _id, String _source) {
return getBulkObject(_index, _type, _id, BulkRequestType.INDEX, _source);
}

public static BulkObject getDeleteObject(String _index, String _type,
String _id) {
return getBulkObject(_index, _type, _id, BulkRequestType.DELETE);
}

public static BulkObject getUpdateObject(String _index, String _type,
String _id, String src) {
return getBulkObject(_index, _type, _id, BulkRequestType.UPDATE, src);
}

public static BulkObject getUpsertUpdateObject(String _index, String _type,
String _id, String _source, String _upsertSource) {
return getBulkObject(_index, _type, _id, BulkRequestType.UPSERT_UPDATE,
_source, _upsertSource);
}

public static BulkObject getIndexObject(String _index, String _type,
String _id, Object _source) {
return getIndexObject(_index, _type, _id, JSONUtil.getJson(_source));
}

public static BulkObject getUpdateObject(String _index, String _type,
String _id, Object _source) {
return getUpdateObject(_index, _type, _id, JSONUtil.getJson(_source));
}

public static BulkObject getUpsertUpdateObject(String _index, String _type,
String _id, Object _source, Object _upsertSource) {
return getUpsertUpdateObject(_index, _type, _id,
JSONUtil.getJson(_source), JSONUtil.getJson(_upsertSource));
}

private static boolean isNull(Object obj) {
return (obj == null);
}

private static boolean isNotNull(Object obj) {
return !isNull(obj);
}

/**
* Validate BulkObject based on Request type.
*
* If Request type
*
* a. is @{link BulkRequestType.INDEX} then BulkObject must has _index,
* _type, _id, _source.
*
* b. is @{link BulkRequestType.UPDATE} then BulkObject must has _index,
* _type, _id, _source.
*
* c. is @{link BulkRequestType.UPSERT_UPDATE} then BulkObject must has
* _index, _type, _id, _source, _upsertSource.
*
* d. is @{link BulkRequestType.DELETE} then BulkObject must has _index,
* _type, _id.
*
* @param type
*            Represents Request type, it can be INDEX, UPDATE,
*            UPSERT_UPDATE, DELETE.
*
* @param obj
* @return
*/
private static boolean isValidBulkObject(BulkObject obj) {
if (obj == null)
return false;

String _index = obj.get_index();
String _type = obj.get_type();
String _id = obj.get_id();
String _source = obj.get_source();
String _upsertSource = obj.get_upsertSource();
BulkRequestType type = obj.getType();

switch (type) {
case INDEX:
if (isNotNull(_index) && isNotNull(_type) && isNotNull(_id)
&& isNotNull(_source))
return true;
break;
case UPDATE:
if (isNotNull(_index) && isNotNull(_type) && isNotNull(_id)
&& isNotNull(_source))
return true;
break;
case UPSERT_UPDATE:
if (isNotNull(_index) && isNotNull(_type) && isNotNull(_id)
&& isNotNull(_source) && isNotNull(_upsertSource))
return true;
break;
case DELETE:
if (isNotNull(_index) && isNotNull(_type) && isNotNull(_id))
return true;
break;
}
return false;
}

/**
* method takes Map of requests and execute bulk requests. Key of map
* represents type of request.
*
* @{link BulkRequestType.INDEX} represents Index request
* @{link BulkRequestType.UPDATE} represents update request
* @{link BulkRequestType.UPSERT_UPDATE} represents UPSERT_UPDATE request
* @{link BulkRequestType.DELETE} represents delete request
*
*        If BulkObject is invalid, then the request is simply ignored.
*
* @param bulkRequest
* @return
*/
public static BulkResponse execute(Client client, Set<BulkObject> bulkReq) {
Preconditions.checkNotNull(client, "client shouldn't be null");
Preconditions.checkNotNull(bulkReq, "bulkReq shouldn't be null");

BulkRequestBuilder bulkRequest = client.prepareBulk();

for (BulkObject obj : bulkReq) {
if (!isValidBulkObject(obj))
continue;

String _index = obj.get_index();
String _type = obj.get_type();
String _id = obj.get_id();
String _source = obj.get_source();
String _upsertSource = obj.get_upsertSource();

BulkRequestType type = obj.getType();

switch (type) {
case INDEX:
bulkRequest.add(new IndexRequest(_index, _type, _id)
.source(_source));
break;
case UPDATE:
bulkRequest.add(new UpdateRequest(_index, _type, _id)
.doc(_source));
break;
case UPSERT_UPDATE:
bulkRequest.add(new UpdateRequest(_index, _type, _id).doc(
_source).upsert(_upsertSource));
break;
case DELETE:
bulkRequest.add(new DeleteRequest(_index, _type, _id));
break;

default:
System.out.println("Invalid Request");
}
}

return bulkRequest.execute().actionGet();
}
}


Step 6: Define ResponseUtil class, used to return the response of query in json format.

package com.self_learn.util;

import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;

import com.google.common.base.Preconditions;

/**
 * Utility class to return response in string format.
 *
 * @author harikrishna_gurram
 */
public class ResponseUtil {

/**
* Returns source of the result as string.
*
* @param response
* @return
*/
public static String getSource(GetResponse response, boolean pretty) {
Preconditions.checkNotNull(response, "response shouldn't be null");
return response.getSourceAsString();
}

/**
* @param response
* @return string representation of {@link BulkResponse}
*/
public static String getResponseInfo(Object response, boolean pretty) {
if (pretty)
return JSONUtil.getPrettyJson(response);

return JSONUtil.getJson(response);
}
}


Step 8: Main.java demonstrate how to use BulkUtil class.

package com.self_learn.test;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;

import com.self_learn.model.BulkObject;
import com.self_learn.model.Employee;
import com.self_learn.util.BulkUtil;
import com.self_learn.util.ResponseUtil;
import com.self_learn.util.TransportClientUtil;

public class Main {
private static String clusterName = "my_cluster_1";
private static String _index = "organization";
private static String _type = "employee";

public static void main(String args[]) throws IOException,
InterruptedException, ExecutionException {
/* Get client instance for cluster */
Client client = TransportClientUtil.getLocalTransportClient(
clusterName, 9300);

Set<BulkObject> objects = new HashSet<>();

/* First 5 index requests */
for (int i = 1; i <= 5; i++) {
Employee emp = new Employee();
emp.setAge("" + i);
emp.setFirstName("firstName " + i);
emp.setLastName("lastName " + i);
emp.setHobbies(Arrays.asList("hobbies " + i));
BulkObject obj = BulkUtil
.getIndexObject(_index, _type, "" + i, emp);
objects.add(obj);
}

BulkResponse response = BulkUtil.execute(client, objects);
System.out.println(ResponseUtil.getResponseInfo(response, true));

/* Delete documents 1 and 4 */
objects = new HashSet<>();
objects.add(BulkUtil.getDeleteObject(_index, _type, "1"));
objects.add(BulkUtil.getDeleteObject(_index, _type, "4"));
response = BulkUtil.execute(client, objects);
System.out.println(ResponseUtil.getResponseInfo(response, true));

/* Update document2 and index document 6 */
objects = new HashSet<>();
Map<String, Object> doc = new HashMap<>();
doc.put("firstName", "Krishna");
doc.put("age", "26");
objects.add(BulkUtil.getUpdateObject(_index, _type, "2", doc));

Employee emp = new Employee();
emp.setAge("" + 6);
emp.setFirstName("firstName " + 6);
emp.setLastName("lastName " + 6);
emp.setHobbies(Arrays.asList("hobbies " + 6));
objects.add(BulkUtil.getIndexObject(_index, _type, "6", emp));
response = BulkUtil.execute(client, objects);
System.out.println(ResponseUtil.getResponseInfo(response, true));

client.close();
}
}

Once you ran, Main.java, you will get following output.  
Sep 10, 2015 2:02:14 PM org.elasticsearch.plugins.PluginsService <init>
INFO: [Turner Century] loaded [], sites []
{
  "responses": [
    {
      "id": 0,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "2",
        "type": "employee",
        "version": 1,
        "created": true
      }
    },
    {
      "id": 1,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "4",
        "type": "employee",
        "version": 1,
        "created": true
      }
    },
    {
      "id": 2,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "1",
        "type": "employee",
        "version": 1,
        "created": true
      }
    },
    {
      "id": 3,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "3",
        "type": "employee",
        "version": 1,
        "created": true
      }
    },
    {
      "id": 4,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "5",
        "type": "employee",
        "version": 1,
        "created": true
      }
    }
  ],
  "tookInMillis": 2,
  "remoteAddress": {
    "address": {}
  }
}
{
  "responses": [
    {
      "id": 0,
      "opType": "delete",
      "response": {
        "index": "organization",
        "id": "4",
        "type": "employee",
        "version": 2,
        "found": true
      }
    },
    {
      "id": 1,
      "opType": "delete",
      "response": {
        "index": "organization",
        "id": "1",
        "type": "employee",
        "version": 2,
        "found": true
      }
    }
  ],
  "tookInMillis": 1,
  "remoteAddress": {
    "address": {}
  }
}
{
  "responses": [
    {
      "id": 0,
      "opType": "update",
      "response": {
        "index": "organization",
        "id": "2",
        "type": "employee",
        "version": 2,
        "created": false
      }
    },
    {
      "id": 1,
      "opType": "index",
      "response": {
        "index": "organization",
        "id": "6",
        "type": "employee",
        "version": 1,
        "created": true
      }
    }
  ],
  "tookInMillis": 1,
  "remoteAddress": {
    "address": {}
  }
}

Elasticsearch Get API in Java

Elasticsearch: Java: Get API
By using ‘prepareGet’ method, you can get a document by specifying _index, _type, _id.

GetResponse response = client.prepareGet("organization", "employee", "1").execute().actionGet();

Following sep-by-step procedure explain complete working application.


Step 1: Define a model class Employee.
package com.self_learn.model;

import java.util.ArrayList;
import java.util.List;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@EqualsAndHashCode()
@ToString
public class Employee {
 @Getter @Setter private String age;
 @Getter @Setter private String firstName;
 @Getter @Setter private String lastName;
 @Getter @Setter private List<String> hobbies = new ArrayList<>();
}


Step 2: Define TransportClientUtil class to get a Client instance.

package com.self_learn.util;

import static com.self_learn.util.IPUtil.isValidHosts;
import static com.self_learn.util.IPUtil.isValidPorts;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.google.common.base.Preconditions;

public class TransportClientUtil {
 private static Map<Map<String, Integer>, Client> localMap = new HashMap<>();

 /**
  * Take machine name and port addresses as map and return transport client.
  * Key is host name, value is port number
  *
  * @throws UnknownHostException
  */
 public static Client getTransportClient(String clusterName,
   Map<String, Integer> map) throws UnknownHostException {

  Preconditions.checkNotNull(clusterName,
    "clusterName shouldn't be empty");
  Preconditions.checkNotNull(map, "Map shouldn't be empty");

  if (localMap.containsKey(map))
   return localMap.get(map);

  Preconditions.checkState(isValidHostPorts(map),
    "Map contains invalid host (or) port");

  Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", clusterName)
    .put("client.transport.sniff", true).build();

  TransportClient client = new TransportClient(settings);

  InetSocketTransportAddress addresses[] = getInetSocketTransportAddresses(map);
  client.addTransportAddresses(addresses);
  localMap.put(map, client);
  return client;
 }

 /**
  * @param map
  * @return true, if all the entries in map are valid host, ports. Else
  *         false.
  */
 private static boolean isValidHostPorts(Map<String, Integer> map) {
  Set<String> hostNames = map.keySet();
  Set<Integer> ports = new HashSet<>(map.values());

  if (!isValidHosts(hostNames.toArray(new String[hostNames.size()])))
   return false;

  if (!isValidPorts(ports.toArray(new Integer[ports.size()])))
   return false;

  return true;
 }

 private static InetSocketTransportAddress[] getInetSocketTransportAddresses(
   Map<String, Integer> map) throws UnknownHostException {
  InetSocketTransportAddress addresses[] = new InetSocketTransportAddress[map
    .size()];
  int count = 0;

  Set<String> keys = map.keySet();
  for (String key : keys) {
   InetAddress addr = InetAddress.getByName(key);
   InetSocketTransportAddress address = new InetSocketTransportAddress(
     addr, map.get(key));
   addresses[count] = address;
  }

  return addresses;
 }

 /**
  * Get transport client for localhost.
  *
  * @param clusterName
  * @param port
  * @return
  * @throws UnknownHostException
  */
 public static Client getLocalTransportClient(String clusterName, int port)
   throws UnknownHostException {
  Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", clusterName)
    .put("client.transport.sniff", true).build();

  TransportClient client = new TransportClient(settings);
  InetAddress addr = InetAddress.getByName("127.0.0.1");
  InetSocketTransportAddress address = new InetSocketTransportAddress(
    addr, port);

  client.addTransportAddress(address);
  return client;
 }

}


IPUtil class is used to validate hostnames, ports.

package com.self_learn.util;

import org.apache.commons.validator.routines.InetAddressValidator;

import com.google.common.base.Preconditions;

/**
 * Validate IPaddresses, ports
 *
 * @author harikrishna_gurram
 */
public class IPUtil {
 private static InetAddressValidator inetAddressValidator = InetAddressValidator
   .getInstance();

 /**
  * @param ipAddress
  * @return true if ip address is valid, else false
  */
 public static boolean isValidIPAddress(String ipAddress) {
  Preconditions.checkNotNull(ipAddress, "IP address should not be null");
  return inetAddressValidator.isValid(ipAddress);
 }

 /**
  * @param port
  *            : Port number
  * @return true if port number is valid, else false
  */
 public static boolean isValidPort(int port) {
  if (port > 0 && port < 65536)
   return true;
  return false;
 }

 /**
  * @param hostNames
  * @return true if all the elements of array represents valid hosnames, else
  *         false.
  */
 public static boolean isValidHosts(String[] hostNames) {
  Preconditions.checkNotNull(hostNames, "Host names shouldn't be empty");
  for (String hostName : hostNames) {
   if (!isValidIPAddress(hostName)) {
    return false;
   }
  }
  return true;
 }

 /**
  *
  * @param ports
  * @return true if all the elements of array represents valid ports, else
  *         false.
  */
 public static boolean isValidPorts(Integer[] ports) {
  Preconditions.checkNotNull(ports, "ports shouldn't be empty");
  for (int port : ports) {
   if (!isValidPort(port)) {
    return false;
   }
  }
  return true;
 }

}


Step 3: Define JSONUtil class to convert object to json.

package com.self_learn.util;

import org.elasticsearch.common.base.Preconditions;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Convert object to json string.
 *
 * @author harikrishna_gurram
 */
public class JSONUtil {
 private static Gson gson = new Gson();
 private static Gson prettyGson = new GsonBuilder().setPrettyPrinting()
   .create();

 /**
  * @param obj
  * @return json string of this object.
  */
 public static String getJson(Object obj) {
  Preconditions.checkNotNull(obj, "obj shouldn't be null");
  return gson.toJson(obj);
 }

 /**
  * @param obj
  * @return json string of this object (Pretty json).
  */
 public static String getPrettyJson(Object obj) {
  Preconditions.checkNotNull(obj, "obj shouldn't be null");
  return prettyGson.toJson(obj);
 }
}


Step 4: IndexUtil class provide methods to store data into Elasticsearch.

package com.self_learn.util;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;

import com.google.common.base.Preconditions;

/**
 * Provides utility methods to store data into Elasticsearch.
 *
 * @author harikrishna_gurram
 */
public class IndexUtil {

 /**
  * Index given document.
  *
  * @param client
  *            : Client used to index data
  * @param _index
  *            : Document is stored in this index
  * @param _type
  *            : Document stored in this type
  * @param _id
  *            : Specifies _id of the document
  * @param document
  *            : Represents body of the document
  * @return {@link IndexResponse}
  */
 public static IndexResponse indexData(Client client, String _index,
   String _type, String _id, String document) {
  Preconditions.checkNotNull(client, "client should not be null");
  Preconditions.checkNotNull(_index, "_index should not be null");
  Preconditions.checkNotNull(_type, "_type should not be null");
  Preconditions.checkNotNull(_id, "_id should not be null");
  Preconditions.checkNotNull(document, "data should not be null");

  IndexResponse response = client.prepareIndex(_index, _type, _id)
    .setSource(document).execute().actionGet();
  return response;
 }

 /**
  * Index given object.
  *
  * @param client
  *            : Client used to index data
  * @param _index
  *            : Document is stored in this index
  * @param _type
  *            : Document stored in this type
  * @param _id
  *            : Specifies _id of the document
  * @param obj
  *            : Object to index
  * @return {@link IndexResponse}
  */
 public static IndexResponse indexData(Client client, String _index,
   String _type, String _id, Object obj) {
  Preconditions.checkNotNull(obj, "data should not be null");
  return indexData(client, _index, _type, _id, JSONUtil.getJson(obj));
 }

}


Step 5: SearchUtil class provides various utility methods to query Elasticsearch.

package com.self_learn.util;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;

import com.google.common.base.Preconditions;

/**
 * Provide various utility methods to query Elasticsearch.
 *
 * @author harikrishna_gurram
 */
public class SearchUtil {

 /**
  * Returns the document by id (Takes _index, _type, _id as input).
  *
  * @param client
  * @param _index
  * @param _type
  * @param _id
  * @return the document by id
  */
 public static GetResponse getDocumentById(Client client, String _index,
   String _type, String _id) {
  Preconditions.checkNotNull(client, "client should not be null");
  Preconditions.checkNotNull(_index, "_index should not be null");
  Preconditions.checkNotNull(_type, "_type should not be null");
  Preconditions.checkNotNull(_id, "_id should not be null");

  GetResponse response = client.prepareGet(_index, _type, _id).execute()
    .actionGet();
  return response;
 }

}


Step 6: ResponseUtil class provide methods to return respone in string format.

package com.self_learn.util;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;

import com.google.common.base.Preconditions;

/**
 * Utility class to return respone in string format.
 *
 * @author harikrishna_gurram
 */
public class ResponseUtil {

 /**
  * @param response
  * @return string representation of {@link IndexResponse}
  */
 public static String getResponseInfo(IndexResponse response) {
  Preconditions.checkNotNull(response, "response shouldn't be null");
  String _index = response.getIndex();
  String _type = response.getType();
  String _id = response.getId();
  long _version = response.getVersion();
  boolean created = response.isCreated();

  StringBuilder builder = new StringBuilder();
  return builder.append("_index: ").append(_index).append("\n")
    .append("_type: ").append(_type).append("\n").append("_id: ")
    .append(_id).append("\n").append("_version: ").append(_version)
    .append("\n").append("created: ").append(created).toString();
 }

 /**
  * @param response
  * @return string representation of {@link GetResponse}
  */
 public static String getResponseInfo(GetResponse response) {
  Preconditions.checkNotNull(response, "response should not be null");

  String _index = response.getIndex();
  String _type = response.getType();
  String _id = response.getId();
  long _version = response.getVersion();
  String source = response.getSourceAsString();

  StringBuilder builder = new StringBuilder();
  return builder.append("_index: ").append(_index).append("\n")
    .append("_type: ").append(_type).append("\n").append("_id: ")
    .append(_id).append("\n").append("_version: ").append(_version)
    .append("\n").append("_source: ").append(source).toString();
 }
}


Step 7: Main class demonstrates complete application.

package com.self_learn.test;

import java.net.UnknownHostException;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;

import com.self_learn.model.Employee;
import com.self_learn.util.IndexUtil;
import com.self_learn.util.ResponseUtil;
import com.self_learn.util.SearchUtil;
import com.self_learn.util.TransportClientUtil;

public class Main {
 private static String clusterName = "my_cluster_1";
 private static String _index = "organization";
 private static String _type = "employee";

 public static void main(String args[]) throws UnknownHostException {
  /* Get client instance for cluster */
  Client client = TransportClientUtil.getLocalTransportClient(
    clusterName, 9300);

  /* Prepare model object */
  Employee emp = new Employee();
  emp.setAge("27");
  emp.setFirstName("PTR");
  emp.setLastName("Nayan");
  emp.getHobbies().add("Tattoos");
  emp.getHobbies().add("People Watching");
  emp.getHobbies().add("Dagger Collecting");
  emp.getHobbies().add("Confusing People");

  /* Write object into Elasticsearch */
  IndexUtil.indexData(client, _index, _type, "1", emp);

  /* Query for the object with id 1 */
  GetResponse response = SearchUtil.getDocumentById(client, _index,
    _type, "1");

  /* Print Response */
  System.out.println(ResponseUtil.getResponseInfo(response));

  client.close();
 }
}


When you ran above application, you will get following kind of output.

Sep 09, 2015 2:47:54 PM org.elasticsearch.plugins.PluginsService <init>
INFO: [Styx and Stone] loaded [], sites []
_index: organization
_type: employee
_id: 1
_version: 8
_source: {"age":"27","firstName":"PTR","lastName":"Nayan","hobbies":["Tattoos","People Watching","Dagger Collecting","Confusing People"]}