SpringBoot2 集成 ElasticSearch 实现搜索引擎

一 简介

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。

二 安装

Linux系统:centos7下搭建 ElasticSearch 环境。

三 与 Spring boot2 集成

3.1 pxm.xml依赖

        
        
		    org.elasticsearch.client
		    elasticsearch-rest-high-level-client
		    6.5.4
            
                
                    org.elasticsearch.client
                    elasticsearch-rest-client
                
            
		

        
        
            org.elasticsearch
            elasticsearch
            6.5.4
        

        
            org.elasticsearch.client
            elasticsearch-rest-client
            6.5.4
        

3.2 配置文件

# es 配置
spring.elasticsearch.host=172.16.20.101
spring.elasticsearch.port=9200

3.3 config 配置类

package com.modules.common.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * elasticsearch 配置类
 *
 * @author lc
 */
@Configuration
public class ElasticsearchConfig {

    @Value(value = "${spring.elasticsearch.host}")
    private String host;

    @Value(value = "${spring.elasticsearch.port}")
    private int port;

    /**
     * 初始化
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
//                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost(host, port, "http")));
        return client;
    }
}

3.4 代码实现

@Autowired
private RestHighLevelClient client;

3.4.1 添加文档

    /**
     * 添加文档
     *
     * @throws
     * @author lc
     */
    @ApiOperation(value = "添加文档", notes = "添加文档")
    @PostMapping(value ="addIndex")
    public Result addIndex(Goods info, String indexName, String type) throws IOException {
        // IndexRequest
        IndexRequest indexRequest = new IndexRequest(indexName, type);
        String source = JSON.toJSONString(info);
        indexRequest.source(source, XContentType.JSON);
        // 操作ES
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        return success(indexResponse);
    }

3.4.2 修改文档

    /**
     * 修改文档
     *
     * @author lc
     */
    @ApiOperation(value = "修改文档", notes = "修改文档")
    @PutMapping(value = "updateIndex")
    public Result updateIndex(Goods info, String indexName, String type) throws IOException {
        // UpdateRequest
        UpdateRequest updateRequest = new UpdateRequest(indexName, type, info.getId());
        updateRequest.doc(JSON.toJSONString(info), XContentType.JSON);
        // 操作ES
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        return success(updateResponse);
    }

3.4.3 删除文档

 
    /**
     * 删除文档
     *
     * @author lc
     */
    @ApiOperation(value = "删除文档", notes = "删除文档")
    @DeleteMapping(value = "deleteById")
    public Result deleteById(String id, String indexName, String type) throws IOException {
        // DeleteRequest
        DeleteRequest deleteRequest = new DeleteRequest(indexName,type,id);
        // 操作ES
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        return success(deleteResponse);
    }

3.4.4 获取ES信息

    /**
     * 获取ES信息
     *
     * @throws IOException
     * @author lc
     */
    @ApiOperation(value = "获取ES信息", notes = "获取ES信息")
    @GetMapping(value = "getEsInfo")
    public Result getEsInfo() throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // SearchRequest
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.source(searchSourceBuilder);
        // 查询ES
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        return success(searchResponse);
    }

3.4.5 根据ID查询

    /**
     * 根据ID查询
     *
     * @author lc
     */
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询")
    @GetMapping(value = "getInfoById")
    public Result getInfoById(String id, String indexName, String type) throws IOException {
        // GetRequest
        GetRequest getRequest = new GetRequest(indexName, type, id);
        // 查询ES
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        Goods info = JSON.parseObject(getResponse.getSourceAsString(), Goods.class);
        return success(info);
    }

3.4.6 条件分页简单列表搜索

    /**
     * 简单分页条件列表搜索
     *
     * @param page
     * @param size
     * @param keyword
     * @throws
     * @author lc
     */
    @ApiOperation(value = "简单分页条件列表搜索", notes = "简单分页条件列表搜索")
    @GetMapping(value = "search")
    public Result search(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size,
                       String keyword) throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 分页采用简单的from + size分页,适用数据量小的,了解更多分页方式可自行查阅资料
        searchSourceBuilder.from((page - 1) * size);
        searchSourceBuilder.size(size);
        //  matchQuery:会将搜索词分词,再与目标查询字段进行匹配,若分词中的任意一个词与目标字段匹配上,则可查询到。
        //  termQuery:不会对搜索词进行分词处理,而是作为一个整体与目标字段进行匹配,若完全匹配,则可查询到。
        // 查询条件,只有查询关键字不为空才带查询条件
        if (StringUtils.isNoneBlank(keyword)) {
            QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "title");
            searchSourceBuilder.query(queryBuilder);
        }
        QueryBuilders.fuzzyQuery("","").fuzziness(Fuzziness.ONE);
        // 排序,根据ID倒叙
        // searchSourceBuilder.sort("id", SortOrder.DESC);
        // SearchRequest
        SearchRequest searchRequest = new SearchRequest("index_goods");
        searchRequest.types("_doc");
        searchRequest.source(searchSourceBuilder);
        // 查询ES
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        // 获取总数
        Long total = hits.getTotalHits();
        // 遍历封装列表对象
        List list = new ArrayList<>();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            list.add(JSON.parseObject(searchHit.getSourceAsString(), Goods.class));
        }
        // 封装Map参数返回
        Map result = new HashMap(16);
        result.put("total", total);
        result.put("list", list);
        return success(result);
    }

你可能感兴趣的:(Spring,Cloud,springboot,ElasticSearch,搜索引擎,检索,es)