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的更多相关文章

  1. Spring Boot整合Elasticsearch

    Spring Boot整合Elasticsearch   Elasticsearch是一个全文搜索引擎,专门用于处理大型数据集.根据描述,自然而然使用它来存储和搜索应用程序日志.与Logstash和K ...

  2. 【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 ], ...

  3. Elasticsearch学习(3) spring boot整合Elasticsearch的原生方式

    前面我们已经介绍了spring boot整合Elasticsearch的jpa方式,这种方式虽然简便,但是依旧无法解决我们较为复杂的业务,所以原生的实现方式学习能够解决这些问题,而原生的学习方式也是E ...

  4. Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...

  5. spring boot 整合 elasticsearch 5.x

    spring boot与elasticsearch集成有两种方式.一种是直接使用elasticsearch.一种是使用data中间件. 本文只指针使用maven集成elasticsearch 5.x, ...

  6. Spring Boot 整合 elasticsearch

    一.简介 我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选.他可以快速的存储.搜索和分析海量数据.Spring Boot通过整合Spring Data E ...

  7. Elasticsearch学习(1) Spring boot整合Elasticsearch

    本文的Spring Boot版本为1.5.9,Elasticsearch版本为2.4.4,话不多说,直接上代码. 一.启动Elasticsearch 在官网上下载Elasticsearch后,打开bi ...

  8. Spring Boot整合ElasticSearch和Mysql 附案例源码

    导读 前二天,写了一篇ElasticSearch7.8.1从入门到精通的(点我直达),但是还没有整合到SpringBoot中,下面演示将ElasticSearch和mysql整合到Spring Boo ...

  9. Elasticsearch学习(4) spring boot整合Elasticsearch的聚合操作

    之前已将spring boot原生方式介绍了,接下将结介绍的是Elasticsearch聚合操作.聚合操作一般来说是解决一下复杂的业务,比如mysql中的求和和分组,由于博主踩的坑比较多,所以博客可能 ...

随机推荐

  1. SpringBoot项目后台对接微信支付开发——微信统一下单接口开发

    开始没找到微信支付的sdk.自己根据官方给的接口文档纯手写,各种xml转JSON,JSON转xml,加密解密,签名....整个人都是崩溃的 开发的第三天,发现有官方的sdk.心情一下子豁然开朗,整个人 ...

  2. 实战_3:新建产品配置(product)并导出项目

    产品配置Product 产品配置用于定义和管理RCP应用的多个方面特征.并支持将RCP项目导出为部署包(类似eclipse压缩包),可以直接部署到其他环境上使用. 产品配置必须新建一个 扩展名为 .p ...

  3. 82)PHP,基本框架类步骤

    framework.class.php 基本代码展示: <?php /** * 框架初始化功能类 */ class Framework { /** * 入口 * 里面的static和self是一 ...

  4. Ananconda常用指令

    Anaconda指的是一个开源的Python发行版本,其包含了conda.Python等180多个科学包及其依赖项,可用于解决开发过程中遇到python版本需要切换的问题. conda有一点好处是,如 ...

  5. java 二分法查找原理

    二分法查找原理: 1.只要低位下标不大于高位下标,就进行二分查找(步骤1-3) 2.先在有序的数组中对半查找中间的坐标,如果中标和要查找的下标相等时,找到目标数,那二分结束. 3.如果步骤2没有找到, ...

  6. Redis学习之热点key重建

    在Redis的生产环境中,大量客户端连接请求某一个key,但都需要从DB中获取数据,来回写数据库,如下图: <ignore_js_op> 造成的问题: 大量的线程请求数据库,造成数据库压力 ...

  7. 浏览器证书问题,chorm,ie,edge,safari都会去读系统证书,firefox例外

    坑爹 没想过浏览器兼容的问题. 为系统安装用户证书后, firefox一直无法连接 提示 连接 www.httpsserver.com:8985 时发生错误. SSL 对等端无法协商出一个可接受的安全 ...

  8. ZOJ-1177-K-Magic Number

    就是分别以1到9作为开头构造结果,取最小答案.看了参考书之后才做出来,对参考书上的代码进行了一些改进 Accepted 1177 C++11 0 408 #include "bits/std ...

  9. JS一维数组、多维数组和对象的混合使用

    转载地址:http://blog.csdn.net/wangyuchun_799/article/details/38460515 引言 这篇文章的主要目的是讲解JavaScript数组和对象的混合使 ...

  10. 吴裕雄--天生自然python学习笔记:Python CGI编程

    什么是CGI CGI 目前由NCSA维护,NCSA定义CGI如下: CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户 ...