BULK - TuPengXiong/TuPengXiong.github.io GitHub Wiki

package tpx.elasticsearch;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
/**
 * 
 * @author tpx
 *
 */
public class Bulk {

	
	public static void main(String[] args) throws IOException {
		Bulk bulk = new Bulk();
		Index index = new Index();
		index.createTransportClient();
		printResponse(bulk.createIndex(index.client));
		index.closeTransportClient();
	/*	printResponse(bulk.deleteIndex(index.client));
		index.closeTransportClient();*/
	}
	
	public BulkResponse createIndex(TransportClient client) throws IOException {
		BulkRequestBuilder bulkRequest = client.prepareBulk();

		// either use client#prepare, or use Requests# to directly build index/delete requests
		bulkRequest.add(client.prepareIndex("tpx", "testBulk", "1")
		        .setSource(XContentFactory.jsonBuilder()
		                    .startObject()
		                        .field("user", "testBulk1")
		                        .field("postDate", new Date())
		                        .field("message", "trying out testBulk")
		                    .endObject()
		                  )
		        );

		bulkRequest.add(client.prepareIndex("tpx", "testBulk", "2")
		        .setSource(XContentFactory.jsonBuilder()
		                    .startObject()
		                        .field("user", "testBulk2")
		                        .field("postDate", new Date())
		                        .field("message", "another testBulk")
		                    .endObject()
		                  )
		        );

		BulkResponse bulkResponse = bulkRequest.get();
		return bulkResponse;
	}
	
	/*public BulkResponse deleteIndex(TransportClient client) throws IOException {
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		// either use client#prepare, or use Requests# to directly build index/delete requests
		bulkRequest.add(client.prepareDelete("tpx", "testBulk", "1"));
		bulkRequest.add(client.prepareDelete("tpx", "testBulk", "2"));
		BulkResponse bulkResponse = bulkRequest.get();
		return bulkResponse;
	}*/
	
	public static void printResponse(BulkResponse response){
		System.out.println(response.hasFailures());
	}
}