Elasticsearch(二)
什么是RestClient
ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过htp请求发送给ES。官方文档地址:https://www.elastic,co/guide/en/elasticsearch/client/index.html
分析数据结构
mapping要考虑的问题:
字段名、数据类型、是否参与搜索、是否发词、如果分词,分词器是什么?
比如用下图这张表进行分析:
地理坐标
在查询的过程中即想用多个字段搜,又想效率高,我们可以用copy_to来实现
初始化RestClient
引入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
初始化
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://127.0.0.1:9200")
));
创建索引库
代码实现:
@Test
void name() throws IOException {
// 1.创建Request对象
CreateIndexRequest request = new CreateIndexRequest("hotel");
// 2.准备请求的参数:DSL语句
request.source(MAPPING_TEMP, XContentType.JSON);
// 3.发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
删除索引库和判断索引库是否存在
删除索引库
/**
* 删除索引库
*/
@Test
void deleteIndex() throws IOException {
// 1.创建Request对象
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
// 2.发送请求
client.indices().delete(request, RequestOptions.DEFAULT);
}
判断索引库是否存在
/**
* 判断索引库是否存在
*/
@Test
void existIndex() throws IOException {
// 1.创建Request对象
GetIndexRequest request = new GetIndexRequest("hotel");
// 2.发送请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
// 3.输出
System.out.println(exists);
}
利用JavaRestClient实现文档的CRUD
添加数据到索引库
/**
* 新增
*/
@Test
void insertDocument() throws IOException {
// 根据id查询
Hotel hotel = iHotelService.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);
}
根据id查询数据
/**
* 根据id查询
*/
@Test
void getDocumentById() throws IOException {
// 创建Request对象
GetRequest request = new GetRequest("hotel", "61083");
// 发送请求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 解析结果
String json = response.getSourceAsString();
System.out.println(json);
}
更新文档数据
/**
* 局部更新
*/
@Test
void updateDocumentById() throws IOException {
// 1.创建Request对象
UpdateRequest request = new UpdateRequest("hotel", "61083");
// 2.准备参数
request.doc(
"business", "123",
"city", "济南"
);
// 3.更新文档
client.update(request, RequestOptions.DEFAULT);
}
删除文档
/**
* 删除文档
*/
@Test
void deleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("hotel", "61083");
client.delete(request, RequestOptions.DEFAULT);
}
批量导入文档数据
/**
* 批量导入
*/
@Test
void importData() throws IOException {
List<Hotel> list = iHotelService.list();
// 创建bulk请求
BulkRequest request = new BulkRequest();
// 添加要批量提交的请求
for (Hotel hotel : list) {
HotelDoc hotelDoc = new HotelDoc(hotel);
request.add(new IndexRequest("hotel").id(String.valueOf(hotelDoc.getId())).source(JSON.toJSONString(hotelDoc), XContentType.JSON));
}
// 发送bulk请求
client.bulk(request, RequestOptions.DEFAULT);
}