前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot下ElasticSearch的使用

SpringBoot下ElasticSearch的使用

作者头像
姜同学
发布2022-10-27 16:50:30
2590
发布2022-10-27 16:50:30
举报
文章被收录于专栏:姜同学姜同学

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
复制
运行结果
创建索引结果
创建索引结果
查询结果
查询结果
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-06T,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档