SpringBoot下ElasticSearch的使用

Java
447
0
0
2022-12-17

es是啥不说了往期写过这次直接干货。

ES与MySQL的对比

导入依赖
<dependency>
	<groupId>org.elasticsearch.plugin</groupId>
	<artifactId>transport-netty4-client</artifactId>
	<version>5.5.0</version>
</dependency>

<dependency>
	<groupId>org.elasticsearch</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>5.5.0</version>
</dependency>

<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>transport</artifactId>
	<version>5.5.0</version>
	<exclusions>
		<exclusion>
		<groupId>*</groupId>
		<artifactId>transport-netty4-client</artifactId>
		</exclusion>
	</exclusions>
</dependency>
配置文件中写入相关配置

server.port=

# mysql相关配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jmy?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root

#驼峰命名的对应关系
mybatis.configuration.mapUnderscoreToCamelCase=true
#缓存关掉
mybatis.configuration.cacheEnabled=false 
#es
jmy.es.nodes=192.168.249.130:
识别配置的es的ip和端口信息为TransportClient注入属性
package com.jmy.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "jmy.es")
public class EsConfig {

    private List<String> nodes;

    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }

    @Bean
    public TransportClient transportClient() throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);

        for (String node : nodes) {
            String ip = node.split(":")[];
            String port = node.split(":")[];
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip),Integer.parseInt(port)));
        }

        return client;
    }
}

测试代码

封装的数据库查询结果对象

package com.jmy.domain;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PutQuestion {
    private Integer userId;
    private Integer pqId;
    private String pqTitle;
    private String pqDate;
    private String pqText;
    private Integer pqRead;
    private Integer pqAnswer;
    private String pqType;
    private String pqStatus;
    private Integer pqKiss;
    private String pqTop;
    private String pqLike;
    private String pqLev;
}

controller

package com.jmy.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmy.service.EsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EsController {

    @Autowired 
    private EsService esService;

    @RequestMapping("/") 
    public String createEsIndex(){
        esService.createEsIndex();
        return "创建成功:true";
    }

    // 只是演示所以之展示第一条数据 
    @RequestMapping("/query/{query}") 
    public  String queryIndex(@PathVariable("query") String query) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(esService.queryIndex(query).get());
    }
}

service

package com.jmy.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmy.domain.PutQuestion;
import com.jmy.mapper.PQMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EsService {
    // 注入ES配置类 
    @Autowired 
    private TransportClient client;

    @Autowired 
    private PQMapper pqMapper;

    public void createEsIndex() {
        ObjectMapper om = new ObjectMapper();
        // 读取数据源
        List<PutQuestion> putQuestions = pqMapper.queryAllQuestion();

        // 创建索引
        client.admin().indices().prepareCreate("jmy").get();
        // 创建document 
        for (PutQuestion pq:putQuestions) {
            try {
                String pqJson = om.writeValueAsString(pq);
                // 定义该样本的索引 类型 以及标识
                client.prepareIndex("jmy","qutQuestion",pq.getPqId().toString()).setSource(pqJson).get();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    public List<PutQuestion> queryIndex(String query){
        ObjectMapper om = new ObjectMapper();
        // 使用client封装查询对象 
        MultiMatchQueryBuilder matchQuery = QueryBuilders.multiMatchQuery(query, "pqTitle","pqId");
        SearchRequestBuilder search = client.prepareSearch("jmy");
        SearchResponse response = search.setQuery(matchQuery).setFrom().setSize().get();

        // 获取PutQuest对象
        SearchHit[] searchHits = response.getHits().getHits();
        List<PutQuestion> list = new ArrayList<>();
        try {
            for (SearchHit hit : searchHits) {
                String pqJson = hit.getSourceAsString();
                list.add(om.readValue(pqJson,PutQuestion.class));
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return list;
    }
}

mapper

package com.jmy.mapper;

import com.jmy.domain.PutQuestion;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface PQMapper {

    // 查询数据库中b_pq表中的所有数据 
    @Select("select * from b_pq order by pq_id desc")
    List<PutQuestion> queryAllQuestion();

}

运行结果

img

img