当前位置:   article > 正文

Elastic Search学习四—SpringBoot集成ES_es集成springboot

es集成springboot

一、前言

Elasticsearch 使用的是标准的 RESTful 风格的 API 和 JSON。此外,还构建和维护了很多其他语言的客户端,例如 Java、Python、.NET、SQL 和 PHP。

本章节通过整合Java客户端,实现对 Elasticsearch服务进行访问。

image

二、SpringBoot集成ES步骤

2.1 创建SpringBoot项目

这里使用IDEA创建项目

image-20230528195047313

2.2导入依赖

elasticsearch依赖

<properties>
    <java.version>1.8</java.version>
    <!-- 统一版本 -->
    <elasticsearch.version>7.9.3</elasticsearch.version>
</properties>
  • 1
  • 2
  • 3
  • 4
  • 5
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4

fastjson、lombok依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
<!-- lombok需要安装插件 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

image-20230526140137334

2.3创建配置类

1.es没有密码配置

@Configuration
public class ElasticSearchConfig {
    // 注册 rest高级客户端 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2.带密码(es设置密码情况下,需配置)

@Configuration
public class ElasticSearchConfig {
    // 注册 rest高级客户端
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        HttpHost host=new HttpHost("10.7.71.112", 9200, HttpHost.DEFAULT_SCHEME_NAME);
        RestClientBuilder builder=RestClient.builder(host);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "gree@2020"));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        RestHighLevelClient restClient = new RestHighLevelClient( builder);
        return restClient;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

image-20230531142422368

2.4创建并编写实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    private String name;
    private Integer age;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.5测试API

2.5.1创建索引

package com.gree.esdemo7;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class EsDemo7ApplicationTests {

    @Autowired
    public RestHighLevelClient restHighLevelClient;

    @Test
    void contextLoads() {
    }

    //创建索引
    @Test
    public void testCreateIndex() throws IOException{
        CreateIndexRequest request = new CreateIndexRequest("user_index");
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
        System.out.println(response);
        restHighLevelClient.close();
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

image-20230526142130677

image-20230526142012436

2.5.2删除索引

image-20230526143309644

2.5.3文档查询

1.查询流程

1、创建 SearchRequest搜索请求
创建 SearchRequest 搜索请求,如果不带参数,表示查询所有索引

2、创建 SearchSourceBuilder条件构造
创建 SearchSourceBuilder条件构造,构建搜索的条件。
添加大部分查询参数到 SearchSourceBuilder,还可以接收 QueryBuilders构建的查询参数。

3、将 SearchSourceBuilder 添加到 SearchRequest中

4、执行查询

5、解析查询结果

示例:

image-20230526161458449

2.查看查询条件

image

这里打印出来的查询语句,为json格式,即RestFul API接口执行语句

image

3.分页查询

示例1

public List<String> getPageDocumentsByIndex(String index, int pageNum, int pageSize) {
	try {
		SearchRequest searchRequest = new SearchRequest(index);
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		// 查询索引下所有的文档
		sourceBuilder.query(QueryBuilders.matchAllQuery());
		//计算出记录起始下标
		int from = (pageNum - 1) * pageSize;
		// 起始记录下标,从0开始
		sourceBuilder.from(from);
		//每页显示的记录数
		sourceBuilder.size(pageSize);

		searchRequest.source(sourceBuilder);

		SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
		SearchHits searchHits = response.getHits();
		List<String> result = new ArrayList<>();
		searchHits.forEach(searchHit -> result.add(searchHit.getSourceAsString()));
		return result;
	} catch (Exception e) {
		log.error("查询索引[{}]的文档失败", index, e);
		throw new MyException("查询索引[" + index + "]的文档失败");
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

示例2

@RestController
@RequestMapping("/es")
public class SearchController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @PostMapping("/article/{keyWords}")
    public List<Map<String,Object>> articleSearch(@PathVariable("keyWords") String keyWords) throws IOException {

        //通过关键词查询相应文章,返会id,标题,相应内容
        SearchRequest searchRequest = new SearchRequest("article");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //设置高亮
        //searchSourceBuilder.highlighter(new HighlightBuilder());
        //System.out.println(key);

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("content", keyWords);
        searchSourceBuilder.query(termQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        SearchHits hits = response.getHits();
        Long totalHits = hits.getTotalHits().value;
        System.out.println("查询的结果条数:"+totalHits);


        List<Map<String,Object>> results=new ArrayList<>();
        for (SearchHit documentFields : hits) {
            System.out.println(documentFields.getSourceAsString());
            results.add(documentFields.getSourceAsMap());

        }
        return results;

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

image-20230529151813472

转换成对象输出

@RestController
@RequestMapping("/es")
public class SearchController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @GetMapping("/article/{keyWords}")
    public List<ArticleDO> articleSearch(@PathVariable("keyWords") String keyWords) throws IOException {

        //通过关键词查询相应文章,返会id,标题,相应内容
        SearchRequest searchRequest = new SearchRequest("article");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("content");
        searchSourceBuilder.highlighter(highlightBuilder);


        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("content", keyWords);
        searchSourceBuilder.query(termQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        SearchHits hits = response.getHits();
        Long totalHits = hits.getTotalHits().value;
        System.out.println("查询的结果条数:"+totalHits);

        //遍历结果
        List<Map<String,Object>> results=new ArrayList<>();
        for (SearchHit documentFields : hits) {
            System.out.println(documentFields.getSourceAsString());
            results.add(documentFields.getSourceAsMap());

        }

        //listmap转换为list对象
        List<ArticleDO> list = JSON.parseArray(JSONArray.toJSONString(results), ArticleDO.class);

        return list;


    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

image-20230529180018563

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/785791
推荐阅读
相关标签
  

闽ICP备14008679号