• SpringBoot 集成 elasticsearch


    版本

    SpringBoot版本为2.4.3
    Elasticsearch 版本 7.0.1
    JDK1.8

    最新的7.x版本已经不支持自定义类型了,默认以_doc作为类型,一个索引只能有一个类型。

    ElasticSearch对比MYSQL

    索引 > 数据库,类型 > 表,文档 > 行,属性 > 列

    引入依赖

    Spring 团队将Elasticsearch归到“Data”的范畴,所以依赖是以Spring-Data开头。

    在pom.xml文件中添加以下依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        <version>2.4.3</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    添加客户端配置类

    新建ElasticSearchConfig.java配置类,并配置一个RestHighLevelClient对象。

    @Configuration
    public class EsClientConfig extends AbstractElasticsearchConfiguration {
    	@Bean
    	@Override
    	public RestHighLevelClient elasticsearchClient() {
    		final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
    				.connectedTo("192.168.11.21:9200")
    				.build();
    		return RestClients.create(clientConfiguration).rest();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    创建文档实体

    定义Book实体,官方叫Elasticsearch 对象映射
    //
    @Document 定义在Elasticsearch中索引信息
    @Field 定义字段类型等信息
    @Id 定义了Elasticsearch的_id, 表明该字段是文档id

    @Data
    @Document(indexName = "book", createIndex = true)
    public class Book {
    	@Id
    	@Field(type = FieldType.Text)
    	private String id;
    	@Field(analyzer = "ik_max_word")
    	private String title;
    	@Field(analyzer = "ik_max_word")
    	private String author;
    	@Field(type = FieldType.Double)
    	private Double price;
    	@Field(type = FieldType.Date, format = DateFormat.basic_date)
    	private Date createTime;
    	@Field(type = FieldType.Date, format = DateFormat.basic_date)
    	private Date updateTime;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    Elasticsearch Repositories

    该接口继承了ElasticsearchRepository接口,ElasticsearchRepository接口定义了Elasticsearch的CRUD,继承了该接口的接口甚至无需定义任何其他的方法就能满足基本需求。
    通过定义的方法名就能自动创建各种查询。

    。。。。。。

  • 相关阅读:
    算法|图论 3
    vulhub中Apache Log4j2 lookup JNDI 注入漏洞(CVE-2021-44228)
    Python-日志模块
    CSS简介
    【再识C进阶3(上)】详细地认识字符串函数、进行模拟字符串函数以及拓展内容
    Web Audio API 第1章 基础篇
    Foxit PDF SDK for Linux (C++ Library) 8.4.1 Crack
    Hbase基本概念
    DBeaver常用快捷键(含复制当前行)
    On-Device Neural Net Inference with Mobile GPUs
  • 原文地址:https://blog.csdn.net/qq_19636353/article/details/125469657