SpringBoot下ElasticSearch的使用

2022-10-27 16:50:30 浏览数 (1)

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

代码语言:javascript复制
ES与MySQL的对比

ES

MySQL

index(索引)

database(数据库)

type(类型):es对海量的数据类型进行分类每个类型下定义一批构相同的document

table(表)

mapping(映射):用来约束该类型下的数据有什么域每个域的类型是什么,用来计算的分次器是什么

schme(表结构):约束表的字段字段类型,主键,索引等等。

dcument(文档):表示一个最小的数据单元(最小样本数据)

row(行数据)

field(域属性)

column(列 字段)

代码语言:javascript复制
导入依赖
代码语言:javascript复制
<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>
代码语言:javascript复制
配置文件中写入相关配置
代码语言:javascript复制

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:
代码语言:javascript复制
识别配置的es的ip和端口信息为TransportClient注入属性
代码语言:javascript复制
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;
    }
}

代码语言:javascript复制
测试代码

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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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();

}

代码语言:javascript复制
运行结果

0 人点赞