ElasticSearch 实现分词全文检索 - Java SpringBoot ES 文档操作

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: ElasticSearch 实现分词全文检索 - Java SpringBoot ES 文档操作

Pom文件添加依赖包

<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.9.3</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.10</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

创建索引

@Test
void createIndex() throws Exception{
    String indexName="person";
    RestHighLevelClient client = ESClient.getClient();
    //1. 准备索引的 settings
    Settings.Builder settings = Settings.builder()
            .put("number_of_shards", 3)
            .put("number_of_replicas", 1);
    //2. 准备索引的结构 Mappings
    XContentBuilder mappings = JsonXContent.contentBuilder()
            .startObject()
                .startObject("properties")
                    .startObject("name")
                        .field("type","text")
                    .endObject()
                    .startObject("age")
                        .field("type","integer")
                    .endObject()
                    .startObject("birthday")
                        .field("type","date")
                        .field("format","yyyy-MM-dd")
                    .endObject()
                .endObject()
            .endObject();
    //3. 将 Settings 和 Mappings 封装到一个Request 对象中
    CreateIndexRequest request = new CreateIndexRequest(indexName)
            .settings(settings)
            .mapping(mappings);
    //4. 通过 client 对象去连接ES并执行创建索引
    CreateIndexResponse resp = client.indices().create(request, RequestOptions.DEFAULT);
    //5. 输出
    System.out.println("resp:"+resp.toString());
}

Person 实体类

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Date;
public class Person {
    @JsonIgnore
    private  Integer id;
    private  String name;
    private  Integer age;
    private Date birthday;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

创建文档

@Test
void createDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备一个JSON数据
    Person person = new Person();
    person.setId(1);
    person.setName("张三");
    person.setAge(23);
    person.setBirthday(DateUtil.date());
    String personJson = JSON.toJSONStringWithDateFormat(person, "yyyy-MM-dd"); //FastJson 将日期格式化
    //准备一个Request对象
    IndexRequest request = new IndexRequest(indexName);
    request.id(person.getId().toString()); //手动指定ID
    request.source(personJson, XContentType.JSON);
    
    //通过 Client 对象执行添加
    IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
    //输入结果
    System.out.println(resp.getResult().toString());
}

修改文档

@Test
void updateDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //创建一个MAP,指定需要修改的内容
    Map<String, Object> doc = new HashMap<>();
    doc.put("name", "张三丰");
    String docId = "1";
    //创建Request对象,封装数据
    UpdateRequest request = new UpdateRequest(indexName,docId);
    request.doc(doc);
    //通过client对象执行
    UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
    //输入结果
    System.out.println(update.getResult().toString());
}

删除文档

@Test
void delete() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备 request 对象
    DeleteRequest request = new DeleteRequest(indexName, "1");
    //通过client去操作
    DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
    System.out.println("delete => " + delete);
}

批量添加

@Test
void batchCreateDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备一个JSON数据
    Person p1 = new Person();
    p1.setId(1);
    p1.setName("张三");
    p1.setAge(23);
    p1.setBirthday(DateUtil.date());
    String personJson1 = JSON.toJSONStringWithDateFormat(p1, "yyyy-MM-dd"); //FastJson 将日期格式化
    Person p2 = new Person();
    p2.setId(2);
    p2.setName("李四");
    p2.setAge(23);
    p2.setBirthday(DateUtil.date());
    String personJson2 = JSON.toJSONStringWithDateFormat(p2, "yyyy-MM-dd"); //FastJson 将日期格式化
    Person p3 = new Person();
    p3.setId(3);
    p3.setName("王五");
    p3.setAge(23);
    p3.setBirthday(DateUtil.date());
    String personJson3 = JSON.toJSONStringWithDateFormat(p3, "yyyy-MM-dd"); //FastJson 将日期格式化
    //准备一个Request对象
    BulkRequest bulkRequest = new BulkRequest();
    IndexRequest request1 = new IndexRequest(indexName)
            .id(p1.getId().toString()) //手动指定ID
            .source(personJson1, XContentType.JSON);
    IndexRequest request2 = new IndexRequest(indexName)
            .id(p2.getId().toString()) //手动指定ID
            .source(personJson2, XContentType.JSON);
    IndexRequest request3 = new IndexRequest(indexName)
            .id(p3.getId().toString()) //手动指定ID
            .source(personJson3, XContentType.JSON);
    bulkRequest.add(request1);
    bulkRequest.add(request2);
    bulkRequest.add(request3);
    //通过 Client 对象执行添加
    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    //输入结果
    System.out.println(bulk.toString());
}

批量删除

@Test
void batchDelete() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备 request 对象
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.add(new DeleteRequest(indexName, "1"));
    bulkRequest.add(new DeleteRequest(indexName, "2"));
    //通过client去操作
    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println("delete => " + bulk.toString());
}
相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
目录
相关文章
|
Java Maven 开发工具
【ElasticSearch 】IK 分词器安装
【ElasticSearch 】IK 分词器安装
637 1
|
Java 索引
SpringBoot2.3.x整合ElasticSearch7.6.2 实现PDF,WORD全文检索
本文使用SpringBoot2.3.x + ElasticSearch7.6.2 实现对PDF,WORD进行全文检索 实现了对文件内容快速搜索
1501 0
SpringBoot2.3.x整合ElasticSearch7.6.2 实现PDF,WORD全文检索
|
2月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
725 0
|
1月前
|
缓存 人工智能 NoSQL
Java中实现Token设置过期时间的方法
本文介绍了在Java应用中实现Token设置过期时间的多种方法,包括使用JWT和Redis缓存,并结合定时任务清理过期Token,以提升系统安全性与用户隐私保护。
240 0
|
自然语言处理 Java 关系型数据库
ElasticSearch 实现分词全文检索 - SpringBoot 完整实现 Demo 附源码【完结篇】
ElasticSearch 实现分词全文检索 - SpringBoot 完整实现 Demo 附源码【完结篇】
264 0
|
搜索推荐 Java 数据库
springboot集成ElasticSearch的具体操作(系统全文检索)
springboot集成ElasticSearch的具体操作(系统全文检索)
|
11月前
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
691 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
SQL JSON Java
一些异常及解决方法记录(持续更新)
一些异常及解决方法记录(持续更新)
808 0
|
11月前
|
自然语言处理 搜索推荐 Java
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(一)
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图
222 0
|
Docker 容器
docker desktop安装es并连接elasticsearch-head:5
以上就是在Docker Desktop上安装Elasticsearch并连接Elasticsearch-head:5的步骤。
532 2