前言

最近在学习elasticsearch,所以从最简单的增删改功能开始,下面是我的版本依赖,我使用的是java17elasticsearch-java8.7spring-boot3.0

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.7.1</version>
</dependency>

静态index操作

我使用的是ElasticsearchOperations来实现,先看看基础类定义:

@Data
@Document(indexName = "index_urls", createIndex = true)
public class UrlIndex {
    private String id;

    private String uid;

    private String title;

    // 下拉提示建议使用的字段,注意:Completion类型字段,不能做筛选用
//    @CompletionField(analyzer="ik_smart",searchAnalyzer="ik_smart", maxInputLength = 100)
    private Completion suggest;

    private String url;

    private String domain;

    private String description;

    private String favicon;

    private Date createdDt;//创建时间

    private Date updatedDt;//更新时间
}

定义好之后,我们来实现增删改功能:

新增:

UrlIndex url = JSONObject.parseObject(msg, UrlIndex.class);
UrlIndex urlIndex = elasticsearchOperations.save(url);

编辑:

Url url = JSONObject.parseObject(msg, Url.class);
UrlIndex urlIndex = elasticsearchOperations.get(url.getId(), UrlIndex.class);
if (urlIndex != null) {
    urlIndex.setTitle(url.getTitle());
    // 存在即更新,,注意要设置index
    elasticsearchOperations.save(urlIndex);
}

删除:

elasticsearchOperations.delete(id, UrlIndex.class);

动态index操作

如果我们不想在实体类上添加@Document来指定index,我们如何实现呢?

@Document(indexName = "index_urls", createIndex = true)

新增:

UrlIndex url = JSONObject.parseObject(msg, UrlIndex.class);
IndexCoordinates indexCoordinates = IndexCoordinates.of("index_name");
UrlIndex urlIndex = elasticsearchOperations.save(url, indexCoordinates);

编辑:

IndexCoordinates indexCoordinates = IndexCoordinates.of("index_name");
UrlIndex resUrl = JSONObject.parseObject(msg, UrlIndex.class);
// 通过get查询出es数据,注意要设置index
UrlIndex urlIndex = elasticsearchOperations.get(resUrl.getId(), UrlIndex.class, indexCoordinates);
if (urlIndex != null) {
    urlIndex.setTitle(resUrl.getTitle());
    urlIndex.setSuggest(resUrl.getSuggest());

    // 存在即更新,,注意要设置index
    elasticsearchOperations.save(urlIndex, indexCoordinates);
}

删除:

IndexCoordinates indexCoordinates = IndexCoordinates.of("index_name");
elasticsearchOperations.delete(msg, indexCoordinates);

总结

1、在实体类上通过设置@Document(indexName = "index_urls", createIndex = true)就可以实现索引就可以完成增删改功能
2、但是如果你使用动态索引,则要指定你的索引名
3、我使用的是ElasticsearchOperations当然还有其它的实现方式,如EnableElasticsearchRepositories


Awbeci
3.1k 声望212 粉丝

Awbeci