springboot 整合Elasticsearch6.x ElasticsearchRepository和ElasticsearchTemplate

一、引入对应的pom

版本要对应,不然连接会报错

<?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.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
	
  <groupId>com.zhouzy.springboot</groupId>
  <artifactId>zhouzy-springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>zhouzy-springboot</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>


  <dependencies>
  		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
      	<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      	</dependency>
      	
      	<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.28</version>
		</dependency>
        
        <dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <scope>provided</scope>
		</dependency>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

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

二、application.properties配置

只要配置集群IP和端口,我是本地测试的

spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.repositories.enabled=true

三、创建实体类

1、Article

索引对应关系型数据库的database,type就是表,Document就是行记录row

package com.zhouzy.springboot.model;

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

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

/**
 * <p>
 * <p>
 *
 * @author zhouzhiyao
 * @since 2021/07/10
 */
@Document(indexName = "zhouzy", type = "article")
public class Article implements Serializable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
    private Long id;
    /**
     * 标题
     */
    private String title;
    /**
     * 摘要
     */
    private String abstracts;
    /**
     * 内容
     */
    private String content;
    /**
     * 发表时间
     */
    private Date postTime;
    /**
     * 点击率
     */
    private Long clickCount;
    /**
     * 作者
     */
    private Author author;
    /**
     * 所属教程
     */
    private Tutorial tutorial;
    
    public Article(){
    	
    }
    
    public Article(Long id,String title,String abstracts,
    		String content,Date postTime,Long clickCount,
    		Author author,Tutorial tutorial){
    	this.id = id;
    	this.title = title;
    	this.abstracts = abstracts;
    	this.content = content;
    	this.postTime = postTime;
    	this.clickCount = clickCount;
    	this.author = author;
    	this.tutorial = tutorial;
    }

	public Long getId() {
		return id;
	}

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

	public String getTitle() {
		return title;
	}

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

	public String getAbstracts() {
		return abstracts;
	}

	public void setAbstracts(String abstracts) {
		this.abstracts = abstracts;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getPostTime() {
		return postTime;
	}

	public void setPostTime(Date postTime) {
		this.postTime = postTime;
	}

	public Long getClickCount() {
		return clickCount;
	}

	public void setClickCount(Long clickCount) {
		this.clickCount = clickCount;
	}

	public Author getAuthor() {
		return author;
	}

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

	public Tutorial getTutorial() {
		return tutorial;
	}

	public void setTutorial(Tutorial tutorial) {
		this.tutorial = tutorial;
	}
    
    
    
}

2、Author

package com.zhouzy.springboot.model;

import java.io.Serializable;

/**
 * <p>
 * <p>
 *
 * @author zhouzhiyao
 * @since 2021/07/10
 */
public class Author implements Serializable {
	public Author(){
		
	}
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
     * 作者id
     */
    private Long id;
    /**
     * 作者姓名
     */
    private String name;
    /**
     * 作者简介
     */
    private String remark;
    
    public Author(Long id,String name,String remark){
    	this.id = id;
    	this.name = name;
    	this.remark = remark;
    }

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}
    
    
}

3、Tutorial

package com.zhouzy.springboot.model;

import java.io.Serializable;

/**
 * <p>
 * <p>
 *
 * @author zhouzhiyao
 * @since 2021/07/10
 */
public class Tutorial implements Serializable {
	public Tutorial(){
		
	}
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Long id;
    private String name;//教程名称
    
    public Tutorial(Long id,String name){
    	this.id = id;
    	this.name = name;
    }

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
    
    
}

四、DAO层接口

package com.zhouzy.springboot.dao;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import com.zhouzy.springboot.model.Article;
import com.zhouzy.springboot.model.Author;

/**
 * <p>
 * <p>
 *
 * @author zhouzhiyao
 * @since 2021/07/10
 */
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {

    Page<Article> findByAuthor(Author author, Pageable pageable);

    List<Article> findByTitle(String title);

    Page<Article> findByTitle(String title, Pageable pageable);
}

五、service层接口

package com.zhouzy.springboot.service;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import com.zhouzy.springboot.model.Article;
import com.zhouzy.springboot.model.Author;

/**
 * <p>
 * <p>
 *
 * @author xiemopeng
 * @since 2018/2/27
 */
public interface ArticleService {

    Article save(Article article);

    void delete(Article article);

    Article findOne(Long id);

    Iterable<Article> findAll();

    Page<Article> findByAuthor(Author author, PageRequest pageRequest);

    Page<Article> findByTitle(String title, PageRequest pageRequest);

    List<Article> findByTitle(String title);

    Iterable<Article> search(String queryString);
}

实现类

package com.zhouzy.springboot.service.impl;

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

import lombok.extern.slf4j.Slf4j;

import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.zhouzy.springboot.dao.ArticleRepository;
import com.zhouzy.springboot.model.Article;
import com.zhouzy.springboot.model.Author;
import com.zhouzy.springboot.service.ArticleService;

/**
 * <p>
 * <p>
 *
 * @author xiemopeng
 * @since 2018/2/27
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Article save(Article article) {
        return articleRepository.save(article);
    }

    @Override
    public void delete(Article article) {
        articleRepository.delete(article);
    }

    @Override
    public Article findOne(Long id) {
    	Optional<Article> op = articleRepository.findById(id);
        return op.get();
    }

    @Override
    public Iterable<Article> findAll() {
        return articleRepository.findAll();
    }

    @Override
    public Page<Article> findByAuthor(Author author, PageRequest pageRequest) {
        return articleRepository.findByAuthor(author, pageRequest);
    }

    @Override
    public Page<Article> findByTitle(String title, PageRequest pageRequest) {
        return articleRepository.findByTitle(title, pageRequest);
    }

    @Override
    public List<Article> findByTitle(String title) {
        return articleRepository.findByTitle(title);
    }

    @Override
    public Iterable<Article> search(String queryString) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        return articleRepository.search(builder);
    }

}

六、Controller控制层

package com.zhouzy.springboot.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.zhouzy.springboot.model.Article;
import com.zhouzy.springboot.model.Author;
import com.zhouzy.springboot.model.Tutorial;
import com.zhouzy.springboot.service.ArticleService;
/**
 * <p>
 * <p>
 *
 * @author zhouzhiyao
 * @since 2021/07/10
 */
@RestController
public class EsController {
	Logger log = LoggerFactory.getLogger(EsController.class);
	@Autowired
	private ArticleService articleService;
	 
 	@RequestMapping("/article/{id}")
    @ResponseBody
    public Article getBookById(@PathVariable Long id){
 		Article article =articleService.findOne(id);
 		log.info("Article:{}",JSONObject.toJSONString(article));
        return article;
    }

    @RequestMapping("/article/save")
    @ResponseBody
    public void Save(){
    	for(Long i=0L;i<10;i++){
	    	Author author = new Author(null, "zhouzy", null);
	    	Tutorial tutorial = new Tutorial(i, "test" + String.valueOf(i));
	    	Article article = new Article(i, "title", "abs", "content", new Date(), i, author, tutorial);
	    	articleService.save(article);
    	}
    }
}

七、启动

package com.zhouzy.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
class WebApplication{

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

}

八、执行

http://localhost:8080/article/save

查看结果:

http://localhost:8080/article/8

 测试成功

九、用ElasticsearchTemplate实现

@Autowired
ElasticsearchTemplate elasticsearchTemplate;
@RequestMapping("/article/list")
    @ResponseBody
    public List<Article> list(HttpServletRequest request){
    	String title = request.getParameter("title");
    	// 创建查询条件对象
    	BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

    	// 拼接查询条件
    	//queryBuilder.must(QueryBuilders.termQuery("title", title)); 
    	//queryBuilder.must(QueryBuilders.matchAllQuery());
    	queryBuilder.must(QueryBuilders.matchQuery("title",title));

    	// 创建查询对象
    	SearchQuery searchQuery = new NativeSearchQueryBuilder()
    	                .withQuery(queryBuilder)// 查询条件对象
    	                .withPageable(PageRequest.of(0, 2))//从0页开始查,每页1000个结果
    	                .build();
    	Page<Article> list = elasticsearchTemplate.queryForPage(searchQuery, Article.class);
    	log.info(JSONObject.toJSONString(list));
    	return list.getContent();
    }

结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wwwzhouzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值