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中的求和和分组,由于博主踩的坑比较多,所以博客可能 ...
随机推荐
- Linear Equations
4.1 Linear Equations with One Independent Variable
- fcntl()函数之文件打开状态
比较有用的就两个. 1.获得/设置文件打开状态标志 oldflag=fcntl(fd,F_GETFL); 获得打开文件的状态标志. arg=oldflag|O_APPEND; fcntl(fd,F_S ...
- spring创建bean异常
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappi ...
- [LC] 78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solut ...
- [LC] 125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...
- 吴裕雄--天生自然python学习笔记:pandas模块读取 Data Frame 数据
读取行数据 读取一个列数据的语法为: 例如,读取所有学生自然科目的成绩 : import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56 ...
- 如何消除img间的默认间隙
方案一:div{font-size:0};方案二:img{ display:block};方案三:img{vertical-align:top;}方案四:div{ margin-bottom:-3px ...
- python学习笔记(10)函数(二)
(函数的参数&递归函数) 一.函数的参数 Python的函数定义非常简单,但灵活度却非常大.除了正常定义的必选参数外,还可以使用默认参数.可变参数和关键字参数,使得函数定义出来的接口,不但能处 ...
- 吴裕雄--天生自然Android开发学习:下载安装android stuio集成开发工具
下载链接: https://developer.android.google.cn/index.html
- lower_bound()函数使用
lower_bound()函数需要加头文件#include<algorithm>,其基本用途是查找(返回)有序区间中第一个大于或等于给定值的元素的位置,其中排序规则可以通过二元关系来表示. ...