栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

从零搭建springcloud项目- elasticsearch(7)

从零搭建springcloud项目- elasticsearch(7)

1、springcloud集成es,es的搭建不多说,直接配置项目,依赖,es选择版本是7.7

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

2、配置yml

spring:
  profiles:
    active: dev
  datasource:      #配置数据库
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3307/springcloud_test002?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  redis:
    host: 192.168.110.12
    port: 6379
    password: Cc68db0e
    
elasticsearch:
  host: 192.168.110.12
  port: 9200
  username: 账号
  password: 密码

3、配置类

package com.example.test002.config.elastic;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


@Configuration
@Primary
public class ElasticConfig extends AbstractFactoryBean {

    private static final Logger LOG = LoggerFactory.getLogger(com.example.test002.config.elastic.ElasticConfig.class);

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

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

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    private RestHighLevelClient restHighLevelClient;

    @Override
    public void destroy() throws Exception {
        // 关闭Client
        if (restHighLevelClient != null) {
            restHighLevelClient.close();
        }
    }

    @Override
    public Class getObjectType() {
        return RestHighLevelClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    protected Object createInstance() throws Exception {
        try {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
          
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            // 如果有多个节点,构建多个HttpHost
            RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, "http"))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    });
            restHighLevelClient = new RestHighLevelClient(builder);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return restHighLevelClient;
    }
}
 

实体

package com.example.test002.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@NoArgsConstructor
@AllArgsConstructor
public final class ElasticEntity {

    private String id;
    private String _id;
    private T data;
}

4、编写工具类

package com.example.test002.mapper.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.test002.entity.ElasticEntity;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class ElasticSearchMapper {

    @Resource
    private RestHighLevelClient client;

    
    public boolean createIndex(String index, String source) {
        try {
            CreateIndexRequest request = new CreateIndexRequest(index);
            request.mapping(source, XContentType.JSON);
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            return createIndexResponse.isAcknowledged();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    
    public boolean indexExist(String index) {
        try {
            GetIndexRequest request = new GetIndexRequest(index);
            request.local(false);
            request.humanReadable(true);
            request.includeDefaults(false);
            return client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    
    public boolean insertOne(String index, ElasticEntity entity) {
        IndexRequest indexRequest = new IndexRequest(index);
        String userJson = JSONObject.toJSonString(entity.getData());
        indexRequest.source(userJson, XContentType.JSON).id(entity.get_id());
        try {
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            if (indexResponse != null) {
                if (indexResponse.getResult() == DocWriteResponse.Result.CREATED || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    
    public  List listByBuilder(String[] indexArray, SearchSourceBuilder searchSourceBuilder, Class c) {
        SearchRequest request = new SearchRequest(indexArray);
        searchSourceBuilder.trackTotalHits(true);
        request.source(searchSourceBuilder);
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            List res = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                Map sourceAsMap = hit.getSourceAsMap();
                String json = JSON.toJSonString(sourceAsMap);
                res.add(JSON.parseObject(json, c));
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

5、测试

package com.example.test002.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.test002.entity.ElasticEntity;
import com.example.test002.entity.SysUserDO;
import com.example.test002.mapper.common.ElasticSearchMapper;
import com.example.test002.mapper.common.RedisMapper;
import org.elasticsearch.common.unit.Timevalue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;



@RestController
@RefreshScope               //nacos配置中心动态刷新
public class ElasticsearchController {

    @Resource
    private ElasticSearchMapper elasticSearchMapper;

    
    @GetMapping(value = "/es/createIndex")
    public boolean createIndex() throws InterruptedException {
        // 大致意思就是配置了四个字段,id、username、tel、rolename
        // username和rolename 指定使用ik分词器,后面搜索的时候可以分词搜索
        String source =  "{" +
                "            "properties": {" +
                "                "id": {" +
                "                    "type": "long"" +
                "                }," +
                "                "username": {" +
                "                    "type": "text"," +
                "                    "analyzer": "ik_max_word"," +
                "                    "search_analyzer": "ik_max_word"" +
                "                }," +
                "                "tel": {" +
                "                    "type": "keyword"" +
                "                }," +
                "                "rolename": {" +
                "                    "type": "text"," +
                "                    "analyzer": "ik_max_word"," +
                "                    "search_analyzer": "ik_max_word"" +
                "                }" +
                "            }" +
                "        }";


        JSonObject json = JSONObject.parseObject(source);
        String s = JSONObject.toJSonString(json);

        boolean index = elasticSearchMapper.createIndex("test_user", s);
        return index;
    }

    
    @GetMapping(value = "/es/indexExist")
    public boolean indexExist() throws InterruptedException {

        boolean index = elasticSearchMapper.indexExist("test_user");
        return index;
    }

    
    @GetMapping(value = "/es/insertOne")
    public boolean insertOne() throws InterruptedException {
        SysUserDO user = new SysUserDO();
        user.setId(1);
        user.setRolename("测试一下");
        user.setUsername("我是测试");
        user.setTel("1311111111");

        ElasticEntity entity = new ElasticEntity();
        entity.setData(user);

        boolean index = elasticSearchMapper.insertOne("test_user", entity);
        return index;
    }

    
    @GetMapping(value = "/es/listByBuilder")
    public List listByBuilder() throws InterruptedException {
        // 使用分词,查询username和rolename中含有测试的
        QueryBuilder nameQuery = QueryBuilders.matchQuery("username", "测试").analyzer("ik_max_word");
        QueryBuilder roleQuery = QueryBuilders.matchQuery("rolename", "测试").analyzer("ik_max_word");

        
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(nameQuery);
        boolQueryBuilder.should(roleQuery);

        
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.explain(true);
        sourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS));
        sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        sourceBuilder.query(boolQueryBuilder);

        String[] indexArray = new String[]{"test_user"};
        List userList = elasticSearchMapper.listByBuilder(indexArray, sourceBuilder, SysUserDO.class);

        return userList;
    }

}

6、启动项目,访问创建索引

查看索引情况

判断索引是否存在

 插入数据

查询数据

 

 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号