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中的求和和分组,由于博主踩的坑比较多,所以博客可能 ...
随机推荐
- rsyslog与journal日志架构
系统日志架构概述 在centos7系统中有两个日志服务,分别是传统的rsyslog和新添加的systemd-journal systemd-journal是一个改进型的日志管理服务,可以收集来自内核. ...
- Wanna go back home
题目描述 Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginnin ...
- matplotlib.pyplot.contour 简单等高线绘制
contour(X, Y, Z) X,Y是与Z形状相同的二维数组,可以通过 numpy.meshgrid()创建. numpy.meshgrid()----从坐标向量返回坐标矩阵 生成的x,y坐标矩阵 ...
- Java 集合的迭代方式
集合的迭代流使得程序员得以站在更高的抽象层次上对集合进行操作.传统的迭代方法直接看代码: List<Dog> dogs = new ArrayList<>(); ...
- python——删除列表中的元素
在python中,删除列表元素的方法有三种,分别为remove(),del(),pop()函数 (1)remove() >>> name = ['小明','小华','小红','小李' ...
- stack|session|fuss|anniversary
N-COUNT A stack of things is a pile of them. 摞; 堆 例: There were stacks of books on the bedside table ...
- 公式化学习urllib(第一卷)
Import urllib.request 正常爬取网页: url=网址 +代表 下面测试一下: 结果我就不显示了 令html为读取后的对象 先用正则表达式抓取数据 Import re 令rule是抓 ...
- spring学习笔记三:Component注解(把POJO类实例化到spring的IOC容器中)
Component注解:把普通的POJO 类实例化到spring的IOC容器中,就是定义成<bean id="" class=""> 项目目录树: ...
- Tuning xgboost in R:Part 1
第一次调整Boosting算法的参数可能是一个非常艰难的任务.有很多参数可供选择,调整不同的参数会有不同的结果产生.最好的调参可能是取决于数据.每当我得到一个新的数据集,我都会学到一些新的东西.对分类 ...
- Protocol Buffers学习(4):更多消息类型
介绍一下消息的不同类型和引用 使用复杂消息类型 您可以使用其他消息类型作为字段类型.例如,假设你想在每个SearchResponse消息中包含Result消息,您可以在同一个.proto中定义一个Re ...