package com.roncoo.es.score.first;
import java.io.IOException;
import java.net.InetAddress;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
/**
* @package: com.roncoo.es.score.first
* @ClassName: EmployeeCRUDApp
* @author yelinsheng
* @created 2017年10月23日 下午5:20:04
* @version 1.0
*
*/
@SuppressWarnings("unused")
public class EmployeeCRUDApp {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
//构建client
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch")
.build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
// createEmployee(client);
// deleteEmployee(client);
// updateEmployee(client);
// getEmployee(client);
client.close();
}
/**
* 创建员工信息(创建一个document)
* @param client
* @throws IOException
*/
private static void createEmployee(TransportClient client) throws IOException {
IndexResponse response = client.prepareIndex("company", "employee", "23")
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field("name", "jack23")
.field("age", 21)
.field("position", "technique")
.field("country", "china")
.field("join_date", "2017-10-23")
.field("salary", 10000)
.endObject())
.get();
System.out.println(response.getResult());
}
/**
* 删除员工信息(删除一个document)
* @param client
* @throws IOException
*/
private static void deleteEmployee(TransportClient client) throws IOException {
DeleteResponse response = client.prepareDelete("company", "employee", "2").get();
System.out.println(response.getResult());
}
/**
* 更新员工信息(更新一个document)
* @param client
* @throws IOException
*/
private static void updateEmployee(TransportClient client) throws IOException {
UpdateResponse response = client.prepareUpdate("company", "employee", "23")
.setDoc(XContentFactory.jsonBuilder()
.startObject()
.field("position", "technique manager")
.endObject())
.get();
System.out.println(response.getResult() + " : " + response.getVersion());
}
/**
* 获取员工信息(得到一个document)
* @param client
*/
private static void getEmployee(TransportClient client) {
GetResponse response = client.prepareGet("company", "employee", "1").get();
System.out.println(response.getSourceAsString());
}
}