将数据库中的信息导入elasticsearch中
以商品数据为例
定义一个索引库结构对应的实体。
@Data
@ApiModel(description = "索引库实体")
public class ItemDoc{
@ApiModelProperty("商品id")
private String id;
@ApiModelProperty("商品名称")
private String name;
@ApiModelProperty("价格(分)")
private Integer price;
@ApiModelProperty("商品图片")
private String image;
@ApiModelProperty("类目名称")
private String category;
@ApiModelProperty("品牌名称")
private String brand;
@ApiModelProperty("销量")
private Integer sold;
@ApiModelProperty("评论数")
private Integer commentCount;
@ApiModelProperty("是否是推广广告,true/false")
private Boolean isAD;
@ApiModelProperty("更新时间")
private LocalDateTime updateTime;
}
新增文档的请求语法如下:
POST /{索引库名}/_doc/1
{
"name": "Jack",
"age": 21
}
对应的JavaAPI如下:
@Test
void createIndex() throws IOException {
//1.准备文档
Item item = itemService.getById("4294760");
log.info(item.getId().toString());
ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
//1.准备Request
IndexRequest request = new IndexRequest("items").id(itemDoc.getId());
//2.准备请求参数
request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
//3.发送请求
client.index(request,RequestOptions.DEFAULT);
}
导入商品数据,还需要做几点准备工作:
可以看到与索引库操作的API非常类似,同样是三步走:
我们以根据id查询文档为例
查询的请求语句如下:
GET /{索引库名}/_doc/{id}
与之前的流程类似,代码大概分2步:
响应结果是一个JSON,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为Java对象即可。
其它代码与之前类似,流程如下:
@Test
void getIndex() throws IOException {
//1.准备Request
GetRequest request = new GetRequest("items","4294760");
//2.发送请求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//3.解析结果
ItemDoc bean = JSONUtil.toBean(response.getSourceAsString(), ItemDoc.class);
log.info(bean.toString());
}
删除的请求语句如下:
DELETE /hotel/_doc/{id}
与查询相比,仅仅是请求方式从DELETE变成GET,可以想象Java代码应该依然是2步走:
在item-service的DocumentTest测试类中,编写单元测试:
@Test
void testDeleteDocument() throws IOException {
// 1.准备Request,两个参数,第一个是索引库名,第二个是文档id
DeleteRequest request = new DeleteRequest("items", "4294760");
// 2.发送请求
client.delete(request, RequestOptions.DEFAULT);
}
修改我们讲过两种方式:
在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:
这里不再赘述,我们主要关注局部修改的API即可。
局部修改的请求语法如下:
POST /{索引库名}/_update/{id}
{
"doc": {
"字段名": "字段值",
"字段名": "字段值"
}
}
与之前类似,也是三步走:
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request
UpdateRequest request = new UpdateRequest("items", "4294760");
// 2.准备请求参数
request.doc(
"price", 58800,
"commentCount", 1
);
// 3.发送请求
client.update(request, RequestOptions.DEFAULT);
}
批处理与前面讲的文档的CRUD步骤基本一致:
BulkRequest本身其实并没有请求参数,其本质就是将多个普通的CRUD请求组合在一起发送。例如:
@Test
void testBulkIndex() throws IOException {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("items","4294760"));
// ...省略重复操作
request.add(new DeleteRequest("items", "429476X"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
}
文档操作的基本步骤: