Java做客户端对Elasticsearch服务的一些操作(一)
程序员文章站
2024-03-26 09:10:41
...
一.ES服务器操作工具类
package com.east.common;
import java.io.IOException;
import java.net.InetAddress;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
/**
* ES服务器操作工具类
* @author lhy
* @date 2018.03.20
*/
public class EsUtil {
private Client client;
private static String name = "127.0.0.1";
private static Integer port = 9300;
private static ObjectMapper objectMapper = new ObjectMapper();
static Settings set = Settings.builder().put("cluster.name", "elasticsearch").build();
//.put("client.transport.sniff",false).
/**
* 本地客户端连接ES服务器
* @return
*/
public static Client EsConnect(){
TransportClient client = null;
try {
client = new PreBuiltTransportClient(set)
.addTransportAddress(new TransportAddress(InetAddress.getByName(name), port));
System.out.println("ES服务器连接成功!");
return client;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("ES服务器连接失败!");
e.printStackTrace();
}
return client;
}
/**
* 关闭ES连接的客户端
* @param client
*/
public static void closeClient(Client client){
if(client != null){
client.close();
System.out.println("Client已关闭!");
}
}
/**
* 使用jackson定义了一个将对象转化成json的工具类
* @param obj
* @return
*/
public static String toJson(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
二.实体对象
package com.east.entity;
public class Student {
private Integer id;
private String name;
private String age;
private String sex;
private String tel;
private String score;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
三.结构化创建索引的mapping
package com.east.entity;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
/**
* 结构化创建索引的mapping
* @author lhy
* @date 2018.03.20
*/
public class StructCreate {
public static XContentBuilder getMapping() throws Exception {
XContentBuilder map = XContentFactory.jsonBuilder().startObject().startObject("student")
.startObject("properties")
.startObject("id").field("type", "number").field("store", "yes").endObject()
.startObject("name").field("type", "string").field("store", "yes").endObject()
.startObject("age").field("type", "string").field("store", "yes").endObject()
.startObject("sex").field("type", "string").field("store", "yes").endObject()
.startObject("tel").field("type", "string").field("store", "yes").endObject()
.startObject("score").field("type", "string").field("store", "yes").endObject()
.endObject().endObject().endObject();
return map;
}
}
四.添加索引
package com.east.operation;
import java.util.Random;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import com.east.common.EsUtil;
import com.east.entity.StructCreate;
import com.east.entity.Student;
/**
* 添加索引
* @author lhy
* @date 2018.03.20
*/
public class AddIndex {
private Client client;
public AddIndex(Client client) {
super();
this.client = client;
}
/**
* 添加一般的索引
*/
public void AddIndexFirst(Student stu){
String jsonData = EsUtil.toJson(stu);
System.out.println("封装的json:"+jsonData);
IndexResponse res = client.prepareIndex().setIndex("student").setType("student01").setId("3")
.setSource(jsonData, XContentType.JSON).execute().actionGet();
System.out.println("索引创建成功,版本号为: " + res.getVersion());
}
/**
* 创建结构化索引
* @throws Exception
*/
public void StructAddIndex() throws Exception{
//首先创建索引库
CreateIndexResponse indexResponse = EsUtil.EsConnect().admin().indices()
.prepareCreate("student").execute().actionGet();
//如果是在两台机器上,下面直接putMapping可能会报异常
PutMappingRequestBuilder builder = client.admin().indices().preparePutMapping("student");
// StructCreate 就像当于数据的 table
builder.setType("stu08");
XContentBuilder map = StructCreate.getMapping();
builder.setSource(map);
PutMappingResponse response = builder.execute().actionGet();
System.out.println(response.isAcknowledged());
}
}
五.删除索引
package com.east.operation;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.Client;
/**
* 删除索引
* @author lhy
* @date 2018.03.20
*/
public class DelIndex {
private Client client;
public DelIndex(Client client) {
super();
this.client = client;
}
public void del(){
DeleteResponse res = client.prepareDelete().setIndex("student")
.setType("student01").setId("2").execute().actionGet();
System.out.println("删除成功!");
}
}
六.简单查询索引
package com.east.operation;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
/**
* 简单的索引查询
* @author lhy
* @date 2018.03.20
*/
public class SimpleQuery {
private Client client;
public SimpleQuery(Client client) {
super();
this.client = client;
}
public void getIndex(){
GetResponse res = client.prepareGet().setIndex("student")
.setType("student01").setId("3").execute().actionGet();
System.out.println(res.getSource());
}
}
七.索引操作测试
package com.east.test;
import java.util.Random;
import org.elasticsearch.client.Client;
import com.east.common.EsUtil;
import com.east.entity.Student;
import com.east.operation.AddIndex;
import com.east.operation.DelIndex;
import com.east.operation.SimpleQuery;
public class EsTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Client client = EsUtil.EsConnect();
/**
* 1.添加索引
*/
AddIndex add = new AddIndex(client);
Student stu = new Student();
Integer random = new Random().nextInt(20);
stu.setId(random);;
stu.setName("杨旭"+random);
stu.setAge("22");
if(random%2==0){
stu.setSex("男");
}else{
stu.setSex("女");
}
stu.setTel("12345678");
stu.setScore("88");
add.AddIndexFirst(stu);
/**
* 2.创建结构化索引
*/
add.StructAddIndex();
/**
* 3.查询索引
*/
SimpleQuery query = new SimpleQuery(client);
query.getIndex();
/**
* 4.删除索引
*/
DelIndex del = new DelIndex(client);
del.del();
}
}
下一篇: SpringSecurity--记住我