springcloud全家桶个人博客系统(五)RestHighLevelClient实现elasticsearch全文检索及结果高亮

一、前言

上个版本使用springdata elasticsearch,但是也只是支持到了elasticsearch 2点几的版本,并不适合继续深入的挖掘。本次使用elasticsearch6.4.2版本,使用RestHighLevelClient客户端,吐嘈一下,transport客户端真的恶心,各种莫名其妙的错误,什么堆栈溢出,找不到节点,反正不好用,个人感觉。

二、配置

1.application.properties

#Elasticserch
elasticsearch.port=9200
elasticsearch.ip=127.0.0.1
elasticsearch.connectTimeOut=1000
elasticsearch.socketTimeOut=30000
elasticsearch.connectionRequestTimeOut=500
elasticsearch.maxConnectNum=100
elasticsearch.maxConnectPerRoute=100

注意:9200,不是9300,9200才是rest的端口

2.ElasticsearchConfig

    private ArrayList hostList;
    @Value(value = "${elasticsearch.port}")
    private Integer port;
    @Value(value = "${elasticsearch.ip}")
    private String hosts;
    /** 连接超时时间 */
    @Value("${elasticsearch.connectTimeOut}")
    private static int connectTimeOut;
    /** 连接超时时间 */
    @Value("${elasticsearch.socketTimeOut}")
    private static int socketTimeOut;
    /** 获取连接的超时时间 */
    @Value("${elasticsearch.connectionRequestTimeOut}")
    private int connectionRequestTimeOut;
    /** 最大连接数 */
    @Value("${elasticsearch.maxConnectNum}")
    private int maxConnectNum;
    /** 最大路由连接数 */
    @Value("${elasticsearch.maxConnectPerRoute}")
    private int maxConnectPerRoute;

    @PostConstruct
    public void init() {
        hostList = new ArrayList<>();
        String[] hostStrs = hosts.split(",");
        for (String host : hostStrs) {
            // 使用的协议
            String schema = "http";
            hostList.add(new HttpHost(host, port, schema));
        }
    }

    @Bean
    public RestHighLevelClient client() {
        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        // 异步httpclient连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });
        // 异步httpclient连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }

注意:PostConstruct设置该方法为init方法 

三、es操作工具类

  private final RestHighLevelClient restHighLevelClient;
    private static final String ES_TYPE = "article";
    private static final String ES_INDEX = "article";

    @Autowired
    public EsUtil(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }


    @PostConstruct
    public void init() throws IOException {
        if (!existsIndex()) {
            CreateIndexRequest request = new CreateIndexRequest("article");
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
            log.info("createIndex: " + JSON.toJSONString(createIndexResponse));

        }
    }

    private boolean existsIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices("article");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        log.info("existsIndex: " + exists);
        return exists;
    }

    public void addData(Blog blog, String id) throws IOException {
        IndexRequest indexRequest = new IndexRequest(ES_INDEX, ES_TYPE, id);
        indexRequest.source(JSONObject.toJSONString(blog), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("add: " + JSON.toJSONString(indexResponse));
    }

    public void updateDataById(Blog blog, String id) throws IOException {
        UpdateRequest request = new UpdateRequest(ES_INDEX, ES_TYPE, id);
        request.doc(JSONObject.toJSONString(blog), XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        log.info("update: " + JSON.toJSONString(updateResponse));
    }

    public void deleteDataById(String id) throws IOException {
        DeleteRequest request = new DeleteRequest(ES_INDEX, ES_TYPE, id);
        DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        log.info("delete: "+JSON.toJSONString(deleteResponse));
    }

    public List searchDataPage(int startRow, int size, BoolQueryBuilder queryBuilder) throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        sourceBuilder.from(startRow);
        // 获取记录数,默认10
        sourceBuilder.size(size);

        //设置高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        sourceBuilder.highlighter(highlightBuilder);

        SearchRequest searchRequest = new SearchRequest(ES_INDEX);
        searchRequest.types(ES_TYPE);
        searchRequest.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //遍历结果
        for(SearchHit hit : response.getHits()){
            Map source = hit.getSourceAsMap();
            //处理高亮片段
            Map highlightFields = hit.getHighlightFields();
            HighlightField nameField = highlightFields.get("title");
            if(nameField!=null){
                Text[] fragments = nameField.fragments();
                StringBuilder nameTmp = new StringBuilder();
                for(Text text:fragments){
                    nameTmp.append(text);
                }
                //将高亮片段组装到结果中去
                source.put("title", nameTmp.toString());
                log.info(source.toString());
            }
        }
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();
        List blogList = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            JSONObject jsonObject = new JSONObject(hit.getSourceAsMap());
            log.info("search:{}", jsonObject.toJSONString());
            blogList.add(JSONObject.toJavaObject(jsonObject, Blog.class));
        }
        return blogList;
    }

四、效果

springcloud全家桶个人博客系统(五)RestHighLevelClient实现elasticsearch全文检索及结果高亮_第1张图片

可以看见title已经有高亮的语法了。

五、github地址

https://github.com/sustly/blog_vue_server

注意:master分支才是springcloud版本

 

 

你可能感兴趣的:(springcloud,elasticsearch,elasticsearch)