ES的RestClient相关操作
Elasticsearch使用Java操作。
本文仅介绍CURD索引库和文档!!!
Elasticsearch基础:https://blog.csdn.net/weixin_46533577/article/details/137207222
Elasticsearch Clients官网:https://www.elastic.co/guide/en/elasticsearch/client/index.html
文档相关:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/getting-started-java.html
Java环境
规定ES版本。
<properties><java.version>1.8</java.version><!-- elasticsearch版本控制全局 --><elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
ES的版本为7.12.1。
<!--FastJson-->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.47</version>
</dependency>
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId>
</dependency>
<!-- elasticsearch -->
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
初始化RestClient
在连接开始前初始化连接对象,IP地址。
在后面关闭资源。
RestClient.builder
中可以添加多个连接,方便集群环境。
import cn.itcast.hotel.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;import java.io.IOException;public class HotelIndexTest {private RestHighLevelClient client;@BeforeEachvoid setup() throws Exception {this.client = new RestHighLevelClient(RestClient.builder((HttpHost.create("http://192.168.1.4:9200"))// 集群缓环境下可以配置多个// HttpHost.create("http://192.168.1.7:9200")));}@AfterEachvoid teardown() throws Exception {this.client.close();}
}
初始化输出
// 初始化输出
@Test
void testInit() {System.out.println(client);
}
索引库操作
查询索引库
控制台中
控制台中添加索引库通过以下方式进行,那么在Java中也需要模拟这种请求。
需要注意的是,索引库不允许修改,只能在索引库中添加新的字段,但是不能修改
# 查询索引库
GET /bunny
Java中演示
ES遵循restfull原则,所以写几个之后大致也能猜出后面怎么写了。
// 查询索引库
@Test
void getHotelIndex() throws IOException {// 1. 创建Request对象GetIndexRequest request = new GetIndexRequest("hotel");// 2. 查询索引库boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);// 输出是否删除System.out.println(exists);
}
删除索引库
控制台中
# 删除索引库
DELETE /bunny
Java中演示
// 删除索引库
@Test
void deleteHotelIndex() throws IOException {// 1. 创建Request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");// 2. 删除索引库client.indices().delete(request, RequestOptions.DEFAULT);
}
添加索引库
控制台中
# 创建索引库
PUT /bunny
{"mappings": {"properties": {"info": {"type": "text","analyzer": "ik_smart"},"email": {"type": "keyword","index": false},"name":{"type": "object","properties": {"firstName":{"type":"keyword"},"lastName":{"type":"keyword"}}}}}
}
Java中演示
为了简单测试,将JSON直接复制了。存到变量中。
// 添加索引库
@Test
void createHotelIndex() throws IOException {// 1. 创建Request对象CreateIndexRequest request = new CreateIndexRequest("hotel");// 2.准备请求参数,DSL语句request.source(HotelConstants.HOTEL_JSON, XContentType.JSON);// 3. 发送请求client.indices().create(request, RequestOptions.DEFAULT);
}
文档操作
基础结构和上面一样。
import cn.itcast.hotel.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;import java.io.IOException;public class HotelIndexTest {private RestHighLevelClient client;@BeforeEachvoid setup() throws Exception {this.client = new RestHighLevelClient(RestClient.builder((HttpHost.create("http://192.168.1.4:9200"))// 集群缓环境下可以配置多个// HttpHost.create("http://192.168.1.7:9200")));}@AfterEachvoid teardown() throws Exception {this.client.close();}
}
文档添加
控制台中
修改也是这个请求。
# 插入文档会导致版本增加
POST /bunny/_doc/1
{"info":"插入文档","email":"1@gamil.com","name":{"firstName":"舒","lastName":"纹"}
}
Java中演示
// 插入文档,记得转换成JSON对象
@Test
void testAddDocument() throws Exception {// 根据id查询酒店数据Hotel hotel = hotelService.getById(61083L);// 转换为文档类型,其中有经纬度转换HotelDoc hotelDoc = new HotelDoc(hotel);// 1. 准备Request对象IndexRequest request = new IndexRequest("hotel").id(String.valueOf(hotelDoc.getId()));// 2. 准备JSON文档request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);// 3. 发送请求client.index(request, RequestOptions.DEFAULT);
}
文档查询
控制台中
/bunny/_doc/
:参数为文档名称/文档id
# 查询文档
GET /bunny/_doc/1
Java中演示
GetRequest中传入,文档名称和文档id。
// 查询文档操作
@Test
void testGetDocuments() throws Exception {// 准备RequestGetRequest request = new GetRequest("hotel", "61083");// 发送请求GetResponse response = client.get(request, RequestOptions.DEFAULT);// 解析响应结果String json = response.getSourceAsString();System.out.println(JSON.parseObject(json, HotelDoc.class));
}
文档更新
Java中演示
request.doc中当成键值对,两两匹配。
// 更新文档
@Test
void testUpdateDocument() throws IOException {// 1. Request准备UpdateRequest request = new UpdateRequest("hotel", "61083");// 准备请求参数request.doc("price", "666","starName", "四钻");// 发送请求client.update(request, RequestOptions.DEFAULT);
}
文档删除
控制台中
/bunny/_doc/1
:文档名称/_doc/文档id
# 删除文档
DELETE /bunny/_doc/1
Java中演示
// 删除文档
@Test
void testDeleteDocument() throws IOException {// 准备RequestDeleteRequest request = new DeleteRequest("hotel", "61083");// 发送请求client.delete(request, RequestOptions.DEFAULT);
}
批量插入文档
在实际中,文档操作有时是批量的,所以将数据库中所有数据都转成文档,这时候需要遍历,需要注意的是经纬度在ES中有单独的规则,在转换时,需要将经纬度转为字符串类型。
格式为:维度,经度
,如:hotel.getLatitude() + ", " + hotel.getLongitude();
Java中演示
// 批量插入文档
@Test
void testBulkRequest() throws IOException {BulkRequest request = new BulkRequest();// 批量查询List<Hotel> hotels = hotelService.list();hotels.forEach(hotel -> {// 转换为HotelDocHotelDoc hotelDoc = new HotelDoc(hotel);// 创建文档的请求体IndexRequest source = new IndexRequest("hotel").id(hotel.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON);// 添加请求体request.add(source);});// 发送请求client.bulk(request, RequestOptions.DEFAULT);
}
otels.forEach(hotel -> {// 转换为HotelDocHotelDoc hotelDoc = new HotelDoc(hotel);// 创建文档的请求体IndexRequest source = new IndexRequest("hotel").id(hotel.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON);// 添加请求体request.add(source);});// 发送请求client.bulk(request, RequestOptions.DEFAULT);
}