SpringBoot2.2.0 整合ElasticSearch7.2

导入依赖

	 <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.2.0</version>
        </dependency>

版本对应 ES安装的版本。

application.yml中写入

elasticsearch:
   host: 192.168.80.130
   port: 9200

还需要做一个配置文件。我定义的是EsConfig

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {
    private String host;
    private Integer port;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, port, "http")
        ));
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}

简单的 增删改查 模糊查询 代码如下

@Service
public class NbaPlayerServiceImpl extends ServiceImpl<NbaPlayerMapper, NbaPlayer> implements INbaPlayerService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    private static final String NBA_INDEX = "nba_latest";

    /**
     * 增
     *
     * @param nbaPlayer
     * @param id
     * @return
     * @throws IOException
     */
    @Override
    public boolean addPlayer(NbaPlayer nbaPlayer, String id) throws IOException {
        //new IndexRequest(NBA_INDEX)----索引别名 .id 索引的key   .source---索引的值(文档_doc)
        IndexRequest request = new IndexRequest(NBA_INDEX).id(id).source(BeanToMap.beanToMap(nbaPlayer, (int) (this.count(null) / 0.75) + 1));
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return false;
    }

    /**
     * 查
     *
     * @param id
     * @return
     * @throws IOException
     */
    @Override
    public Map<String, Object> getPlayer(String id) throws IOException {
        GetRequest request = new GetRequest(NBA_INDEX, id);
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        return response.getSource();
    }

    /**
     * 改
     *
     * @param nbaPlayer
     * @param id
     * @return
     * @throws IOException
     */
    @Override
    public boolean updatePlayer(NbaPlayer nbaPlayer, String id) throws IOException {
        UpdateRequest request = new UpdateRequest(NBA_INDEX, id).doc(BeanToMap.beanToMap(nbaPlayer, (int) (this.count(null) / 0.75) + 1));
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return true;
    }

    /**
     * 删
     *
     * @param id
     * @return
     * @throws IOException
     */
    @Override
    public boolean deletePlayer(String id) throws IOException {
        DeleteRequest request = new DeleteRequest(NBA_INDEX, id);
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return false;
    }

    /**
     * 删除全部
     *
     * @return
     * @throws IOException
     */
    @Override
    public boolean deleteAllPlayer() throws IOException {
        DeleteByQueryRequest request = new DeleteByQueryRequest(NBA_INDEX);
        // 设置查询条件,第一个参数是字段名,第二个参数是字段的值
        request.setQuery(QueryBuilders.matchAllQuery());
        // 刷新索引
        request.setRefresh(true);
        BulkByScrollResponse response = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));

        return true;
    }

    /**
     * 导入数据
     * @return
     * @throws IOException
     */
    @Override
    public boolean importAll() throws IOException {
        List<NbaPlayer> list = this.list(null);
        Iterator<NbaPlayer> iterator = list.iterator();
        while (iterator.hasNext()) {
            NbaPlayer nbaPlayer = iterator.next();
            addPlayer(nbaPlayer, String.valueOf(nbaPlayer.getId()));
        }
        return true;
    }

    /**
     * 根据名字查询
     * @param key
     * @param value
     * @return
     * @throws IOException
     */
    @Override
    public List<NbaPlayer> searchMatch(String key,String value) throws IOException {
        SearchRequest request = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery(key,value));
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(100);
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(search));

        SearchHit[] hits = search.getHits().getHits();
        List<NbaPlayer> players = new LinkedList<>();
        for(SearchHit hit : hits){
            NbaPlayer nbaPlayer = JSONObject.parseObject(hit.getSourceAsString(), NbaPlayer.class);
            players.add(nbaPlayer);
        }
        return players;
    }

    /**
     * 根据词条精确查询
     * @param key
     * @param value
     * @return
     * @throws IOException
     */
    @Override
    public List<NbaPlayer> searchMaTerm(String key,String value) throws IOException {
        SearchRequest request = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery(key+".keyword",value));
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(100);
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(search));

        SearchHit[] hits = search.getHits().getHits();
        List<NbaPlayer> players = new LinkedList<>();
        for(SearchHit hit : hits){
            NbaPlayer nbaPlayer = JSONObject.parseObject(hit.getSourceAsString(), NbaPlayer.class);
            players.add(nbaPlayer);
        }
        return players;
    }

    /**
     * 查询全部
     * @return
     * @throws IOException
     */
    @Override
    public List<NbaPlayer> searchMatch_All() throws IOException {
        SearchRequest request = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        builder.from(0);
        builder.size(1000);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<NbaPlayer> players = new LinkedList<>();
        for(SearchHit hit : hits){
            NbaPlayer nbaPlayer = JSONObject.parseObject(hit.getSourceAsString(), NbaPlayer.class);
            players.add(nbaPlayer);
        }
        return players;

    }

    /**
     * 根据单词前缀匹配查询(区分大小写)
     * @param key
     * @param value
     * @return
     * @throws IOException
     */
    @Override
    public List<NbaPlayer> searchPrefix(String key, String value) throws IOException {
        SearchRequest request = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.prefixQuery(key+".keyword",value));
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(100);
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(search));

        SearchHit[] hits = search.getHits().getHits();
        List<NbaPlayer> players = new LinkedList<>();
        for(SearchHit hit : hits){
            NbaPlayer nbaPlayer = JSONObject.parseObject(hit.getSourceAsString(), NbaPlayer.class);
            players.add(nbaPlayer);
        }
        return players;
    }
}

this.count(null)

这个方法是 Mybatis-Plus中取数据库 中数据条数的方法

BeanToMap.beanToMap(nbaPlayer, (int) (this.count(null) / 0.75) + 1))

将对象转Map集合(nbaPlayer-----实体类对象名,后面的参数则是map长度),
根据阿里开发规范中说道,为了调高map集合运行效率 应当在创建集合时为其附上一定的长度,
公式为 (数据长度/0.75)+1

代码如下

public static <T> Map<String, Object> beanToMap(T bean, int size) {
        Map<String, Object> map = new HashMap<>(size);
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if(beanMap.get(key) != null) {
                    map.put(key + "", beanMap.get(key));
                }
            }
        }
        return map;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值