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中的求和和分组,由于博主踩的坑比较多,所以博客可能 ...
随机推荐
- Spatial crowdsourcing
空间众包(Spatial crowdsourcing)分类 空间众包是将一组空间任务众包给一组工作人员的过程,这要求工作人员实际位于该位置以执行相应的任务. 空间众包可以根据员工的动机分为两类:基于奖 ...
- [LC] 426. Convert Binary Search Tree to Sorted Doubly Linked List
Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers ...
- 70)PHP,cookie的安全传输和HTTPonly
(1)是否仅安全传输:
- 吴裕雄--天生自然python学习笔记:Matplotlib 基本绘图
使用 Matplotlib 组件绘图时,经常要与 Numpy 组件搭配使用 . 使用 Matplotlib 绘图首先要导入 Matplotlib 组件 , 由于大部分绘图功能是在 matplotlib ...
- RHCE考试(Linux7)
博主本人平和谦逊,热爱学习,读者阅读过程中发现错误的地方,请帮忙指出,感激不尽 一.环境模拟 * server0.example.com :172.25.0.11 * desktop0.example ...
- JDBC介绍和Mybatis运行原理及事务处理
本博客内容非自创,转载自以下三位,侵删: https://juejin.im/post/5ab7bd11f265da23906bfbc5 https://my.oschina.net/fifadxj/ ...
- windows下面 apache 虚拟主机配置
<VirtualHost > ServerAdmin www.test2.com DocumentRoot "D:/PHP/Apache/htdocs/testSite2&quo ...
- 吴裕雄--天生自然python编程:实例
# 该实例输出 Hello World! print('Hello World!') # 用户输入数字 num1 = input('输入第一个数字:') num2 = input('输入第二个数字:' ...
- webdriver访问各个浏览器驱动下载及安装
这里首先需要查看一下自己安装的selenium版本 查看步骤: windows系统打开cmd命令行输入:pip show selenium查看结果如下: 进入到selenium官网查看版本信息 sel ...
- mongodb 4.0配置认证模块
use admin db.createUser({user:"root",pwd:"xxx",roles:[{role:"root",db: ...