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. classpath和classpath*区别

    classpath和classpath*区别: classpath:只会到你的class路径中查找找文件. classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找. ...

  2. C#3.0新增功能10 表达式树 07 翻译(转换)表达式

    连载目录    [已更新最新开发文章,点击查看详细] 本篇将介绍如何访问表达式树中的每个节点,同时生成该表达式树的已修改副本. 以下是在两个重要方案中将使用的技巧. 第一种是了解表达式树表示的算法,以 ...

  3. [HDOJ] 1753.大明A+B (大数加法)

    Problem Description 话说,经过了漫长的一个多月,小明已经成长了许多,所以他改了一个名字叫"大明". 这时他已经不是那个只会做100以内加法的那个"小明 ...

  4. 【Arduino】66种传感器系列实验(1)---干簧管传感器模块

    37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器和各种模块,依照实践(动手试试)出真知的理念,以学习和交流为目的,这里 ...

  5. PHP 跨域处理

    PHP 跨域处理 跨域访问失败是会出现 No 'Access-Control-Allow-Origin' header is present on the requested resource. Or ...

  6. java连接oracle数据库jdbc

    driver = oracle.jdbc.driver.OracleDriver url = jdbc:oracle:thin:@localhost:1521:orcl

  7. Ubuntu下Mongo的安装和笔记

    在linux下的安装 打开https://www.mongodb.com/download-center#community选择linux然后选择自己的Version复制DOWNLOAD旁边的链接 打 ...

  8. 图像反转(一些基本的灰度变换函数)基本原理及Python实现

    1. 基本原理 获取像素值在[0, L]范围内的图像的反转图像,即为负片.适用于增强图像中白色或者灰色的区域,尤其当黑色在图片中占主地位时候 $$T(r) = L-r$$ 2. 运行结果 图源自ski ...

  9. 解决跨域session 同步问题

    跨域来源:(前端站点和后端API布署到不同的站点) 解决方案 一.服务端设置 1.配置允许跨域请求 public class BaseAction { /** * 支持跨域请求 * @author f ...

  10. Install eclipse ns3 in ubuntu 14.04

    1. NS3 install 参考NS3 tutorial即可. 2.eclipse 2.1下载 下载地址:http://www.eclipse.org/downloads/              ...