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

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 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());
}
相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
目录
相关文章
|
28天前
|
Java 开发者 Spring
java springboot监听事件和处理事件
通过上述步骤,开发者可以在Spring Boot项目中轻松实现事件的发布和监听。事件机制不仅解耦了业务逻辑,还提高了系统的可维护性和扩展性。掌握这一技术,可以显著提升开发效率和代码质量。
90 33
|
16天前
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
41 6
|
20天前
|
Java 应用服务中间件 API
【潜意识Java】javaee中的SpringBoot在Java 开发中的应用与详细分析
本文介绍了 Spring Boot 的核心概念和使用场景,并通过一个实战项目演示了如何构建一个简单的 RESTful API。
37 5
|
20天前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
36 2
|
30天前
|
Java 开发者 Spring
java springboot监听事件和处理事件
通过上述步骤,开发者可以在Spring Boot项目中轻松实现事件的发布和监听。事件机制不仅解耦了业务逻辑,还提高了系统的可维护性和扩展性。掌握这一技术,可以显著提升开发效率和代码质量。
65 13
|
20天前
|
监控 Java API
【潜意识Java】使用SpringBoot构建高效的RESTfulAPI
本文介绍了使用Spring Boot构建RESTful API的完整流程,涵盖从项目创建到API测试的各个步骤。
38 1
|
1月前
|
Java Spring
Java Spring Boot监听事件和处理事件
通过上述步骤,我们可以在Java Spring Boot应用中实现事件的发布和监听。事件驱动模型可以帮助我们实现组件间的松耦合,提升系统的可维护性和可扩展性。无论是处理业务逻辑还是系统事件,Spring Boot的事件机制都提供了强大的支持和灵活性。希望本文能为您的开发工作提供实用的指导和帮助。
93 15
|
Java
Java计算机IT编程文档常见单词翻译(四)
Java计算机IT编程文档常见单词翻译(四)
128 0
Java计算机IT编程文档常见单词翻译(四)
|
Java
Java计算机IT编程文档常见单词翻译(三)
Java计算机IT编程文档常见单词翻译(三)
119 0
Java计算机IT编程文档常见单词翻译(三)
|
Java
Java计算机IT编程文档常见单词翻译(二)
Java计算机IT编程文档常见单词翻译(二)
120 0
Java计算机IT编程文档常见单词翻译(二)