SpringBoot整合ElasticSearch

一、基于spring-boot-starter-data-elasticsearch整合

开发环境:springboot版本:2.0.1,elasticSearch-5.6.8.jar版本:5.6.8,服务器部署ElasticSearch版本:6.3.2

1、application.properties

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.repositories.enabled=true

2、pom.xml

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

3、Notice实体

@Data
@AllArgsConstructor
@NoArgsConstructor
//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; }

4、NoticeRepository类

import com.jincou.elasearch.domain.Notice;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component; @Component
public interface NoticeRepository extends ElasticsearchRepository<Notice, Long> { } 

5、NoticeController

@RestController
@RequestMapping("/api/v1/article")
public class NoticeController { @Autowired
private NoticeRepository nticeRepository; @GetMapping("save")
public CommandResult<Void> save(long id, String title){ Notice article = new Notice();
article.setId(id);
article.setReadCount(123);
article.setTitle("springboot整合elasticsearch,这个是新版本 2018年");
nticeRepository.save(article);
return CommandResult.ofSucceed();
} /**
* @param title 搜索标题
* @param pageable page = 第几页参数, value = 每页显示条数
*/
@GetMapping("search")
public CommandResult<List<Notice>> search(String title,@PageableDefault(page = 1, value = 10) Pageable pageable){
//按标题进行搜索
QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
//如果实体和数据的名称对应就会自动封装,pageable分页参数
Iterable<Notice> listIt = nticeRepository.search(queryBuilder,pageable);

//Iterable转list
List<Notice> list= Lists.newArrayList(listIt); return CommandResult.ofSucceed(list);
}
}

6、查看运行结果

它会进行中文分词查询,然后安装相识度进行排序

总体步骤还是蛮清晰简单的,因为有spring-boot-starter-data-elasticsearch进行了整合,所以我们可以少敲很多代码。

二、 基于TransportClient整合

首先明白:如果项目SpringBoot1.5.X以下的,那么elasticSearch.jar最高是2.4.4版本的,只有SpringBoot2.X+,elasticSearch.jar才是5.X+

如果你的SpringBoot是1.5.X以下,那你又想用elasticSearch.jar5.X+怎么办呢,那就不要用spring-boot-starter-data-elasticsearch,用原生的TransportClient实现即可。

这个相当于用原生的去使用elasticsearch,这里面并没有用到spring-boot-starter-data-elasticsearch相关jar包,因为我们公司的springBoot版本是1.5.9。

如果用spring-boot-starter-data-elasticsearch的话,那么elasticsearch版本最高只有2.4.4,这也太落后了,现在elasticsearch已经到6.3.2了,为了用更好的版本有两个方案:

1、提高springboot版本到2.X(不过不现实,船大难掉头),2、用原生的TransportClient实现。最终落地实现是通过TransportClient实现

把关键代码展示出来。

1、pom.xml

    <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency> <dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.8</version>
</dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>

2、创建实体

    @Configuration
public class ServerModule { @Bean
public TransportClient transportClient() {
Settings settings = Settings.builder().put("cluster.name", "biteniuniu").build();
//我用6.3.2版本的时候这里一直报异常说找不到InetSocketTransportAddress类,这应该和jar有关,当我改成5.6.8就不报错了
TransportClient client = new PreBuiltTransportClient(settings);//6.3.2这里TransportAddress代替InetSocketTransportAddress
client.addTransportAddress(new InetSocketTransportAddress(
new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));
return client;
}
}

3、NoticeController类

@RestController
@RequestMapping("/api/v1/notice")
public class NoticeController { @Autowired
private TransportClient transportClient; /**
*利用TransportClient实现搜索功能
* @param title 搜索标题
* @param page = 从第几条结果返回 | Integer(比如一次size=20,page=0,如果要显示下一页20条记录则需要size=20,page=20)这个和之前有点区别, size = 每页显示条数
*/ @RequestMapping(value = "trsearch", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public CommandResult<List<Notice>> search(@RequestParam(value = "title", defaultValue = "比特币")String title, @RequestParam(value = "page", defaultValue = "0")Integer page,
@RequestParam(value = "size", defaultValue = "20")Integer size) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//按标题进行查找
boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));

//在这里输入索引名称和type类型
SearchResponse response = transportClient.prepareSearch("wantu_notice_info").setTypes("doc") // 设置查询类型java
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
// 设置查询关键词
.setQuery(boolQueryBuilder)
// 设置查询数据的位置,分页用
.setFrom(page)
// 设置查询结果集的最大条数
.setSize(size)
// 设置是否按查询匹配度排序
.setExplain(true)
// 最后就是返回搜索响应信息
.get();
SearchHits searchHits = response.getHits(); List<Notice> list = Lists.newArrayListWithCapacity(size); for (SearchHit searchHit : searchHits) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
//获得titie数据
String titles = (String) sourceAsMap.get("title");
//获得阅读量数据
Integer readCount = (Integer) sourceAsMap.get("read_count");
//把数据装入对象中
Notice notice=new Notice();
notice.setTitle(titles);
notice.setReadCount(readCount);
list.add(notice);
} return CommandResult.ofSucceed(list);
} }

4、运行结果

总结下:第一种整合相对简单很多,因为本身封装很多东西,比如分页,封装数据等。第二种的话可以在不用spring的情况下使用它。

我只是偶尔安静下来,对过去的种种思忖一番。那些曾经的旧时光里即便有过天真愚钝,也不值得谴责。毕竟,往后的日子,还很长。不断鼓励自己,

天一亮,又是崭新的起点,又是未知的征程(上校4)

ElasticSearch(2)---SpringBoot整合ElasticSearch的更多相关文章

  1. 【SpringBoot整合Elasticsearch】SpringBoot整合ElasticSearch

    一.Linux下安装ElasticSearch 1.检测是否安装了Elasticsearch ps aux |grep elasticsearch 2.安装JDK 3.下载Elasticsearch ...

  2. SpringBoot整合ElasticSearch实现多版本的兼容

    前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...

  3. springboot整合elasticsearch入门例子

    springboot整合elasticsearch入门例子 https://blog.csdn.net/tianyaleixiaowu/article/details/72833940 Elastic ...

  4. Springboot整合elasticsearch以及接口开发

    Springboot整合elasticsearch以及接口开发 搭建elasticsearch集群 搭建过程略(我这里用的是elasticsearch5.5.2版本) 写入测试数据 新建索引book( ...

  5. SpringBoot整合Elasticsearch详细步骤以及代码示例(附源码)

    准备工作 环境准备 JAVA版本 java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121 ...

  6. Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]

    Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...

  7. Springboot整合ElasticSearch进行简单的测试及用Kibana进行查看

    一.前言 搜索引擎还是在电商项目.百度.还有技术博客中广泛应用,使用最多的还是ElasticSearch,Solr在大数据量下检索性能不如ElasticSearch.今天和大家一起搭建一下,小编是看完 ...

  8. 😊SpringBoot 整合 Elasticsearch (超详细).md

    SpringBoot 整合 Elasticsearch (超详细) 注意: 1.环境搭建 安装es Elasticsearch 6.4.3 下载链接 为了方便,环境使用Windows 配置 解压后配置 ...

  9. SpringBoot整合elasticsearch

    在这一篇文章开始之前,你需要先安装一个ElasticSearch,如果你是mac或者linux可以参考https://www.jianshu.com/p/e47b451375ea,如果是windows ...

随机推荐

  1. linux上部署JMeter

    export JAVA_HOME=/opt/jdk1.8.0_171 export PATH=$PATH:$JAVA_HOME/bin 让环境变量生效 vi /etc/profile 添加下述两行: ...

  2. mysql驱动问题

    Unknown initial character set index '255' received from server. Initial client character 解决方法 驱动版本不对 ...

  3. python默认参数陷阱

    对于学习python的人都有这样的困惑 def foo(a=[]): a.append(5) return a Python新手希望这个函数总是返回一个只包含一个元素的列表:[5].结果却非常不同,而 ...

  4. 修改 salt-minion 的 ID 后报错解决方法

    当在搭建 Saltstack 集中化管理平台配置完毕时,启动服务时,不知道是否你也越到过如下报错的现象呢? 报错问题如下: [root@saltstack_web1group_1 ~]# vim /e ...

  5. 微服务框架——SpringCloud(四)

    1.Spring Cloud Config 分布式配置 a.Config服务器 ①新建springboot项目,依赖选择Config Server ②pom文件关键依赖 <parent> ...

  6. Jmeter中实现base64加密

    Jmeter已不再提供内置base64加密函数,遇到base64加密需求,需要通过beanshell实现 直接上beanshell代码: import org.apache.commons.net.u ...

  7. Windows linux子系统 使用说明

    1.安装 linux 子系统 2.应用商店安装ubuntu 3.为了方便可以配置成默认登陆root账户 Ubuntu config –default-user root   4. 安装完毕   5.安 ...

  8. iOS 上传自己的工程(模块工具类)到cocoapods上遇到坑

    最近在研究把自己写的工具类和模块上传到cocoapods上, 再新构建项目中可以直接使用cocoapods使用  也可以更新之前的版本 便于维护项目. 但是在这个过程中遇到了种种问题 但是最后还是解决 ...

  9. Centos 7安装python3(PY3.6)

    # 安装 sudo yum install centos-release-scl sudo yum install rh-python36 #开启 scl enable rh-python36 bas ...

  10. VB控件间的拖放

    新建工程,放置控件Picture1,Text1,Text2,复制下面的代码运行 Text1和Text2可以互相拖放,也可以将Picture1拖放给Text1,Text2. Private Sub Fo ...