文档操作
文档CRUD
# 新增文档
POST /heima/_doc/1
{
"info": "黑马程序员Java讲师",
"email": "zy@itcast.cn",
"name": {
"firstName": "云",
"lastName": "赵"
}
}
# 查询文档
GET /heima/_doc/1
# 删除文档
DELETE /heima/_doc/1
修改
方式一:全量修改,会删除旧文档,添加新文档
方式二:增量修改,修改指定字段值
# 全量修改
PUT /heima/_doc/1
{
"info": "黑马程序员Java讲师",
"email": "ZY@itcast.cn",
"name": {
"firstName": "云",
"lastName": "赵"
}
}
#增量修改
POST /heima/_update/1
{
"doc": {
"email": "ZhaoYun@itcast.cn"
}
}
批量处理
Elasticsearch中允许通过一次请求中携带多次文档操作,也就是批量处理,语法格式如下:
POST _bulk
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_id" : "2" } }
{ "create" : { "_index" : "test", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
- index代表新增操作
- _index:指定索引库名
- _id指定要操作的文档id
- { "field1" : "value1" }:则是要新增的文档内容
- delete代表删除操作
- _index:指定索引库名
- _id指定要操作的文档id
- update代表更新操作
POST /_bulk
{"index": {"_index":"heima", "_id": "3"}}
{"info": "黑马程序员C++讲师", "email": "ww@itcast.cn", "name":{"firstName": "五", "lastName":"王"}}
{"index": {"_index":"heima", "_id": "4"}}
{"info": "黑马程序员前端讲师", "email": "zhangsan@itcast.cn", "name":{"firstName": "三", "lastName":"张"}}
#批量新增
POST /_bulk
{"index": {"_index":"heima", "_id": "3"}}
{"info": "黑马程序员C++讲师", "email": "ww@itcast.cn", "name":{"firstName": "五", "lastName":"王"}}
{"index": {"_index":"heima", "_id": "4"}}
{"info": "黑马程序员前端讲师", "email": "zhangsan@itcast.cn", "name":{"firstName": "三", "lastName":"张"}}
#批量删除
POST /_bulk
{"delete": {"_index":"heima", "_id": "3"}}
{"delete": {"_index":"heima", "_id": "4"}}
JavaRestClient
客户端初始化
1)在模块中引入es
的RestHighLevelClient
依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
2)因为SpringBoot默认的ES版本是7.17.10
,所以我们需要覆盖默认的ES版本:
<properties>
<elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
3)初始化RestHighLevelClient:
初始化的代码如下:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.21.129:9200")
));
商品Mapping映射
PUT /items
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name":{
"type": "text",
"analyzer": "ik_max_word"
},
"price":{
"type": "integer"
},
"stock":{
"type": "integer"
},
"image":{
"type": "keyword",
"index": false
},
"category":{
"type": "keyword"
},
"brand":{
"type": "keyword"
},
"sold":{
"type": "integer"
},
"commentCount":{
"type": "integer",
"index": false
},
"isAD":{
"type": "boolean"
},
"updateTime":{
"type": "date"
}
}
}
}
索引库操作
创建索引库的API如下:
代码分为三步:
- 1)创建Request对象。
- 因为是创建索引库的操作,因此Request是
CreateIndexRequest
。
- 2)添加请求参数
- 其实就是Json格式的Mapping映射参数。因为json字符串很长,这里是定义了静态字符串常量
MAPPING_TEMPLATE
,让代码看起来更加优雅。
- 3)发送请求
client.
indices
()
方法的返回值是IndicesClient
类型,封装了所有与索引库操作有关的方法。例如创建索引、删除索引、判断索引是否存在等
@Test
void testCreateIndex() throws IOException {
//1.准备Request对象
CreateIndexRequest request = new CreateIndexRequest("items");
//2.准备请求方式
request.source("MAPPING_TEMPLATE", XContentType.JSON);
//3.发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
删除索引库
@Test
void testDeleteIndex() throws IOException {
// 1.创建Request对象
DeleteIndexRequest request = new DeleteIndexRequest("items");
// 2.发送请求
client.indices().delete(request, RequestOptions.DEFAULT);
}
查询索引库
@Test
void testGetIndex() throws IOException {
// 1.创建Request对象
GetIndexRequest request = new GetIndexRequest("items");
// 2.发送请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println("exists ="+exists);
}
文档操作
新增文档JavaAPI如下:
@Test
void testIndexDoc() throws IOException {
//准备文档数据
Item item = iItemService.getById(100000011127L);
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);
}
删除文档
@Test
void testDeleteDoc() throws IOException {
//1.准备Request
DeleteRequest request = new DeleteRequest("items","100000011127L");
//2.发送请求
client.delete(request, RequestOptions.DEFAULT);
}
查询文档
@Test
void testGetDoc() throws IOException {
//1.准备Request
GetRequest request = new GetRequest("items","100000011127L");
//2.发送请求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//解析结果
String json = response.getSourceAsString();
ItemDoc doc = JSONUtil.toBean(json, ItemDoc.class);
System.out.println(doc);
}
修改文档数据有两种方式:
方式一︰全量更新。再次写入id一样的文档,就会删除旧文档,添加新文档。与新增的JavaAPI一致。
方式二︰局部更新。只更新指定部分字段。
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request
UpdateRequest request = new UpdateRequest("items", "100002644680");
// 2.准备请求参数
request.doc(
"price", 58800,
"commentCount", 1
);
// 3.发送请求
client.update(request, RequestOptions.DEFAULT);
}
批处理
- 可以看到,能添加的请求有:
- IndexRequest,也就是新增
- UpdateRequest,也就是修改
- DeleteRequest,也就是删除
@Test
void testBulk() throws IOException {
// 1.创建Request
BulkRequest request = new BulkRequest();
// 2.准备请求参数
request.add(new IndexRequest("items").id("1").source("json doc1", XContentType.JSON));
request.add(new IndexRequest("items").id("2").source("json doc2", XContentType.JSON));
// 3.发送请求
client.bulk(request, RequestOptions.DEFAULT);
}
@Test
void testLoadItemDocs() throws IOException {
// 分页查询商品数据
int pageNo = 1;
int size = 500;
while (true) {
Page<Item> page = iItemService.lambdaQuery().eq(Item::getStatus, 1).page(new Page<Item>(pageNo, size));
// 非空校验
List<Item> items = page.getRecords();
if (CollUtils.isEmpty(items)) {
return;
}
log.info("加载第{}页数据,共{}条", pageNo, items.size());
// 1.创建Request
BulkRequest request = new BulkRequest("items");
// 2.准备参数,添加多个新增的Request
for (Item item : items) {
// 2.1.转换为文档类型ItemDTO
ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
// 2.2.创建新增文档的Request对象
request.add(new IndexRequest()
.id(itemDoc.getId())
.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON));
}
// 3.发送请求
client.bulk(request, RequestOptions.DEFAULT);
// 翻页
pageNo++;
}
}