SpringBoot2.X整合elasticsearch'

Posted shsgshn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.X整合elasticsearch'相关的知识,希望对你有一定的参考价值。

 SpringBoot默认支持两种技术来和ES交互;

创建项目需要引入ES的启动器

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--集合工具包-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>

 

第一种:

 1、Jest(默认不生效)   需要导入jest的工具包(io.searchbox.client.JestClient)

操作步骤:

  1) 引入jest的依赖

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>

 

  2)在配置文件中jest添加相关配置

#使用jest客户端操作ES
spring.elasticsearch.jest.uris=http://10.2.193.102:9200

 

  3)使用jest客户端操作ES

import cn.xiwei.springboot.es.bean.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
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.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsApplicationTests

@Autowired
JestClient jestClient;
@Test
public void contextLoads()

//1、给Es中索引(保存)一个文档;
Article article = new Article();
article.setId(1);
article.setTitle("好消息");
article.setAuthor("zhangsan");
article.setContent("Hello World");

//构建一个索引功能
Index index = new Index.Builder(article).index("xiwei").type("news").build();

try
//执行
jestClient.execute(index);
catch (IOException e)
e.printStackTrace();



//测试搜索
@Test
public void search()
//构建查询表达式
String json = "\n" +
" \"query\" : \n" +
" \"match\" : \n" +
" \"content\" : \"hello\"\n" +
" \n" +
" \n" +
"";
Search search = new Search.Builder(json).addIndex("xiwei").addType("news").build();

try
SearchResult result = jestClient.execute(search);
System.out.println(result.getJsonString());
catch (IOException e)
e.printStackTrace();



 

 

第二种:
1、SpringData ElasticSearch【ES版本有可能不合适】
  * 版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch
  * 如果版本不适配:2.4.6
  * 1)、升级SpringBoot版本
  * 2)、安装对应版本的ES

  1)、Client 节点信息clusterNodes;clusterName

#ES集群的名称
spring.data.elasticsearch.cluster-name=my-application

#Es节点的访问地址及端口
spring.data.elasticsearch.cluster-nodes=10.2.193.102:9300

#开启repositories
spring.data.elasticsearch.repositories.enabled=true

#项目端口号
server.port=8080


  2)、ElasticsearchTemplate 操作es (略)

  3)、编写一个 ElasticsearchRepository 的子接口来操作ES;

import cn.xiwei.springboot.es.bean.Notice;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface NoticeRepository extends ElasticsearchRepository<Notice, Long>

  4)、测试

import cn.xiwei.springboot.es.bean.Notice;
import cn.xiwei.springboot.es.repository.NoticeRepository;
import com.google.common.collect.Lists;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
* @author lykan
* @create 2019-09-11 18:40
*/
@RestController
@RequestMapping("/api/v1/article")
public class NoticeController


@Autowired
private NoticeRepository nticeRepository;

@Autowired
ElasticsearchTemplate elasticsearchTemplate;

@GetMapping("/save")
public Object save(long id, String title)

Notice article = new Notice();
article.setId(id);
article.setReadCount(123);
article.setTitle(title);
return nticeRepository.save(article);



/**
* @param title 搜索标题
* @param pag page = 第几页参数, value = 每页显示条数
*/
@GetMapping("/search")
public Object search(String title ,@PageableDefault() Pageable pag)

//按标题进行搜索
QueryBuilder builder = QueryBuilders.matchQuery("title", title);
//如果实体和数据的名称对应就会自动封装,pageable分页参数
Iterable<Notice> listIt = nticeRepository.search(builder, pag);
//Iterable转list
List<Notice> list= Lists.newArrayList(listIt);

return list;



@RequestMapping("/all")
public List<Notice> all() throws Exception
Iterable<Notice> data = nticeRepository.findAll();
List<Notice> ds = new ArrayList<>();
for (Notice d : data)
ds.add(d);

return ds;

@RequestMapping("/id")
public Object findid(long id) throws Exception
return nticeRepository.findById(id).get();



  5)、实体类

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.elasticsearch.annotations.Document;

/**
* @author lykan
* @create 2019-09-11 18:00
*/
//indexName代表所以名称,type代表表名称
@Document(indexName = "wantu_notice_info", type = "doc")
public class Notice
//id
@JsonProperty("auto_id")
private Long id;
//标题
@JsonProperty("title")
private String title;
//公告标签
@JsonProperty("exchange_mc")
private String exchangeMc;
//公告发布时间
@JsonProperty("create_time")
private String originCreateTime;
//公告阅读数量
@JsonProperty("read_count")
private Integer readCount;
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 getExchangeMc()
return exchangeMc;

public void setExchangeMc(String exchangeMc)
this.exchangeMc = exchangeMc;

public String getOriginCreateTime()
return originCreateTime;

public void setOriginCreateTime(String originCreateTime)
this.originCreateTime = originCreateTime;

public Integer getReadCount()
return readCount;

public void setReadCount(Integer readCount)
this.readCount = readCount;

public Notice(Long id, String title, String exchangeMc, String originCreateTime, Integer readCount)
super();
this.id = id;
this.title = title;
this.exchangeMc = exchangeMc;
this.originCreateTime = originCreateTime;
this.readCount = readCount;

public Notice()
super();

  
  两种用法:https://github.com/spring-projects/spring-data-elasticsearch

以上是关于SpringBoot2.X整合elasticsearch'的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot2.x整合WebSoket

springboot2.x整合quartz2.x.md

SpringBoot2.x 整合Redis和使用Redis缓存

SpringBoot2.X整合Redis

springboot2.x版本整合redis(单机/集群)(使用lettuce)

SpringBoot2.x整合Prometheus+Grafana附源码