【Elasticsearch入门到落地】12、索引库删除判断以及文档增删改查

接上篇《11、RestClient初始化索引库
上一篇我们完成了使用RestHighLevelClient创建索引库的代码实现,本篇将讲解如何判断索引库是否存在并删除它,以及如何对索引库中的文档进行增删改查操作。

一、索引库判断与删除

在操作索引库时,有时需要先判断索引库是否存在,若存在则进行删除操作。以下是具体的实现代码:

1. 判断索引库是否存在

@Test
void testExistsIndex() throws IOException {
    // 1. 准备Request
    GetIndexRequest request = new GetIndexRequest("hotel");
    // 2. 发送请求
    boolean isExists = client.indices().exists(request, RequestOptions.DEFAULT);
 
    System.out.println(isExists ? "索引库存在" : "索引库不存在");
}

代码解析:
GetIndexRequest 是 Elasticsearch 提供的用于判断索引库是否存在的请求类。
调用 client.indices().exists() 方法发送请求,并返回一个布尔值,表示索引库是否存在。
异常处理:如果索引库名称格式错误,可能会抛出 IllegalArgumentException。

2. 删除索引库

@Test
void testDeleteIndex() throws IOException {
    // 1. 准备Request
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    // 2. 发送请求
    client.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println("索引库删除成功");
}

代码解析:
DeleteIndexRequest 是 Elasticsearch 提供的用于删除索引库的请求类。
调用 client.indices().delete() 方法发送请求。
异常处理:如果索引库不存在,可能会抛出 IndexNotFoundException。

二、文档的增删改查

1. 添加文档

@Test
void testAddDocument() throws IOException {
    // 1. 查询数据库hotel数据
    Hotel hotel = hotelService.getById(61083L);
    // 2. 转换为HotelDoc
    HotelDoc hotelDoc = new HotelDoc(hotel);
    // 3. 转JSON
    String json = JSON.toJSONString(hotelDoc);
 
    // 1. 准备Request
    IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
    // 2. 准备请求参数DSL,其实就是文档的JSON字符串
    request.source(json, XContentType.JSON);
    // 3. 发送请求
    client.index(request, RequestOptions.DEFAULT);
    System.out.println("文档添加成功");
}

代码解析:
IndexRequest 是 Elasticsearch 提供的用于添加文档的请求类。
调用 client.index() 方法发送请求。
异常处理:如果索引库不存在,可能会抛出 IndexNotFoundException。Hotel和HotelDoc实体代码:

package cn.itcast.hotel.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("tb_hotel")
public class Hotel {
    @TableId(type = IdType.INPUT)
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String longitude;
    private String latitude;
    private String pic;
}
package cn.itcast.hotel.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;
    private Object distance;
    private Boolean isAD;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}

2. 根据ID查询文档

@Test
void testGetDocumentById() throws IOException {
    // 1. 准备Request      // GET /hotel/_doc/{id}
    GetRequest request = new GetRequest("hotel", "61083");
    // 2. 发送请求
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    // 3. 解析响应结果
    String json = response.getSourceAsString();
 
    HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
    System.out.println("hotelDoc = " + hotelDoc);
}

代码解析:
GetRequest 是 Elasticsearch 提供的用于查询文档的请求类。
调用 client.get() 方法发送请求,并返回 GetResponse 对象。
使用 response.getSourceAsString() 获取文档的 JSON 字符串。
异常处理:如果文档不存在,response.isExists() 将返回 false。

3. 根据ID删除文档

@Test
void testDeleteDocumentById() throws IOException {
    // 1. 准备Request      // DELETE /hotel/_doc/{id}
    DeleteRequest request = new DeleteRequest("hotel", "61083");
    // 2. 发送请求
    client.delete(request, RequestOptions.DEFAULT);
    System.out.println("文档删除成功");
}

代码解析:
DeleteRequest 是 Elasticsearch 提供的用于删除文档的请求类。
调用 client.delete() 方法发送请求。
异常处理:如果文档不存在,可能会抛出 DocumentMissingException。

4. 根据ID更新文档

@Test
void testUpdateById() throws IOException {
    // 1. 准备Request
    UpdateRequest request = new UpdateRequest("hotel", "61083");
    // 2. 准备参数
    request.doc(
            "price", "870"
    );
    // 3. 发送请求
    client.update(request, RequestOptions.DEFAULT);
    System.out.println("文档更新成功");
}

代码解析:
UpdateRequest 是 Elasticsearch 提供的用于更新文档的请求类。
调用 request.doc() 方法设置更新的字段和值。
调用 client.update() 方法发送请求。
异常处理:如果文档不存在,可能会抛出 DocumentMissingException。

5. 批量操作

@Test
void testBulkRequest() throws IOException {
    // 查询所有的酒店数据
    List<Hotel> list = hotelService.list();
 
    // 1. 准备Request
    BulkRequest request = new BulkRequest();
    // 2. 准备参数
    for (Hotel hotel : list) {
        // 2.1. 转为HotelDoc
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 2.2. 转json
        String json = JSON.toJSONString(hotelDoc);
        // 2.3. 添加请求
        request.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(json, XContentType.JSON));
    }
 
    // 3. 发送请求
    client.bulk(request, RequestOptions.DEFAULT);
    System.out.println("批量操作成功");
}

代码解析:
BulkRequest 是 Elasticsearch 提供的用于批量操作的请求类。
调用 request.add() 方法添加多个子请求(如添加、更新、删除)。
调用 client.bulk() 方法发送批量请求。
异常处理:如果批量操作中某个请求失败,可能会抛出 BulkItemResponse.Failure 异常。

三、什么是 RequestOptions.DEFAULT?

RequestOptions.DEFAULT 是 Elasticsearch 提供的默认请求选项,表示使用默认的配置参数发送请求。例如:

●默认的超时时间。
●默认的认证信息(如果需要)。
●默认的请求头信息。

如果需要自定义请求选项,可以通过 RequestOptions.Builder 创建,例如:

RequestOptions options = RequestOptions.DEFAULT.toBuilder()
        .addHeader("Custom-Header", "value")
        .build();

四、完整测试类

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
class HotelDocumentTest {

    private RestHighLevelClient client;

    @Autowired
    private IHotelService hotelService;

    @Test
    void testAddDocument() throws IOException {
        // 1.查询数据库hotel数据
        Hotel hotel = hotelService.getById(61083L);
        // 2.转换为HotelDoc
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 3.转JSON
        String json = JSON.toJSONString(hotelDoc);

        // 1.准备Request
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        // 2.准备请求参数DSL,其实就是文档的JSON字符串
        request.source(json, XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        // 1.准备Request      // GET /hotel/_doc/{id}
        GetRequest request = new GetRequest("hotel", "61083");
        // 2.发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析响应结果
        String json = response.getSourceAsString();

        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println("hotelDoc = " + hotelDoc);
    }

    @Test
    void testDeleteDocumentById() throws IOException {
        // 1.准备Request      // DELETE /hotel/_doc/{id}
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

    @Test
    void testUpdateById() throws IOException {
        // 1.准备Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        // 2.准备参数
        request.doc(
                "price", "870"
        );
        // 3.发送请求
        client.update(request, RequestOptions.DEFAULT);
    }

    @Test
    void testBulkRequest() throws IOException {
        // 查询所有的酒店数据
        List<Hotel> list = hotelService.list();

        // 1.准备Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数
        for (Hotel hotel : list) {
            // 2.1.转为HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 2.2.转json
            String json = JSON.toJSONString(hotelDoc);
            // 2.3.添加请求
            request.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(json, XContentType.JSON));
        }

        // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.2.129:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}        

五、数据库查询机制解释

这里给不了解mybatis-plus-extension-3.4.2的同学解释一下,为什么直接用hotelService.getById就可以查询数据库数据了。首先看一下hotelService和其实现类代码:

package cn.itcast.hotel.service;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import com.baomidou.mybatisplus.extension.service.IService;

public interface IHotelService extends IService<Hotel> {
    PageResult search(RequestParams params);
}
package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备请求参数
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            // 2.3.距离排序
            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }
            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索数据失败", e);
        }
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1.关键字搜索,match查询,放到must中
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 不为空,根据关键字查询
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            // 为空,查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        // 1.2.品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3.城市
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        // 1.4.星级
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        // 1.5.价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        // 2.算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery, // 原始查询,boolQuery
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ // function数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), // 过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(10) // 算分函数
                        )
                }
        );

        // 3.设置查询条件
        request.source().query(functionScoreQuery);
    }

    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            // 4.4.获取source
            String json = hit.getSourceAsString();
            // 4.5.反序列化,非高亮的
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 4.6.处理高亮结果
            // 1)获取高亮map
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2)根据字段名,获取高亮结果
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    // 3)获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4)把高亮结果放到HotelDoc中
                    hotelDoc.setName(hName);
                }
            }
            // 4.8.排序信息
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }

            // 4.9.放入集合
            hotels.add(hotelDoc);
        }
        return new PageResult(total, hotels);
    }
}

然后是HotelMapper的代码:

package cn.itcast.hotel.mapper;

import cn.itcast.hotel.pojo.Hotel;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface HotelMapper extends BaseMapper<Hotel> {
}

这里为什么我们不需要在hotelService的实现类中再去写HotelMapper的getById代码,类似如下:

@Service
public class HotelServiceImpl implements HotelService {
    
    @Autowired
    private HotelMapper hotelMapper;

    @Test
    public void testSelectById(Serializable id) {
        Hotel hotel = hotelMapper.selectById(id);
        System.out.println(hotel);
    }
}

而是直接在其他测试类中直接可以调用hotelService.getById呢?这是因为当HotelService同时继承ServiceImpl<HotelMapper, Hotel> 并实现 HotelService接口时,大部分基础CRUD操作的实现确实不需要再手动编写了。原因如下:
​​1、ServiceImpl已提供默认实现​​
ServiceImpl是MyBatis-Plus提供的通用服务实现类,它已经实现了IService接口中的所有基础方法(如save、remove、update、getById、list等)。这些方法通过泛型HotelMapper直接调用底层Mapper的CRUD操作。
​2、继承关系的作用​​
IHotelService接口继承IService<Hotel>:定义了服务层的契约方法(包括MyBatis-Plus提供的通用方法和自定义业务方法)。
ServiceImpl<HotelMapper, Hotel>:通过泛型绑定了具体的Mapper(HotelMapper)和实体类(Hotel),并自动注入baseMapper(即HotelMapper实例),直接复用其CRUD能力。
​​3、无需重复编写的场景​​
如果业务仅需基础增删改查(如getById、save等),直接继承ServiceImpl后,这些方法已默认实现,无需在 HotelServiceImpl中重写。例如:

@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> 
                           implements HotelService {
    // 无需实现 getById(),直接继承父类的默认实现
}

​4、仍需自定义的场景​​
若需扩展复杂业务逻辑(如多表关联查询、特殊条件更新),仍需在HotelServiceImpl中重写或新增方法。例如:

@Override
public Hotel getHotelWithOtherCondition(String condition) {
    // 自定义逻辑需手动实现
}

​​总结​​:继承ServiceImpl后,基础CRUD方法由MyBatis-Plus自动提供,开发者只需关注自定义业务逻辑即可,这是MyBatis-Plus设计的重要优势——减少重复代码,提升开发效率。

六、总结

1. 新增文档 (Create)

​​Request:​​ IndexRequest
​​(1)参数:​​
索引名 (必填)
文档ID (可选,不填会自动生成)
文档内容 (JSON格式)
(2)请求创建代码

IndexRequest request = new IndexRequest("索引名")
    .id("文档ID")  // 可选
    .source(JSON数据, XContentType.JSON);

(3)执行代码

client.index(request, RequestOptions.DEFAULT);

2. 查询文档 (Read)

​​Request:​​ GetRequest
​​(1)参数:​​
索引名 (必填)
文档ID (必填)
(2)请求创建代码

GetRequest request = new GetRequest("索引名", "文档ID");

(3)执行代码

client.get(request, RequestOptions.DEFAULT);

3. 更新文档 (Update)

​​Request:​​ UpdateRequest
​​(1)参数:​​
索引名 (必填)
文档ID (必填)
要更新的字段 (Map或键值对形式)
(2)请求创建代码

UpdateRequest request = new UpdateRequest("索引名", "文档ID")
    .doc("字段1", "值1", "字段2", "值2");  // 部分更新

(3)执行代码

client.update(request, RequestOptions.DEFAULT);

4. 删除文档 (Delete)

​​Request:​​ DeleteRequest
​​(1)参数:​​
索引名 (必填)
文档ID (必填)
(2)请求创建代码

DeleteRequest request = new DeleteRequest("索引名", "文档ID");

(3)执行代码

client.delete(request, RequestOptions.DEFAULT);

5. 批量操作 (Bulk)

​​Request:​​ BulkRequest
​​(1)参数:​​
可添加多个Index/Update/Delete请求
(2)请求创建代码

BulkRequest request = new BulkRequest()
    .add(new IndexRequest(...))  // 批量新增
    .add(new UpdateRequest(...)) // 批量更新
    .add(new DeleteRequest(...));// 批量删除

(3)执行代码

//client为RestHighLevelClient
client.bulk(request, RequestOptions.DEFAULT);    

下一篇我们将讲解如何使用Elasticsearch的查询DSL实现复杂的搜索功能。

转载请注明出处:https://blog.csdn.net/acmman/article/details/147719492

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光仔December

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值