import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Transport_Main01 {
public static void main(String[] args) throws IOException {
//1.实例化客户端对象 连接服务器
RestHighLevelClient client = new RestHighLevelClient(
//把HttpHost里通过构造参数赋值的属性,放入一个list,
//elasticsearch指定配置文件,ip,端口号,通信协议,创建客户端对象
RestClient.builder(new HttpHost(“39.105.189.141”,
9200,“http”)));
//2.实现操作
//新增或修改数据 如果_id存在就是跟新它,不存在就新增
//创建Student对象并传参
Student student=new Student(3,“双奔”,“man”);
//==============
IndexResponse response1=client.
//index对象设置索引名
index(new IndexRequest(“user”).//设置要操作的索引名称
//传id值再加空
id(student.getId()+"").//为_id赋值 唯一
source( //设置操作的数据源
//java对象转为JSON字符串
JSON.toJSONString(student),
//XContentType指定内容类型
XContentType.JSON),
//请求选项
//在真正发送请求之前,会先进行一次预请求
//他的作用是用于试探性的服务器响应是否正确,
RequestOptions.DEFAULT);
System.out.println(“ggg”);
//response1.status().toString() 执行状态:ok
System.out.println(response1.status().toString());
//删除
DeleteResponse response2 = client.delete(
//new DeleteRequest("索引名","id")删除索引内的指定ID
new DeleteRequest("user","2"),RequestOptions.DEFAULT);
System.err.println(response2.status().toString()+"222");
//修改
//建立Student对象,放入数据
Student student2=new Student(3,"Double Ben","WoMan");
//new UpdateRequest("索引名","id")//跟新索引内指定id
UpdateResponse response3=client.update(new UpdateRequest("user","3")
//.doc(JSON.toJSONString(student2)设置跟新的文档内容
//JSON.toJSONString(student2)将java对象转为json键值对
.doc(JSON.toJSONString(student2),XContentType.JSON),
RequestOptions.DEFAULT);
System.err.println(response3.status().toString());
//查询
GetResponse response4=client.get(new GetRequest("user","3"),RequestOptions.DEFAULT);
System.err.println(response3);
//3.关闭
client.close();
}
}