码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot整合Elasticsearch

时间:2021-03-15 10:40:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:应用   _id   auto   retention   use   表达   com   put   host   

说明

相关环境:

SpringBoot - 2.4.3

Elasticsearch - 7.11.2

这个例子默认已搭建好springboot、jdbc、mybatis和Swagger(非必需)

添加依赖

<!--Elasticsearch相关依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

配置类

/**
 * es客户端配置类
 * 需要继承抽象类AbstractElasticsearchConfiguration,重写方法中配置ip和端口
 * @author
 */
@Configuration
public class EsClientConfig extends AbstractElasticsearchConfiguration {
    private final String HOST_AND_PORT = "192.168.xx.xxx:9200";

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            	// ip和端口号
                .connectedTo(HOST_AND_PORT)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

实现代码

大概结构:

  • 语言类
  • 细分为计算机语言类,包含Java、C++、JavaScript
{
    "list": [
        {
            "id": 1,
            "name": "Computer Language",
            "description": "计算机语言",
            "type": 1,
            "containList": [
                {
                    "id": 1,
                    "type:": 1,
                    "value": "Java",
                    "name": "Java"
                },
                {
                    "id": 2,
                    "type:": 1,
                    "value": "C++",
                    "name": "C艹"
                }
            ]
        },
        {
            "id": 2,
            "name": "Person Language",
            "description": "人类语言",
            "type": 2,
            "containList": [
                {
                    "id": 1,
                    "type:": 2,
                    "value": "zh-CN",
                    "name": "汉语"
                },
                {
                    "id": 2,
                    "type:": 2,
                    "value": "en",
                    "name": "??语"
                }
            ]
        }
    ]
}

类文件

  • Language
/**
 * 语言类
 * @author
 */
@Data
@Document(indexName = "language", shards = 1, replicas = 0)
public class Language {
    @Id
    private int id;
    private int type;
    @Field(type = FieldType.Keyword)
    private String name;
    @Field(type = FieldType.Keyword)
    private String description;
    @Field(type = FieldType.Nested)
    private List<LanguageDetails> languageDetailsList;
}
  • LanguageDetails
/**
 * 计算机语言
 * @author
 */
@Data
public class LanguageDetails {
    @Id
    private int id;
    private int type;
    @Field(type = FieldType.Keyword)
    private String value;
    @Field(type = FieldType.Keyword)
    private String name;
}

es操作接口

对es的操作经由这个接口完成,接口必须继承ElasticsearchRepository,继承这个接口不需要实现类,就可以使用es的操作方法。

/**
 * ES操作接口
 * @author
 */
public interface EsReponsitory extends ElasticsearchRepository<Language, Integer> {}

mapper接口

/**
 * ES mapper接口
 * @author
 */
@Mapper
public interface EsMapper {
    /**
     * 获取语言数据
     * @param id
     * @return
     */
    List<Language> getAllLanguages(@Param("id") Long id);
}

mapper.xml:LanguageMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dev.springboot.mall.elasticsearch.mapper.EsMapper">
    <resultMap id="languageMap" type="dev.springboot.elasticsearch.Language"
               autoMapping="true">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <collection property="languageDetailsList" ofType="dev.springboot.elasticsearch.LanguageDetails">
            <result column="detail_id" property="id"/>
            <result column="detail_type" property="type"/>
            <result column="value" property="value"/>
            <result column="detail_name" property="name"/>
        </collection>
    </resultMap>
    <select id="getAllLanguages" resultMap="languageMap">
        select t1.id,
        t1.type,
        t1.name,
        t1.description,
        t2.id as detail_id,
        t2.name as detail_name,
        t2.type as detail_type,
        t2.value
        from language t1
        left join language_details t2 on t1.type = t2.type
        <if test="id!=null">
            and t1.id=#{id}
        </if>
    </select>
</mapper>

esService接口

/**
 * es操作Service接口
 * @author
 */
@Component
public interface EsService {
    /**
     * 从数据库中导入所有商品到ES
     * @return
     */
    int importAll();

    /**
     * 根据id删除商品
     * @param id
     */
    void delete(int id);
}

esServiceImpl接口实现类

/**
 * es操作实现类
 * @author
 */
@Service
public class EsServiceImpl implements EsService {
    @Resource
    private EsMapper esMapper;
    @Resource
    private EsReponsitory esReponsitory;

    @Override
    public int importAll() {
        try {
            // 将对象数据从数据库中取出来
            List<Language> languageList = esMapper.getAllLanguages(null);
            // 将对象集合通过ElasticsearchRepository存入到es中
            esReponsitory.saveAll(languageList);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return 0;
        }
        return 1;
    }

    @Override
    public void delete(int id) {
        esReponsitory.deleteById(id);
    }
}

Controller调用接口

/**
 * @author
 */
@Api(tags = "es接口测试")
@RestController
@RequestMapping("/es")
public class EsController {

    @Resource
    private EsService esService;

    @ApiOperation("从数据库中导入全部数据")
    @PostMapping(value = "/importAll")
    public int importFromDb() {
        return esService.importAll();
    }

    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public void deleteById(@PathVariable("id") int id) {
        esService.delete(id);
    }
}

查询结果

Kibana的devTool中使用命令查询结果或在浏览器中调用接口

GET /language/_search # 命令行
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "language",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "_class" : "dev.springboot.elasticsearch.Language",
          "id" : 1,
          "type" : 1,
          "name" : "Computer",
          "description" : "计算机语言",
          "languageDetailsList" : [
            {
              "id" : 1,
              "type" : 1,
              "value" : "Java",
              "name" : "Java"
            },
            {
              "id" : 2,
              "type" : 1,
              "value" : "C++",
              "name" : "C艹"
            }
          ]
        }
      },
      {
        "_index" : "language",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "_class" : "dev.springboot.elasticsearch.Language",
          "id" : 2,
          "type" : 2,
          "name" : "Person",
          "description" : "人类语言",
          "languageDetailsList" : [
            {
              "id" : 3,
              "type" : 2,
              "value" : "zh-CN",
              "name" : "中文"
            },
            {
              "id" : 4,
              "type" : 2,
              "value" : "en",
              "name" : """??语"""
            }
          ]
        }
      }
    ]
  }
}

需要关注的点

实体类注解说明

  • @Document
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {
    // 用于存储此实体的索引的名称。它可以包含SpEL模板表达式,例如"log-#{T(java.time.LocalDate).now().toString()}" 
    // 简单说就是es中的index, 即:GET /index/_search
    String indexName();

    boolean useServerConfiguration() default false;
	// 索引分片数
    short shards() default 1;
	// 索引副本数
    short replicas() default 1;
	// 索引的刷新间隔。用于索引创建。默认值为“ 1s”
    String refreshInterval() default "1s";
	// 索引的索引存储类型。用于索引创建。默认值为“ fs”
    String indexStoreType() default "fs";
	// 标记是否在存储库引导中创建索引。默认值是true
    boolean createIndex() default true;
	// 版本管理的配置。默认值为EXTERNAL
    VersionType versionType() default VersionType.EXTERNAL;
}
  • @Id:在字段级别应用,以标记用于标识目的的字段

  • @Field

public @interface Field {
	// 字段名称,它将在Elasticsearch文档中表示,如果未设置,则使用Java字段名称
    @AliasFor("value")
    String name() default "";
	// 字段类型,如:Text, Keyword, Long, Integer, Short, Byte等
    FieldType type() default FieldType.Auto;
	// 记原始字段值是否应存储在Elasticsearch中,默认值为false
    boolean store() default false;
    // 其他属性省略
}

ElasticsearchRepository接口原理说明

  • 底层Repository<T, ID>接口

    根据Spring Data官方文档:

    Spring Data存储库抽象的中央接口 Repository<T, ID>,该接口主要用作标记接口,以捕获要使用的类型并发现扩展该接口的接口

    @Indexed
    public interface Repository<T, ID> {}
    
  • CrudRepository<T, ID>接口

    继承自中央接口Repository<T, ID>,作用是为正在管理的实体类提供复杂的CRUD功能

    @NoRepositoryBean
    public interface CrudRepository<T, ID> extends Repository<T, ID> {
        <S extends T> S save(S var1);
    
        <S extends T> Iterable<S> saveAll(Iterable<S> var1);
    
        Optional<T> findById(ID var1);
    
        boolean existsById(ID var1);
    
        Iterable<T> findAll();
    
        Iterable<T> findAllById(Iterable<ID> var1);
    
        long count();
    
        void deleteById(ID var1);
    
        void delete(T var1);
    
        void deleteAll(Iterable<? extends T> var1);
    
        void deleteAll();
    }
    
  • PagingAndSortingRepository<T, ID>接口

    继承自CrudRepository接口,添加了其他方法来简化对实体的分页访问

    @NoRepositoryBean
    public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
        Iterable<T> findAll(Sort var1);
    
        Page<T> findAll(Pageable var1);
    }
    
  • ElasticsearchRepository<T, ID>接口

    继承自PagingAndSortingRepository接口,是由elasticsearch提供具体的方法,其实现类是

    public class SimpleElasticsearchRepository<T, ID> implements ElasticsearchRepository<T, ID> {
        // 本次用到的saveAll方法,
        public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
            Assert.notNull(entities, "Cannot insert ‘null‘ as a List.");
            IndexCoordinates indexCoordinates = this.getIndexCoordinates();
            this.executeAndRefresh((operations) -> {
                return operations.save(entities, indexCoordinates);
            });
            return entities;
        }
    }
    

所以,直接继承这个接口,不需要实现类即可使用es提供的基本方法

SpringBoot整合Elasticsearch

标签:应用   _id   auto   retention   use   表达   com   put   host   

原文地址:https://www.cnblogs.com/chengshuai5421/p/14525924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!