首页 > 其他分享 >SpringBoot整合ElasticSearch

SpringBoot整合ElasticSearch

时间:2024-08-11 18:53:44浏览次数:9  
标签:SpringBoot boot springframework ElasticSearch elasticsearch 整合 org import data

文章目录

Spring Boot整合ES

官方文档:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#new-features.4-4-0

版本选择

Elasticsearch 7.17.3 对应依赖 Spring Data Elasticsearch 4.4.x,对应springboot版本2.7.x

版本对应关系

在这里插入图片描述



引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>

    <spring-boot.version>2.7.13</spring-boot.version>
    <lombok.version>1.18.16</lombok.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>



    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>



yum配置

spring:
  elasticsearch:
    uris: http://localhost:9200
    connection-timeout: 3s



创建实体

@Document(indexName = "employees") 指定索引名,注意这里@Document是es包下的注解,不要导入错了

Field指定字段类型以及分词器,它是es包下的注解,不要导入错了

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @Description: 索引为sys_user的实体
 * @Author 胡尚
 * @Date: 2024/8/11 17:00
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "sys_user")
public class UserEntity {
    @Id
    private Long id;
    
    @Field(type = FieldType.Keyword)
    private String name;
    
    // @Field(index = false) 也可以指定不要创建索引
    private int sex;
    
    private int age;
    
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String address;
    
    private String remark;
}



实现ElasticsearchRepository

该方式了解即可,一般都是使用的ElasticsearchRestTemplate对象操作

该接口是框架封装的用于操作Elastsearch的高级接口

import com.hs.es.entity.UserEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description: 使用 实现ElasticsearchRepository 方式进行测试
 * @Author 胡尚
 * @Date: 2024/8/11 17:10
 */
@Repository
public interface UserRepository extends ElasticsearchRepository<UserEntity, Long> {

    // 因为我实体类中字段名为name,所以这里方法名必须是ByName,不然就会报错,
    List<UserEntity> findByName(String name);
}



我实体类使用username字段名报错信息如下图所示

在这里插入图片描述



测试

import com.hs.es.entity.UserEntity;
import com.hs.es.mapper.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Optional;


/**
 * @Description: 测试类
 * @Author 胡尚
 * @Date: 2024/8/11 17:13
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticsearchTest {
    @Autowired
    UserRepository userRepository;

    @Test
    public void testDocument(){

        UserEntity user = new UserEntity(1L, "hs666", 1, 24, "长沙麓谷", "java architect");
        // 插入文档
        userRepository.save(user);

        // 根据id查询
        Optional<UserEntity> userOptional = userRepository.findById(1L);
        System.out.println(userOptional.get());

        //根据name查询
        List<UserEntity> hsUser = userRepository.findByName("hs666");
        System.out.println(hsUser.get(0));
    }
}



使用ElasticsearchRestTemplate

@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;



索引操作

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Description: es测试类
 * @Author 胡尚
 * @Date: 2024/8/11 17:30
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {

    @Autowired
    ElasticsearchRestTemplate restTemplate;


    // 创建索引
    @Test
    public void testCrateIndex(){
        IndexOperations employeeIndex = restTemplate.indexOps(IndexCoordinates.of("employee_index"));
        if (employeeIndex.exists()){
            log.info("索引已存在");
        }else {
            log.info("创建索引");
            employeeIndex.create();
        }
    }

    // 删除索引
    @Test
    public void testDeleteIndex(){
        IndexOperations employeeIndex = restTemplate.indexOps(IndexCoordinates.of("employee_index"));
        employeeIndex.delete();
    }
}



当然也可以把我们之前创建的User实体类也利用上,可以发现,创建的index的mapping下只有我们加了@Field的字段信息

@Test
public void testCrateIndex2(){
    IndexOperations userIndex = restTemplate.indexOps(IndexCoordinates.of("sys_user"));
    // 调用createMapping()方法
    userIndex.createMapping(UserEntity.class);

}

在这里插入图片描述



文档操作

import com.alibaba.fastjson2.JSON;
import com.hs.es.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: es测试类
 * @Author 胡尚
 * @Date: 2024/8/11 17:30
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {

    @Autowired
    ElasticsearchRestTemplate restTemplate;


    /**
     * 批量插入文档
     */
    @Test
    public void testInsertDocumentBatch(){
        List<UserEntity> userEntityList = new ArrayList<>();
        userEntityList.add(new UserEntity(1L,"张三",1,25,"广州天河公园","java developer"));
        userEntityList.add(new UserEntity(2L,"李四",1,28,"广州荔湾大厦","java assistant"));
        userEntityList.add(new UserEntity(3L,"小红",0,26,"广州白云山公园","php developer"));

        List<IndexQuery> indexQueries = new ArrayList<>();
        for (UserEntity userEntity : userEntityList) {
            // 封装id与数据
            IndexQuery indexQuery = new IndexQuery();
            indexQuery.setId(String.valueOf(userEntity.getId()));
            indexQuery.setSource(JSON.toJSONString(userEntity));

            indexQueries.add(indexQuery);
        }
        // 批量插入
        restTemplate.bulkIndex(indexQueries, UserEntity.class);
    }
}



插入的数据如下

在这里插入图片描述



package com.hs.es;

import com.alibaba.fastjson2.JSON;
import com.hs.es.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: es测试类
 * @Author 胡尚
 * @Date: 2024/8/11 17:30
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {

    @Autowired
    ElasticsearchRestTemplate restTemplate;

    /**
     * 查询文档
     */
    @Test
    public void testQueryDocument(){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        // 查询
        builder.withQuery(QueryBuilders.matchQuery("address", "公园"));
        // 设置分页信息
        builder.withPageable(PageRequest.of(0,5));
        // 设置排序
        builder.withSorts(SortBuilders.fieldSort("age").order(SortOrder.DESC));

        SearchHits<UserEntity> searchHits = restTemplate.search(builder.build(), UserEntity.class);
        for (SearchHit<UserEntity> searchHit : searchHits) {
            System.out.println(JSON.toJSON(searchHit));
            System.out.println(searchHit.getContent());
        }
    }
}



一个SearchHit对象保存的信息如下

{
  "content": {
    "address": "广州白云山公园",
    "age": 26,
    "id": 3,
    "name": "小红",
    "remark": "php developer",
    "sex": 0
  },
  "highlightFields": {
    
  },
  "id": "3",
  "index": "sys_user",
  "innerHits": {
    
  },
  "matchedQueries": [
    
  ],
  "score": null,
  "sortValues": [
    26
  ]
}

标签:SpringBoot,boot,springframework,ElasticSearch,elasticsearch,整合,org,import,data
From: https://blog.csdn.net/qq_44027353/article/details/141109731

相关文章

  • 基于Springboot+Vue的网上蛋糕销售系统(含源码数据库)
    1.开发环境开发系统:Windows10/11架构模式:MVC/前后端分离JDK版本:JavaJDK1.8开发工具:IDEA数据库版本:mysql5.7或8.0数据库可视化工具:navicat服务器:SpringBoot自带apachetomcat主要技术:Java,Springboot,mybatis,mysql,vue2.视频演示地址3.功能这个系......
  • 基于Springboot+Vue的学生就业信息系统 (含源码数据库)
    1.开发环境开发系统:Windows10/11架构模式:MVC/前后端分离JDK版本:JavaJDK1.8开发工具:IDEA数据库版本:mysql5.7或8.0数据库可视化工具:navicat服务器:SpringBoot自带apachetomcat主要技术:Java,Springboot,mybatis,mysql,vue2.视频演示地址3.功能在这个......
  • Windows ,elasticsearch 启动报错 failed to obtain node locks
    报错:2024.08.1118:14:45ERRORes[][o.e.b.ElasticsearchUncaughtExceptionHandler]uncaughtexceptioninthread[main]org.elasticsearch.bootstrap.StartupException:java.lang.IllegalStateException:failedtoobtainnodelocks,tried[[D:\soft\Java\sonarq......
  • SonarQube启动时,elasticsearch 报错 with lock id [0]; maybe these locations are n
     报错: 查看elasticsearch日志,在安装位置\sonarqube-9.9.6.92038\logs\es.log2024.08.1118:14:45ERRORes[][o.e.b.ElasticsearchUncaughtExceptionHandler]uncaughtexceptioninthread[main]org.elasticsearch.bootstrap.StartupException:java.lang.IllegalStateE......
  • 基于Java Springboot“一分钟”寝室小卖部系统
    一、作品包含源码+数据库+设计文档万字+PPT+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css、Js、Vue、Element-ui数据库:MySQL后端技术:Java、SpringBoot、MyBatis三、运行环境开发工具:IDEA/eclipse数据库:MySQL5.7数据库管理工具:Navicat10以上版本环境......
  • 基于Java Springboot音乐播放器系统
    一、作品包含源码+数据库+设计文档万字+PPT+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css、Js、Vue、Element-ui数据库:MySQL后端技术:Java、SpringBoot、MyBatis三、运行环境开发工具:IDEA/eclipse数据库:MySQL5.7数据库管理工具:Navicat10以上版本环境......
  • 基于Java Springboot传统戏曲推广微信小程序
    一、作品包含源码+数据库+设计文档万字+PPT+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css、Js、Vue、Element-ui数据库:MySQL后端技术:Java、SpringBoot、MyBatis三、运行环境开发工具:IDEA/eclipse+微信开发者工具数据库:MySQL5.7数据库管理工具:Navica......
  • 基于Java Springboot宠物中心信息管理app或微信小程序
    一、作品包含源码+数据库+设计文档万字+PPT+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css、Js、Vue、Element-ui数据库:MySQL后端技术:Java、SpringBoot、MyBatis三、运行环境开发工具:IDEA/eclipse+微信开发者工具数据库:MySQL5.7数据库管理工具:Navica......
  • 时尚美妆化妆品电商商城网站-计算机毕设Java|springboot实战项目
    ......
  • springboot打包程序操作
    打包作用:我们打包的主要目的就是为了不使用idea也能够运行程序,能够把这个程序给放到服务器上去运行。第一部分:打包程序(1)首先把所有的页面都关掉,确保有一个干净的页面:(2)然后在右侧的maven部分点击package操作,并等待执行一段时间:(3)打包成功的结果第二部分:找到打包程序(1)在......