ElasticSearch入门教程【六】- spring-boot-starter-data-elasticsearch

教程列表

ElasticSearch入门教程【一】- 简介
ElasticSearch入门教程【二】- 安装
ElasticSearch入门教程【三】- Head插件
ElasticSearch入门教程【四】- 基本用法
ElasticSearch入门教程【五】- TransportClient客户端
ElasticSearch入门教程【六】- spring-boot-starter-data-elasticsearch

文章目录

        • 一、版本信息
        • 二、Maven依赖
        • 三、application.properties配置文件
        • 四、代码实现
          • 1. 实体类
          • 2. Repository接口
          • 3. 增删改查操作
        • 五、工程目录结构
        • 六、Springboot和Elasticsearch的版本对照关系
        • 七、参考文档

一、版本信息

Springboot 2.0.9.RELEASE

spring-boot-starter-data-elasticsearch 2.0.9.RELEASE

Elasticsearch 5.6.16

二、Maven依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.0.9.RELEASEversion> 
		<relativePath/> 
	parent>
	<groupId>com.rkyaogroupId>
	<artifactId>spring-boot-elasticsearch-repositoriesartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>spring-boot-elasticsearch-repositoriesname>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
	properties>

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

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintagegroupId>
					<artifactId>junit-vintage-engineartifactId>
				exclusion>
			exclusions>
		dependency>

		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>4.12version>
		dependency>

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-elasticsearchartifactId>
		dependency>

		
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<version>1.18.12version>
			<scope>providedscope>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

project>

三、application.properties配置文件

# elasticsearch配置
# 集群地址
spring.data.elasticsearch.cluster-nodes=192.168.255.150:9300
# 集群名称
spring.data.elasticsearch.cluster-name=rkyao-es-cluster
# 开启 Elasticsearch 仓库
spring.data.elasticsearch.repositories.enabled=true

四、代码实现

1. 实体类
package com.rkyao.spring.boot.elasticsearch.repositories.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "people", type="student")
public class Student implements Serializable {

    /**
     * id字段必须有
     */
    @Id
    private String id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 地址
     */
    private String address;

    /**
     * 年龄
     */
    private int age;

    /**
     * 出生日期
     */
    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss||epoch_millis")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date birthday;

}
2. Repository接口
package com.rkyao.spring.boot.elasticsearch.repositories.repository;

import com.rkyao.spring.boot.elasticsearch.repositories.entity.Student;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface StudentRepository extends ElasticsearchRepository<Student, String> {

    List<Student> findByNameAndAge(String name, int age);

}
3. 增删改查操作
package com.rkyao.spring.boot.elasticsearch.repositories.repository;

import com.rkyao.spring.boot.elasticsearch.repositories.entity.Student;
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.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class StudentRepositoryTest {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 新增数据
     *
     * @throws Exception
     */
    @Test
    public void testSave() throws Exception {
        Student student = new Student();
        // id不指定会自动生成
        student.setId("1");
        student.setName("Big Q");
        student.setAddress("SD");
        student.setAge(26);
        student.setBirthday(new Date());
        Student student1 = studentRepository.save(student);
        System.out.println(student1);
    }

    /**
     * 更新数据
     *
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        Student student = new Student();
        // 根据id更新
        student.setId("1");
        student.setName("Big Q");
        student.setAddress("HZ");
        student.setAge(25);
        student.setBirthday(new Date());
        studentRepository.save(student);
        Student student1 = studentRepository.save(student);
        System.out.println(student1);
    }

    /**
     * 删除数据
     *
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        String id = "1";
        studentRepository.deleteById(id);
    }

    /**
     * 查询全部数据
     *
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        Iterable<Student> list = studentRepository.findAll();
        for (Student student : list) {
            System.out.println(student);
        }
    }

    /**
     * 根据id查询
     *
     * @throws Exception
     */
    @Test
    public void testFindById() throws Exception {
        String id = "1";
        Optional<Student> student = studentRepository.findById(id);
        student.ifPresent(System.out::println);
    }

    /**
     * 自定义查询 根据姓名和年龄查询
     *
     * @throws Exception
     */
    @Test
    public void testFindByNameAndAge() throws Exception {
        String name = "Big Q";
        int age = 26;
        List<Student> studentList = studentRepository.findByNameAndAge(name, age);
        System.out.println(studentList);
    }

}

五、工程目录结构

ElasticSearch入门教程【六】- spring-boot-starter-data-elasticsearch_第1张图片

六、Springboot和Elasticsearch的版本对照关系

ElasticSearch入门教程【六】- spring-boot-starter-data-elasticsearch_第2张图片

七、参考文档

https://docs.spring.io/spring-data/elasticsearch/docs/

你可能感兴趣的:(elasticsearch)