1.创建maven项目,pom.xml文件中增加如下配置:
org.elasticsearch.client
transport
6.4.0
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.2
1.8
UTF-8
java代码调用:
package com.es.elasticsearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
public class ElasticsearchTest_1 {
private Logger logger = LoggerFactory.getLogger(ElasticsearchTest_1.class);
public final static String HOST="127.0.0.1";
//http请求的端口是9200,客户端是9300
public final static int PORT = 9300;
public final static String CLUSTERNAME = "elasticsearch";
public static TransportClient getConnection() throws Exception {
Settings settings = Settings.builder()
.put("client.transport.sniff", true) //增加嗅探机制,找到ES集群
.put("cluster.name", CLUSTERNAME) // 设置集群名称
.put("thread_pool.search.size", 20)// 增加线程池个数,暂时设为20
.build();
// 创建client
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));
return client;
}
/*
* 添加
* 索引和类型是必需的,而id部分是可选的。如果不指定ID,ElasticSearch会为我们生成一个ID。
*/
public void add() throws Exception{
try {
XContentBuilder content = XContentFactory.jsonBuilder().startObject()
.field("name","daniel")
.field("age",20)
.field("job","coder")
.endObject();
String index = "data"; // 索引值
String type ="person"; // 类型
String id="1"; // id值
TransportClient client = this.getConnection();
IndexResponse iresp = client.prepareIndex(index, type,id).setSource(content).get();
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 添加索引:传入json字符串
* id 自动创建
*
* */
public void addJsonstr() throws Exception{
String jsonstr = "{\"userName\":\"Tom\",\"date\":\"2018-11-7\",\"msg\":\"where are you\"}";
TransportClient client = this.getConnection();
IndexResponse iresp = client.prepareIndex("chat", "msg").setSource(jsonstr,XContentType.JSON).get();
client.close();
System.err.println(iresp.getIndex());
System.err.println(iresp.getId());
System.out.println(iresp.status());
}
/*
* 添加索引:传入json
*
* */
public void addJSON() throws Exception{
JSONObject json = new JSONObject();
json.put("userName", "allen");
json.put("date", new Date().toString());
json.put("msg", "hello allen");
TransportClient client = this.getConnection();
IndexResponse iresp = client.prepareIndex("chat", "msg","3").setSource(json,XContentType.JSON).get();
client.close();
System.err.println(iresp.getIndex());
System.err.println(iresp.getId());
System.out.println(iresp.status());
}
/*
* 创建索引-传入Map对象
*
* */
public void addMap() throws Exception{
Map map = new HashMap();
map.put("userName", "Daniel");
map.put("sendDate", new Date());
map.put("msg", "hello Daniel");
TransportClient client = this.getConnection();
IndexResponse response = client.prepareIndex("momo", "msg","1").setSource(map).get();
logger.info("map索引名称:" + response.getIndex() + "\n map类型:" + response.getType()
+ "\n map文档ID:" + response.getId() + "\n当前实例map状态:" + response.status());
}
/*
* 获取数据
*/
public void get(String index,String type,String id) throws Exception{
TransportClient client = this.getConnection();
GetResponse result = client.prepareGet(index,type,id).get();
System.out.println(result.getSourceAsString());
System.out.println(result.getType());
System.out.println(result.getVersion());
System.err.println(result.getIndex());
System.err.println(result.getId());
client.close();
}
/*
* 更新
*/
public void update() throws Exception{
XContentBuilder content = XContentFactory.jsonBuilder().startObject();
content.field("age",22);
content.field("job","boss");
content.endObject();
UpdateRequest request = new UpdateRequest("data","person","1");
request.doc(content);
TransportClient client = this.getConnection();
UpdateResponse resp = client.update(request).get();
client.close();
}
/*
* 删除
*/
public void delete() throws Exception{
TransportClient client = this.getConnection();
DeleteResponse response = client.prepareDelete("data","person","1").get();
client.close();
System.out.println(response.getResult());
}
/*
* 关闭
*/
public static void closeConnect(TransportClient client){
if(null !=client){
client.close();
}
}
public static void main(String[] args) throws Exception {
/*TransportClient client = getConnection();
System.out.println(client.toString());
System.out.println(client.nodeName());*/
ElasticsearchTest_1 t = new ElasticsearchTest_1();
// t.add();
// t.get();
// t.update();
// t.get();
// t.delete();
// t.get("data","person","1");
// t.addJsonstr();
// t.get("chat", "msg","5jbh7GYB_P4tFfCC1ruQ");
// t.get("chat", "msg","5zbl7GYB_P4tFfCCpLt1");
// t.addJSON();
t.get("chat", "msg","3");
// t.addMap();
// t.get("momo", "msg","1");
}
}
请关注我微信公众号: