spring boot 整合elasticsearch
1.导入jar包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.5.4</version>
</dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
2.编写elasticsear远程连接配置文件
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.net.InetAddress; @Configuration
public class ElasticSearchConfig { @Bean
public TransportClient transportClient() throws Exception{
//此处需要使用elastic服务的tcp端口默认是9300
InetSocketTransportAddress master = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.242"), 9300);
InetSocketTransportAddress node1 = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.108"), 9300);
InetSocketTransportAddress node2 = new InetSocketTransportAddress(InetAddress.getByName("192.168.30.82"), 9300); Settings settings = Settings.builder().put("cluster.name", "elasticCluster").build(); TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(master);
client.addTransportAddress(node1);
client.addTransportAddress(node2);
return client;
}
}
3.实现elasticsearch的基本操作
@RestController
public class TestController { @Autowired
private TransportClient transportClient; //查询
@GetMapping(value = "/get")
public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) { if (id.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
} GetResponse result = transportClient.prepareGet("book", "novel", id).get(); if (!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
} return new ResponseEntity(result.getSource(), HttpStatus.OK);
} //新增
@PostMapping(value = "/add")
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") String publishdate) { try {
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject()
.field("title", title)
.field("author", author)
.field("word_count", wordCount)
.field("publish_date", publishdate).endObject();
IndexResponse result = transportClient.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);
}
} //删除
@GetMapping(value = "/delete")
public ResponseEntity delete(@RequestParam(name = "id") String id) {
DeleteResponse result = transportClient.prepareDelete("book", "novel", id).get(); return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
} //修改
@PostMapping(value = "/update")
public ResponseEntity update(@RequestParam(name = "id") String id,
@RequestParam(name = "title", required = false) String title,
@RequestParam(name = "author", required = false) String author) { UpdateRequest updateRequest = new UpdateRequest("book", "novel", id); try {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); if (title != null) {
builder.field("title", title);
} if (author != null) {
builder.field("author", author);
}
builder.endObject();
updateRequest.doc(builder); UpdateResponse result = transportClient.update(updateRequest).get();
return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
} //复核查询
@PostMapping(value = "/query")
public ResponseEntity query(@RequestParam(name = "author", required = false) String author,
@RequestParam(name = "title", required = false) String title,
@RequestParam(name = "gt_word_count", required = false) Integer gtWordCount,
@RequestParam(name = "lt_word_count", required = false) Integer ltWordCount) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (author != null) {
boolQueryBuilder.must(QueryBuilders.matchQuery("author", author));
} if (title != null) {
boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
} RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
if (ltWordCount != null && ltWordCount > 0) {
rangeQueryBuilder.to(ltWordCount);
} boolQueryBuilder.filter(rangeQueryBuilder); SearchRequestBuilder builder = transportClient.prepareSearch("book")
.setTypes("novel")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQueryBuilder)
.setFrom(0)
.setSize(10); System.out.println(builder); SearchResponse response = builder.get();
List<Map<String, Object>> result = new ArrayList<>(); for (SearchHit hit : response.getHits()) {
result.add(hit.getSource());
} return new ResponseEntity(result, HttpStatus.OK);
}
spring boot 整合elasticsearch的更多相关文章
- Spring Boot整合Elasticsearch
Spring Boot整合Elasticsearch Elasticsearch是一个全文搜索引擎,专门用于处理大型数据集.根据描述,自然而然使用它来存储和搜索应用程序日志.与Logstash和K ...
- 【spring boot】【elasticsearch】spring boot整合elasticsearch,启动报错Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8
spring boot整合elasticsearch, 启动报错: Caused by: java.lang.IllegalStateException: availableProcessors ], ...
- Elasticsearch学习(3) spring boot整合Elasticsearch的原生方式
前面我们已经介绍了spring boot整合Elasticsearch的jpa方式,这种方式虽然简便,但是依旧无法解决我们较为复杂的业务,所以原生的实现方式学习能够解决这些问题,而原生的学习方式也是E ...
- Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...
- spring boot 整合 elasticsearch 5.x
spring boot与elasticsearch集成有两种方式.一种是直接使用elasticsearch.一种是使用data中间件. 本文只指针使用maven集成elasticsearch 5.x, ...
- Spring Boot 整合 elasticsearch
一.简介 我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选.他可以快速的存储.搜索和分析海量数据.Spring Boot通过整合Spring Data E ...
- Elasticsearch学习(1) Spring boot整合Elasticsearch
本文的Spring Boot版本为1.5.9,Elasticsearch版本为2.4.4,话不多说,直接上代码. 一.启动Elasticsearch 在官网上下载Elasticsearch后,打开bi ...
- Spring Boot整合ElasticSearch和Mysql 附案例源码
导读 前二天,写了一篇ElasticSearch7.8.1从入门到精通的(点我直达),但是还没有整合到SpringBoot中,下面演示将ElasticSearch和mysql整合到Spring Boo ...
- Elasticsearch学习(4) spring boot整合Elasticsearch的聚合操作
之前已将spring boot原生方式介绍了,接下将结介绍的是Elasticsearch聚合操作.聚合操作一般来说是解决一下复杂的业务,比如mysql中的求和和分组,由于博主踩的坑比较多,所以博客可能 ...
随机推荐
- 文本输入框input将输入转换为统一大小写
转载地址:http://blog.csdn.net/yieryi_/article/details/52078596 文本输入框input将输入转换为统一大小写,通常有两种方法:JS和CSS方法. 1 ...
- iOS动画效果集合、 通过摄像头获取心率、仿淘宝滑动样式、瀑布流、分类切换布局等源码
iOS精选源码 动画知识运用及常见动画效果收集 较为美观的多级展开列表 MUImageCache -简单轻量的图片缓存方案 iOS 瀑布流之栅格布局 一用就上瘾的JXCategoryView iOS ...
- K3CLOUD表关联
销售订单关联发货通知单 销售订单表 T_SAL_ORDER A T_SAL_ORDERENTRY B T_SAL_ORDERENTRY_LK C 发货通知单表 T_SAL_DELIVERYNOTICE ...
- 信息熵、信息增益、信息增益率、gini、woe、iv、VIF
整理一下这几个量的计算公式,便于记忆 采用信息增益率可以解决ID3算法中存在的问题,因此将采用信息增益率作为判定划分属性好坏的方法称为C4.5.需要注意的是,增益率准则对属性取值较少的时候会有偏好,为 ...
- 框架之MyBatis
什么是框架,简单的来说框架就是一个程序的半成品,而我们就是的工作就是根据我们的工作需要将其完善.MyBatis框架的作用就是将我们使用JDBC操作数据库的过程移交给MyBatis,让它来帮我们完成这些 ...
- WebFilter 在springBoot工程中不起作用
[1]@ServletComponentScan 必须有一个注解将带有@WebFilter的类包含进去. [2]自定义 FiltersConfig extends WebMvcConfigurerAd ...
- ionic2踩坑之ionic build android报错
自己项目一直跑的好好好好的,build还是run都没问题,今天忽然一个小伙伴build一直报错.\ 错误如下: Error occurred during initialization of VMCo ...
- 吴裕雄--python学习笔记:sqlite3 模块的使用与学生信息管理系统
import sqlite3 cx = sqlite3.connect('E:\\student3.db') cx.execute( '''CREATE TABLE StudentTable( ID ...
- python socket粘包及实例
1.在linux中经常出现粘包的出现(因为两个send近靠着,造成接受到的数据是在一起的.)解决方法: 在服务端两send的中间中再添加一个recv(),客户端添加一个send(),服务端收到信息确认 ...
- Django学习之路02
静态文件配置 html文件默认全都放在templates文件夹下 对于前段已经写好了的文件, 我们只是拿过来使用 那么这些文件都可以称之为叫"静态文件"静态文件可以是 bootst ...