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可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
目录
相关文章
|
10天前
|
JSON Java 网络架构
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
这篇文章介绍了如何使用Spring Boot整合REST方式来搭建和操作Elasticsearch服务。
74 4
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
|
9天前
|
JavaScript 前端开发 Java
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
这篇文章详细介绍了如何在前端Vue项目和后端Spring Boot项目中通过多种方式解决跨域问题。
175 1
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
|
4天前
|
JavaScript Java 关系型数据库
自主版权的Java诊所管理系统源码,采用Vue 2、Spring Boot等技术栈,支持二次开发
这是一个自主版权的Java诊所管理系统源码,支持二次开发。采用Vue 2、Spring Boot等技术栈,涵盖患者管理、医生管理、门诊管理、药店管理、药品管理、收费管理、医保管理、报表统计及病历电子化等功能模块。
|
26天前
|
Java Linux
java读取linux服务器下某文档的内容
java读取linux服务器下某文档的内容
31 3
java读取linux服务器下某文档的内容
|
29天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
基于Java+Springboot+Vue开发的大学竞赛报名管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的大学竞赛报名管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
128 3
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
|
10天前
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
103 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
10天前
|
自然语言处理 Java Maven
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
这篇博客介绍了如何使用Spring Boot整合TransportClient搭建Elasticsearch服务,包括项目创建、Maven依赖、业务代码和测试示例。
34 0
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
|
29天前
|
JSON NoSQL Java
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
这篇文章介绍了在Java中使用Redis客户端的几种方法,包括Jedis、SpringDataRedis和SpringBoot整合Redis的操作。文章详细解释了Jedis的基本使用步骤,Jedis连接池的创建和使用,以及在SpringBoot项目中如何配置和使用RedisTemplate和StringRedisTemplate。此外,还探讨了RedisTemplate序列化的两种实践方案,包括默认的JDK序列化和自定义的JSON序列化,以及StringRedisTemplate的使用,它要求键和值都必须是String类型。
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
|
17天前
|
自然语言处理 搜索推荐 Java
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(一)
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图
37 0
|
17天前
|
存储 自然语言处理 搜索推荐
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(二)
SpringBoot 搜索引擎 海量数据 Elasticsearch-7 es上手指南 毫秒级查询 包括 版本选型、操作内容、结果截图(二)
22 0