elasticsearch整合springBoot

elasticsearch的安装请参考:https://blog.csdn.net/qq_42410605/article/details/97884456

elasticsearch插件head的安装请参考:https://blog.csdn.net/qq_42410605/article/details/97885092

elasticsearch的基本操作请参考:https://blog.csdn.net/qq_42410605/article/details/97907209

elasticsearch高级查询请参考:https://blog.csdn.net/qq_42410605/article/details/97962286

在学习了elasticsearch的基本语法和基础功能之后,我们将elasticsearch和springboot进行整合,在实战中使用elasticsearch。

模拟的数据如下:

本篇博客我将对elasticsearch和springboot进行整合,整合的方法一共有两种,一种是使用Java API,另一种是使用springData-ES,进行整合。

ES使用Java API进行开发,官方已经明确表示在ES 7.0版本中将弃用TransportClient客户端,且在8.0版本中完全移除它。但是它在整合ES方面还是非常的活跃,请各位谨慎使用。


一、进行开发前期的新建项目和添加依赖等准备工作

1. 构建一个springboot项目:

(1)打开IntelliJ IDEA :File-->New-->Project-->

(2)找到spring initializr-->next

(3)创建项目:

(4)选择自己想要的依赖,我们这里只选了web的启动项-->next

(5)创建完成后的项目目录如下:

2.创建所需要的包以及文件:

在项目中新建下图的包以及类,接口:

解释:

controller包用来存放控制器:

  • RestfulApiController用来存放javaAPI的控制器方法;
  • SpringDataController用来存放SpringData-ES的控制器方法。

entity包用来存放model类:

  • Book为开发的实现类。

repository为Elasticsearch存储库(直接访问ES):

  • BookRepository用来存放Book的存储库。

service包用来存放业务类:

  • SpringDataService接口;
  • SpringDataService的实现类。

 

3.添加依赖:

(1)打开项目下的pom.xml:

(2)添加依赖:

在pom.xml中添加以下依赖,将你没有的依赖加进来就可以(我使用的springboot版本为2.1.6,elasticsearch为6.4.2)

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.lcc.springboot</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>elasticsearch</name>
	<description>Demo project for Spring Boot</description>

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


	<dependencies>
		<!--项目启动依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--测试依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!--elasticsearch依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<!--使用springdata时需要-->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
			<version>2.1.9.RELEASE</version>
		</dependency>

	</dependencies>



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

</project>

前期准备工作完成,下面进入编写代码阶段。

 

 

二、使用java API进行项目整合

1.添加ESConfig,配置Elasticsearch:

在项目中新建一个ESConfig用于配置Elasticsearch,添加以下代码:

package com.lcc.springboot.elasticsearch;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 李歘歘
 * ES配置文件
 */
@Configuration
public class ESConfig {


    @Bean
    public TransportClient client() throws UnknownHostException {
        TransportAddress node = new TransportAddress(
                //此处为tcp端口
                InetAddress.getByName("localhost"),9300

        );

        //elasticsearch配置
        Settings settings = Settings.builder()
                .put("cluster.name","lcc")
                .build();


        TransportClient client = new PreBuiltTransportClient(settings);
        //将地址传递给client,使其在这个地址发起请求
        //在集群环境下,可以创建多个node并传递进来
        client.addTransportAddress(node);
        return client;
    }
    /**
     * 防止netty的bug
     */
    @PostConstruct
    void init() {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }

}

完成后如下图:

2.编写业务逻辑代码:

在RestfulApiController类上添加控制器注解:

@RestController

在RestfulApiController类中添加以下代码实现自动注入:

	/***
	 * 自动注入
	 */
	@Autowired
	private TransportClient client;

完成后如下图:

 

(1)简单的查询--根据Id查询书籍:

在项目启动类中添加以下代码:

	/**
	 * 根据Id查询书籍
	 * @param id
	 * @return
	 */
	@GetMapping("/get/book/novel")
	@ResponseBody
	public ResponseEntity get(@RequestParam(name = "id",defaultValue = "") String id){
		//当传进来的id为空时返回404
		if (id.isEmpty()){
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		//获得传进来的值以及索引和类型等
		GetResponse result = this.client.prepareGet("book","novel",id).get();
		//当传进来的id不存在时返回404
		if (!result.isExists()) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(result.getSource(), HttpStatus.OK);
	}

 

(2)添加书籍:

在项目启动类中添加以下代码:

	/**
	 * 添加书籍
	 * @param title
	 * @param author
	 * @param wordCount
	 * @param publishDate
	 * @return
	 */
	@PostMapping("/add/book/novel")
	@ResponseBody
	public ResponseEntity add(
			@RequestParam(name = "title") String title,
			@RequestParam(name = "author") String author,
			@RequestParam(name = "word_count") int wordCount,
			@RequestParam(name = "publish_date")
					//限定日期格式
					@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
			Date publishDate ) {
		try {
			//构建json
			XContentBuilder content = XContentFactory.jsonBuilder()
					.startObject()
					.field("title",title)
					.field("author",author)
					.field("word_count",wordCount)
					.field("publish_date",publishDate.getTime())
					.endObject();
			//将json传进去并构建
			IndexResponse result = this.client.prepareIndex("book","novel")
					.setSource(content)
					.get();
			return new ResponseEntity(result.getId(),HttpStatus.OK);
		}catch (IOException e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

 

(3)删除书籍:

在项目启动类中添加以下代码:

	/**
	 * 删除书籍
	 * @param id
	 * @return
	 */
	@DeleteMapping("/delete/book/novel")
	@ResponseBody
	public ResponseEntity delete(@RequestParam(name = "id") String id) {
		DeleteResponse result = this.client.prepareDelete("book","novel",id).get();
		return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
	}

 

(4)更新书籍:

在项目启动类中添加以下代码:

/**
	 * 更新书籍
	 * @param id
	 * @param title
	 * @param author
	 * @return
	 */
	@PutMapping("/update/book/novel")
	@ResponseBody
	public ResponseEntity update(
			@RequestParam(name = "id") String id,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "author", required = false) String author ) {
		UpdateRequest update = new UpdateRequest("book","novel",id);
		try {
			XContentBuilder builder = XContentFactory.jsonBuilder()
					.startObject();
			//如果title和author不为空则传进来
			if (title != null) {
				builder.field("title",title);
			}
			if (author != null) {
				builder.field("author",author);
			}
			//builder一定要以endObject()结尾
			builder.endObject();
			update.doc(builder);
		}catch (IOException e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}

		try {
			//更新文档
			UpdateResponse result = this.client.update(update).get();
			return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
		}catch (Exception e){
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}

 

(5)复合查询书籍---检索:

在项目启动类中添加以下代码:

	/**
	 * 复合查询书籍---检索
	 * @param author
	 * @param title
	 * @param gtWordCount
	 * @param ltWordCount
	 * @return
	 */
	@PostMapping("/query/book/novel")
	@ResponseBody
	public ResponseEntity query (
			@RequestParam(name = "author", required = false) String author,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
			@RequestParam(name = "lt_word_count", required = false ) Integer ltWordCount ){

		//构建布尔查询
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		if (author != null){
			boolQuery.must(QueryBuilders.matchQuery("author",author));
		}
		if (title != null){
			boolQuery.must(QueryBuilders.matchQuery("title",title));
		}

		//构建范围查询
		RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count")
										.from(gtWordCount);
		if (ltWordCount != null && ltWordCount > 0 ) {
			rangeQuery.to(ltWordCount);
		}

		//将rangeQuery和boolQuery用filter结合起来
		boolQuery.filter(rangeQuery);

		SearchRequestBuilder builder = this.client.prepareSearch("book")
				.setTypes("novel")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(boolQuery)
				.setFrom(0)
				.setSize(10);

		System.out.println(builder);
		//获取返回结果,返回结果是一个hits
		SearchResponse response = builder.get();
		//创建存放返回结果的list
		List<Map<String, Object>> result = new ArrayList<>();

		//遍历取出的hits,存入result
		for (SearchHit hit : response.getHits()) {
			result.add(hit.getSource());
		}
		return new ResponseEntity(result, HttpStatus.OK);
	}

以上分别实现了增删改查的方法;

完整的代码如下:

package com.lcc.springboot.elasticsearch;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 李歘歘
 */
@SpringBootApplication
@RestController
public class ElasticsearchApplication {

	/***
	 * 自动注入
	 */
	@Autowired
	private TransportClient client;

	/**
	 * 根据Id查询书籍
	 * @param id
	 * @return
	 */
	@GetMapping("/get/book/novel")
	@ResponseBody
	public ResponseEntity get(@RequestParam(name = "id",defaultValue = "") String id){
		//当传进来的id为空时返回404
		if (id.isEmpty()){
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		//获得传进来的值以及索引和类型等
		GetResponse result = this.client.prepareGet("book","novel",id).get();
		//当传进来的id不存在时返回404
		if (!result.isExists()) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(result.getSource(), HttpStatus.OK);
	}


	/**
	 * 添加书籍
	 * @param title
	 * @param author
	 * @param wordCount
	 * @param publishDate
	 * @return
	 */
	@PostMapping("/add/book/novel")
	@ResponseBody
	public ResponseEntity add(
			@RequestParam(name = "title") String title,
			@RequestParam(name = "author") String author,
			@RequestParam(name = "word_count") int wordCount,
			@RequestParam(name = "publish_date")
					//限定日期格式
					@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
			Date publishDate ) {
		try {
			//构建json
			XContentBuilder content = XContentFactory.jsonBuilder()
					.startObject()
					.field("title",title)
					.field("author",author)
					.field("word_count",wordCount)
					.field("publish_date",publishDate.getTime())
					.endObject();
			//将json传进去并构建
			IndexResponse result = this.client.prepareIndex("book","novel")
					.setSource(content)
					.get();
			return new ResponseEntity(result.getId(),HttpStatus.OK);
		}catch (IOException e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}


	/**
	 * 删除书籍
	 * @param id
	 * @return
	 */
	@DeleteMapping("/delete/book/novel")
	@ResponseBody
	public ResponseEntity delete(@RequestParam(name = "id") String id) {
		DeleteResponse result = this.client.prepareDelete("book","novel",id).get();
		return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
	}


	/**
	 * 更新书籍
	 * @param id
	 * @param title
	 * @param author
	 * @return
	 */
	@PutMapping("/update/book/novel")
	@ResponseBody
	public ResponseEntity update(
			@RequestParam(name = "id") String id,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "author", required = false) String author ) {
		UpdateRequest update = new UpdateRequest("book","novel",id);
		try {
			XContentBuilder builder = XContentFactory.jsonBuilder()
					.startObject();
			//如果title和author不为空则传进来
			if (title != null) {
				builder.field("title",title);
			}
			if (author != null) {
				builder.field("author",author);
			}
			//builder一定要以endObject()结尾
			builder.endObject();
			update.doc(builder);
		}catch (IOException e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}

		try {
			//更新文档
			UpdateResponse result = this.client.update(update).get();
			return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
		}catch (Exception e){
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}

	/**
	 * 复合查询书籍---检索
	 * @param author
	 * @param title
	 * @param gtWordCount
	 * @param ltWordCount
	 * @return
	 */
	@PostMapping("/query/book/novel")
	@ResponseBody
	public ResponseEntity query (
			@RequestParam(name = "author", required = false) String author,
			@RequestParam(name = "title", required = false) String title,
			@RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
			@RequestParam(name = "lt_word_count", required = false ) Integer ltWordCount ){

		//构建布尔查询
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		if (author != null){
			boolQuery.must(QueryBuilders.matchQuery("author",author));
		}
		if (title != null){
			boolQuery.must(QueryBuilders.matchQuery("title",title));
		}

		//构建范围查询
		RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count")
										.from(gtWordCount);
		if (ltWordCount != null && ltWordCount > 0 ) {
			rangeQuery.to(ltWordCount);
		}

		//将rangeQuery和boolQuery用filter结合起来
		boolQuery.filter(rangeQuery);

		SearchRequestBuilder builder = this.client.prepareSearch("book")
				.setTypes("novel")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(boolQuery)
				.setFrom(0)
				.setSize(10);

		System.out.println(builder);
		//获取返回结果,返回结果是一个hits
		SearchResponse response = builder.get();
		//创建存放返回结果的list
		List<Map<String, Object>> result = new ArrayList<>();

		//遍历取出的hits,存入result
		for (SearchHit hit : response.getHits()) {
			result.add(hit.getSource());
		}
		return new ResponseEntity(result, HttpStatus.OK);
	}

	/**
	 * 启动方法
	 * @param args
	 */

	public static void main(String[] args) {
		SpringApplication.run(ElasticsearchApplication.class, args);
	}

}

由于java API较为简单,我们就不在service层进行开发了,只对controller进行开发。

3.代码测试:

启动项目,使用postman测试:

(1)根据Id查询书籍:

(2)添加书籍:

head中展示:

(3)删除书籍:

head中展示:

(4)更新书籍:

head展示:

(5)复合查询书籍---检索:

实例一:

实例二:

实例三:

 

 

三、springData-ES

1.在ESConfig,中添加以下代码,用于指定Elasticsearch存储库:

@EnableElasticsearchRepositories(basePackages = "com.lcc.springboot.elasticsearch.repository")

 如下图:

2.在创建好的实体类Book.java中编写以下:

package com.lcc.springboot.elasticsearch.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

import java.util.Date;

@Document(indexName = "book",type = "novel")
public class Book {

    @Id
    private String id;

    private String title;

    private String author;

    private Integer word_count;

    private Date publish_date;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getWord_count() {
        return word_count;
    }

    public void setWord_count(Integer word_count) {
        this.word_count = word_count;
    }

    public Date getPublish_date() {
        return publish_date;
    }

    public void setPublish_date(Date publish_date) {
        this.publish_date = publish_date;
    }
}

解释:

Spring Data通过注解来声明字段的映射属性,有下面的三个注解:

    @Document 作用在类,标记实体类为文档对象,一般有两个属性
        indexName:对应索引库名称
        type:对应在索引库中的类型
        shards:分片数量,默认5
        replicas:副本数量,默认1
    @Id 作用在成员变量,标记一个字段作为id主键
    @Field 作用在成员变量,标记为文档的字段,并指定字段映射属性:
        type:字段类型,是枚举:FieldType,可以是text、long、short、date、integer、object等
            text:存储数据时候,会自动分词,并生成索引
            keyword:存储数据时候,不会分词建立索引
            Numerical:数值类型,分两类
                基本数据类型:long、interger、short、byte、double、float、half_float
                浮点数的高精度类型:scaled_float
                    需要指定一个精度因子,比如10或100。elasticsearch会把真实值乘以这个因子后存储,取出时再还原。
            Date:日期类型
                elasticsearch可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long,节省空间。
        index:是否索引,布尔类型,默认是true
        store:是否存储,布尔类型,默认是false
        analyzer:分词器名称,这里的ik_max_word即使用ik分词器

3.编写Controller如下,分别编写模糊查询,按照Id查询,添加,删除,更新操作:

package com.lcc.springboot.elasticsearch.controller;

import com.lcc.springboot.elasticsearch.entity.Book;
import com.lcc.springboot.elasticsearch.service.SpringDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/springBoot")
public class SpringDataController {

    @Autowired
    private SpringDataService springDataService;

    /**
     * 查询包含title字段的书
     * @param title
     * @return
     */
    @PostMapping("/book/novel/findByTitle")
    public List<Book> findByTitle(@RequestParam(name = "title",required = false) String title) {
        List<Book> bookList = springDataService.findByTitle(title);
        return bookList;
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    @GetMapping("/book/novel/queryBookById")
    public Book queryBookById(String id) {
        Book book = springDataService.queryBookById(id);
        return book;
    }

    /**
     * 添加类型
     * @param book
     * @return
     */
    @PostMapping("/add/book/novel")
    public String add(Book book) {
        String info = springDataService.add(book);
        return info;
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/book/novel")
    public String delete(String id) {
        String info = springDataService.delete(id);
        return info;
    }


    /**
     * 更新(本质上就是添加)
     * @param book
     * @return
     */
    @PutMapping("/update/book/novel")
    public String update(Book book){
        String info = springDataService.update(book);
        return info;
    }




}

4.编写业务逻辑service层:

(1)SpringDataService:

package com.lcc.springboot.elasticsearch.service;

import com.lcc.springboot.elasticsearch.entity.Book;

import java.util.List;

public interface SpringDataService {

    /**
     * 查询包含title字段的书
     * @param title
     * @return
     */
    List<Book> findByTitle(String title);

    /**
     * 添加类型
     * @param book
     * @return
     */
    String add(Book book);

    /**
     * 删除
     * @param id
     * @return
     */
    String delete(String id);

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    Book queryBookById(String id);

    /**
     * 更新
     * @param book
     * @return
     */
    String update(Book book);

}

(2).SpringDataServiceImpl:

package com.lcc.springboot.elasticsearch.service.Impl;

import com.lcc.springboot.elasticsearch.entity.Book;
import com.lcc.springboot.elasticsearch.repository.BookRepository;
import com.lcc.springboot.elasticsearch.service.SpringDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpringDataServiceImpl implements SpringDataService {

    @Autowired
    private BookRepository bookRepository;


    /**
     * 查询包含title字段的书
     * @param title
     * @return
     */
    @Override
    public List<Book> findByTitle(String title) {
        /**
         * 这个方法已经springdata未装,自己编写
         */
        List<Book> bookList = bookRepository.findByTitle(title);
        return bookList;
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    @Override
    public Book queryBookById(String id) {
//        Book book = bookRepository.queryBookById(id);
        Book book = bookRepository.findById(id).get();
        return book;
    }

    /**
     * 添加
     * @param book
     * @return
     */
    @Override
    public String add(Book book){
        /**
         * 这个方法已经被springdata封装,不必自己编写
         */
        bookRepository.save(book);
        return "success";
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public String delete(String id) {
        Book book = new Book();
        book.setId(id);
        /**
         * 这个方法已经被springdata封装,不必自己编写
         */
        bookRepository.delete(book);
        return "success";
    }


    /**
     * 更新
     * @param book
     * @return
     */
    @Override
    public String update(Book book) {
//        Book book1 = bookRepository.queryBookById(book.getId());
        Book book1 = bookRepository.findById(book.getId()).get();
        //当传进来的值为空时不变
        if (book.getAuthor()!=null)
        book1.setAuthor(book.getAuthor());
        if (book.getPublish_date()!=null)
        book1.setPublish_date(book.getPublish_date());
        if (book.getTitle()!=null)
        book1.setTitle(book.getTitle());
        if (book.getWord_count()!=null)
        book1.setWord_count(book.getWord_count());
        bookRepository.save(book1);
        return "success";
    }
}

5.编写ES存储类BookRepository:

package com.lcc.springboot.elasticsearch.repository;

import com.lcc.springboot.elasticsearch.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {

    /**
     * 查询包含title字段的书
     * @param title
     * @return
     */
    List<Book> findByTitle(String title);


    /**
     * 根据Id查询
     * @param id
     * @return
     */
    Book queryBookById(String id);
}

解释:

很多的方法已经被springdata封装(上述的save,delete,findById等),不必自己编写,在根据Id进行查询时应注意springboot的版本,在springboot 2.x以后,根据id查询一条数据,就不能再使用findone方法了,变成了findbyid。上述代码时使用springboot2.1.6,使用findbyid方法。若你的项目是使用springboot2.x一下使用findone(id),即可。更多的了解请参考博客:https://blog.csdn.net/m0_37107281/article/details/85293694

Spring Data 的另一个强大功能,是根据方法名称自动实现功能。比如上面的findByTitle方法,它知道你是根据title查询,然后自动帮你完成,无需写实现类,只要写出接口就行。方法名称要符合一定的约定,如下:

6.代码测试:

启动项目,使用postman测试:

(1)根据Id查询:

 

(2)根据标题模糊查询:

 

(3)添加一个新的文档:

head显示:

(4)更新:

head显示:

(5)删除:

 

以上便是全部的elasticsearch整合springBoot实战过程,还是建议大家使用springData-ES,毕竟我们要学习最先进的东西,官方也会更重视新的东西。

在我的github上有完整的代码可以参考,如有不妥之处请留言,地址请参考:

Github地址

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值