1、本地安装elasticsearch服务,具体过程见上一篇文章(安装和配置elasticsearch服务集群)

2、修改项目中pom文件,引入搜索相关jar包

<!-- elasticsearch相关jar包开始 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
     <!-- 链接数据库用的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- elasticsearch相关jar包结束 -->

2、在application.yml文件中添加elasticsearch配置信息

spring:
#elasticsearch配置
data:
elasticsearch: #ElasticsearchProperties
cluster-name: elastic #默认为elasticsearh
cluster-nodes: 192.168.97.88:9300,192.168.97.88:9301 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode

  

3、编写elasticsearch操作的相关类

(1)、获取elasticsearch客户端

//获取elasticsearch客户端
String hostName = "192.168.97.88" ; //本地elasticsearch的yml配置文件中写的IP地址
Integer port = 9200 ; //远程链接的端口号为9200
RestClient restClient = RestClient.builder(new HttpHost(hostName, port)).build();
/*
//如果想要获取阿里云上的elasticsearch客户端,代码如下
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("阿里云elasticsearch用户名", "阿里云elasticsearch密码"));
RestClient restClient = RestClient.builder(new HttpHost("阿里云elasticsearch的ip", 9200))
        .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
        @Override
        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
      return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
       }
        }).setMaxRetryTimeoutMillis(5 * 60 * 1000) //设置超时时间
      .build();
*/

  

(2)、查看索引是否存在 (索引必须为全小写)

//查看 demoIndex 索引是否存在
Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.<String, String>emptyMap());
System.out.println(isExist.getStatusLine().getStatusCode());

(3)、索引不存在,创建索引

//查看 demoIndex 索引是否存在
Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.<String, String>emptyMap());
int status = isExist.getStatusLine().getStatusCode();
if( status == 404){
//不存在索引,创建索引
String method = "PUT";
String endpoint = "demoindex";
Response response = restClient.performRequest(method, "/" + endpoint);
System.out.println(EntityUtils.toString(response.getEntity()));
}

(4)、索引已经创建存在,我们接下来进行索引的  增删改查  操作

①、新增索引数据

//手动拼写一个符合要求的json串   json串的格式为:{"field1":"value1","field2":"value2"}
String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
//发送一个请求,将json转换的实体发送到es,并常见索引,索引主键id=1
Response indexResponse = restClient.performRequest(
"PUT",
"/" + "demoindex" + "/" + "demoindex" + "/1",
Collections.<String, String>emptyMap(),
entity);
//获取结果中的实体,查看是否新增成功
System.out.println(EntityUtils.toString(indexResponse.getEntity()));

  得到如下结果图,表示成功

  

②、批量新增索引数据 ( bulk )

//批量添加索引数据
//手动拼写一个符合要求的json串
// json串的格式为:
// { "index" : { "_id" : "1" }} //这里为手动赋值id,也可以{ "index" : { }}为es自动设置id id相同时后添加的数据会覆盖之前添加的数据
// {"field1":"value1","field2":"value2"}
// { "index" : { "_id" : "2" }}
// {"field1":"value1","field2":"value2"}
String json = "{ \"index\" : { \"_id\" : \"1\" }} \n" +
"{" +
"\"user\":\"kimchy1\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch1\"" +
"} \n"; //一定要加换行
json += "{ \"index\" : { \"_id\" : \"2\" }} \n" +
"{" +
"\"user\":\"kimchy2\"," +
"\"postDate\":\"2014-01-30\"," +
"\"message\":\"trying out Elasticsearch2\"" +
"}";
//将字符串转换成http实体
HttpEntity entity = new NStringEntity(json,ContentType.APPLICATION_JSON);
//发送请求,并的到处理结果
Response response = restClient.performRequest("POST","/demoindex/demoindex/_bulk",Collections.singletonMap("pretty","true"),entity);
//获取结果中的实体,查看是否新增成功
System.out.println(EntityUtils.toString(response.getEntity()));

  得到如下结果图,则表示批量插入成功;若红框裱起来的位置为update表示修改成功

  

③、修改单个索引时去执行插入单个索引,将主键id设置为需要更改的索引id即可

④、删除指定索引

//删除指定id索引
Response deleteResponse = restClient.performRequest(
"DELETE",
"/demoindex/demoindex/3", //删除id为 3 的索引
Collections.<String, String>emptyMap());
System.out.println(EntityUtils.toString(deleteResponse.getEntity()));

  得到如下结果,表示删除成功

  ⑤、根据属性来删除对应索引

//根据属性值来删除索引
//删除user="kimchy2"的索引
String queryString = "{\n" +
" \"query\": {\n" +
"\"match_phrase\": {\"user\": \"kimchy2\"}\n" +
"}\n" +
"}\n";
HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);
Response deleteResponse = restClient.performRequest(
"POST",
"/demoindex/demoindex/_delete_by_query",
Collections.<String, String>emptyMap(),entity);
System.out.println((EntityUtils.toString(deleteResponse.getEntity())));

  得到如下结果图表示删除成功

  ⑥、删除所有索引数据

//删除所有索引数据
String queryString = "";
queryString = "{\n" +
" \"query\": {\n" +
"\"match_all\": {}\n" +
"}\n" +
"}\n";
HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);
Response deleteResponse = restClient.performRequest(
"POST",
"/demoindex/demoindex/_delete_by_query",
Collections.<String, String>emptyMap(),entity);
System.out.println(EntityUtils.toString(deleteResponse.getEntity()));

  ⑦、搜索索引中的数据

//查询索引数据
String queryStr = "{ \n" +
"\"query\" : { \n" +
"\"match_phrase\": { \"user\": { \"query\" : \"kimchy1\", \"boost\" :\"5\" }}}\n" +
"}\n" +
"}";
HttpEntity entity = new NStringEntity(queryStr, ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("GET", "/demoindex/demoindex/" + "_search",Collections.singletonMap("pretty", "true"),entity);
System.out.println(EntityUtils.toString(response.getEntity()));

  得到查询结果

有关更多查询匹配方式请看下一篇文章

springBoot配置elasticsearch搜索的更多相关文章

  1. kotlin + springboot启用elasticsearch搜索

    参考自: http://how2j.cn/k/search-engine/search-engine-springboot/1791.html?p=78908 工具版本: elasticsearch ...

  2. springboot 配置elasticsearch Java High Rest Client

    前提声明 在新版本的spring boot中逐渐放弃了对Spring Data Elasticsearch的支持,所以不推荐使用,使用ES官方推出的Java High Rest Client. 引入依 ...

  3. 基于Spring-Boot框架的Elasticsearch搜索服务器配置

    一.相关包maven配置 <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elastic ...

  4. SpringBoot整合ElasticSearch实现多版本的兼容

    前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...

  5. springboot集成elasticsearch

    在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用: 在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理: 第 ...

  6. 最新学习springboot 配置注解

    一.概述      Spring Boot设计目的是用来简化新Spring应用的初始搭建以及开发过程.Spring Boot并不是对Spring功能上的增强,而是提供了一种快速使用Spring的方式. ...

  7. Springboot整合elasticSearch的官方API实例

    前言:在上一篇博客中,我介绍了从零开始安装ElasticSearch,es是可以理解为一个操作数据的中间件,可以把它作为数据的存储仓库来对待,它具备强大的吞吐能力和计算能力,其基于Lucene服务器开 ...

  8. SpringBoot整合ElasticSearch:基于Jest技术

    1.给pom.xml添加依赖 <!--SpringBoot默认使用SpringData ElasticSearch模块进行操作 <dependency> <groupId> ...

  9. 一次 ElasticSearch 搜索优化

    一次 ElasticSearch 搜索优化 1. 环境 ES6.3.2,索引名称 user_v1,5个主分片,每个分片一个副本.分片基本都在11GB左右,GET _cat/shards/user 一共 ...

随机推荐

  1. Scala数据结构

    Scala数据结构 主要的集合特质 Scala同时支持可变集合和不可变集合,优先采用不可变集合.集合主要分为三大类:序列(List),集(set),映射(map).所有的集合都扩展自Iterable特 ...

  2. SQL server 2014使用导出数据为Excel

    1.打开SQL server 2014,连接至数据库引擎 2.在要导出的数据库上右击,选择"任务->导出数据" 3.数据源选择"SQL Server Native ...

  3. 《VR入门系列教程》之9---谷歌纸盒

    谷歌纸盒---基于智能手机的廉价VR眼镜     如果用汽车来做类比,Oculus Rift和GearVR就是特斯拉和兰博基尼,它们物美但是价不廉.要是主机性能不好,那么几百美元的Oculus眼镜就是 ...

  4. python课堂整理17---文件操作(上)

    1.在同一目录下新建文本文件 “爱了” 2.在该文件下写入内容,同时留意pycharm右下角的编码格式为 utf- 8 3.下面程序中的read函数会索引系统默认的编码格式,winx下是gbk ,所以 ...

  5. 05-k8s调度器、预选策略、优选函数

    目录 k8s调度器.预选策略.优选函数 节点选择过程 调度器 预选策略 优选函数 高级调度设置机制 node选择器/node亲和调度 pod亲和性 污点调度 Taints 与 Tolerations ...

  6. 【Python-Django后端】用户注册通用逻辑,用户名、手机号重名检测,注册成功后状态保持!!!

    用户注册后端逻辑 1. 接收参数 username = request.POST.get('username') password = request.POST.get('password') pas ...

  7. l命令练习题1

    1.创建/guanli 目录,在/guanli下创建zonghe 和 jishu 两个目录(一条命令) [root@localhost ~]# mkdir -p /guanli/zonghe | mk ...

  8. html+css+dom补充

    补充1:页面布局 一般像京东主页左侧右侧都留有空白,用margin:0 auto居中,一般.w. <!DOCTYPE html> <html lang="en"& ...

  9. .NET----错误和异常处理机制

    前言 错误的出现并不总是编写程序的人的原因,有时应用程序会因为应用程序的最终用户引发的动作或运行代码的环境发生错误.无论如何,我们都应预测应用程序中出现的错误,并相应的进行编码. .Net改进了处理错 ...

  10. Starling 环形进度条实现

    项目初期想实现这个效果来着,查了很多资料(包括式神的<神奇的滤镜>),也没找到完美的实现方法,,当时时间紧迫,就找了传统的进度条来代替实现. 最近偶然心血来潮,查了各方面资料,终于找到实现 ...