博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springBoot配置elasticsearch搜索
阅读量:5294 次
发布时间:2019-06-14

本文共 5946 字,大约阅读时间需要 19 分钟。

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

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

org.springframework.boot
spring-boot-starter-data-elasticsearch
     
org.springframework.boot
spring-boot-starter-jdbc

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 ; //远程链接的端口号为9200RestClient 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.
emptyMap());System.out.println(isExist.getStatusLine().getStatusCode());

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

//查看 demoIndex 索引是否存在Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.
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=1Response indexResponse = restClient.performRequest(       "PUT",       "/" + "demoindex" + "/" + "demoindex" + "/1",       Collections.
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.
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.
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.
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()));

  得到查询结果

 

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

转载于:https://www.cnblogs.com/lazycxy/p/9467792.html

你可能感兴趣的文章
[SCOI2009] windy数
查看>>
053第246题
查看>>
webpack
查看>>
OR(Convex_Optimization_读书杂记)
查看>>
java基础笔记
查看>>
Spring框架IoC和传统bean调用的区别
查看>>
用户登录后的信息存取
查看>>
Win10 linux子系统Ubuntu下显示图形界面
查看>>
(转载)技术人员,请注意那些被你忽略的重要事情
查看>>
模块化(零):综述
查看>>
osgi应用使用桥接的方式打成war包部署在websphere上时遇到的与cxf相关的问题
查看>>
HIbernate中openSession和getCurrentSession
查看>>
Wordpress 建站(一)
查看>>
macOS iTerm2 + Oh My Zsh
查看>>
Ubuntu安装使用iptables
查看>>
【转载】MySQL之CONCAT()的用法
查看>>
今天碰到的400错误
查看>>
C#机器学习之判断日报是否合格
查看>>
asterisk事件监控
查看>>
python的初始化运行了哪些?
查看>>