springBoot配置elasticsearch搜索

摘要:
1.本地安装弹性搜索服务。有关具体过程,请参阅前一篇文章2。修改项目中的pom文件并介绍与搜索相关的jar包!

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

  springBoot配置elasticsearch搜索第1张

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()));

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

  springBoot配置elasticsearch搜索第2张

       ②、批量新增索引数据 ( 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" }} 
" +
        "{" +
        ""user":"kimchy1"," +
        ""postDate":"2013-01-30"," +
        ""message":"trying out Elasticsearch1"" +
        "} 
";  //一定要加换行
json += "{ "index" : { "_id" : "2" }} 
" +
        "{" +
        ""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表示修改成功

  springBoot配置elasticsearch搜索第3张

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

       ④、删除指定索引

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

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

springBoot配置elasticsearch搜索第4张

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

//根据属性值来删除索引
//删除user="kimchy2"的索引
String queryString = "{
" +
        "  "query": {
" +
        ""match_phrase":  {"user": "kimchy2"}
" +
        "}
" +
        "}
";
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())));

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

springBoot配置elasticsearch搜索第5张

  ⑥、删除所有索引数据

//删除所有索引数据
String queryString = "";
queryString = "{
" +
        "  "query": {
" +
        ""match_all":  {}
" +
        "}
" +
        "}
";
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 = "{ 
" +
                      ""query" : { 
" +
                           ""match_phrase": { "user": { "query" : "kimchy1", "boost" :"5" }}}
" +
                      "}
" +
                  "}";
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搜索第6张

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

免责声明:文章转载自《springBoot配置elasticsearch搜索》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue 使用vuedraggable 实现列表拖拽排序田忌赛马下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Node.js如何执行cmd

最近,由于业务需求,有必要研究如何根据vscode插件的名称下载相应的插件,以解决打包插件并将其上载到服务器所导致的延迟问题。灵感是件好事。本文主要讨论Node.js如何执行cmd。除了我一开始说的,还有很多应用场景,但只有意想不到的。正如我们的经理所说,现在20%的技术基本上可以解决80%的业务问题。在这个时代,技术有点泛滥,换句话说,技术过剩。...

kettle的job中运行每行

有时,在运行作业中的每一行时,我们需要多次执行作业或转换。假设我们需要导入从开始日期到昨天的所有旧数据。手动执行作业是痛苦和错误的。Kettle可以首先计算正确的日期,然后根据每个日期执行导入作业。在主作业中,返回日期转换首先运行,实际导入数据的作业在转换后运行。它是一个子作业,负责运行每个输入日期。子作业接收每行的“date”日期参数并执行它。在演示示例中...

CorelDRAW 编写和运行宏指令

在开发和运行CorelDRAW宏之前,必须安装VBA组件。在CoerlDRAW11和12中安装CorelDRAWVBAVBA是典型安装的一部分。2如果安装开始,请单击安装CorelDRAW12 Graphics Suite。CorelDRAWVBA工具栏CorelDRaw工具栏提供了几个快速的VBA函数和对VB编辑器的访问。但是,您可以通过在CorelDRA...

C# Winform Treeview控件

WinformTreeview控件目录手动添加节点。丰富节点数据并清除所有节点信息。选择指定的节点。函数GetAllTreeNodeWinformTreeview控件手动添加节点//在根节点下添加根节点和子节点TreeNodeCollectionRoot=treeView1.Nodes;TreeNodecurNode=根。添加(“良好”);curN(电流)...

plsql 导出查询结果

单击青色按钮,表示所查询的所有数据都将导出到指定文件,而不仅仅是以下列表中显示的数据行;无需单击“获取最后一页”按钮。注意:选择导出到excel文件时,需要注意默认导出为*。xlsx格式。您可以选择*。xls格式,但*。xls格式只能容纳65536行数据。如果要导出的数据超过最大值,则必须更改为*。xlsx格式!如果您仍然使用此格式,后面的数据将覆盖以前的数...

Python-正则

,三:量词*重复0次或多次{0,}+重复一次或多次{1,}?重复0或1次{1,0}{n}重复n次{n}{n,}重复n次,或更多次{n,m}将n次重复到m次Escape:如果字符串中有特殊字符要匹配,请在常规字符和字符串前面添加r。如果特殊字符在字符组中,则它们是匹配的特殊字符,但为了记忆,匹配时会转义所有特殊字符。...