Elasticsearch-Sql+Mybatis+SpringBoot集成

本文介绍了springboot如何集成elasticsearch-sql+mybatis

大家好!ElasticSearch(下面用es作为缩减)作为开源界搜索和数据分析的宠儿,受到了很多公司的青睐,无论是查询速度,还是扩展性,容错性都是很不错的,而且配合官方的logstashkibana,以及filebeat,更是如虎添翼,但是es的transport client的api是解析非常困难,而且大家又习惯了sql语法,所以在es5.x版本以后已经有elasticsearch-sql的插件,在6.4版本以后,这个插件无需安装,自带的功能。下面给大家介绍一下es-sql的使用方法

rest方式使用es-sql

下面我给大家简要看一下如何用rest方式来执行es-sql

  1. curl
    POST /_xpack/sql?format=txt
    {
     "query": "select sum(money) from trade "
    }
    
  2. 学习链接地址https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html

JDBC方式用springboot+mybatis访问

1.maven依赖引入

         <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>x-pack-sql-jdbc</artifactId>
            <version>6.4.3</version>
        </dependency>
    如果引入失败,将jar包下载下来,用下面的方式引入,将jar包下载下来,到本地文件夹,然后引入
        <dependency>
          <groupId>org.elasticsearch.plugin</groupId>
          <artifactId>x-pack-sql-jdbc</artifactId>
          <version>6.4.3</version>
          <systemPath>${project.basedir}/../lib/x-pack-sql-jdbc-6.4.3.jar</systemPath>
          <scope>system</scope>
      </dependency>
  1. mybatis config文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <settings>    <!-- 开启二级缓存 -->
       <setting name="cacheEnabled" value="true"/>

       <!-- 打印查询语句 -->
       <setting name="logImpl" value="STDOUT_LOGGING" />
       <setting name="useColumnLabel" value="false" />
   </settings>
</configuration>

-比较重要的地方

<setting name="useColumnLabel" value="false" />

这句话一定要添加

  1. application.yml添加一下配置
spring:
 datasource: 
   es: 
     url: jdbc:es://host地址:9200
     driver-class-name: org.elasticsearch.xpack.sql.jdbc.jdbc.JdbcDriver
     mapperLocations: classpath:mapper/es/*.xml
     configLocation: classpath:config/mybatis.cfg.xml

4.EsDruidDataSourceConfig 类,我用的是druid连接池,你们在用的时候需要把这个连接池在pom文件中引入一下

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
* @program: 
* @description: es 数据源配置
* @author: sunyf
* @create: 2018-11-16 19:15
**/
@Configuration
@MapperScan(basePackages = {"cc.youshu.eurekaclient.dao.es"}, sqlSessionFactoryRef = "esSqlSessionFactory")
public class EsDruidDataSourceConfig {

   @Value("${spring.datasource.es.configLocation}")
   private String configLocation;

   @Value("${spring.datasource.es.mapperLocations}")
   private String bigdataMapperLocations;

   @Value("${spring.datasource.es.url}")
   private String esUrl;
   
   @Bean(name = "esDataSource")
   public DataSource esDataSource() {
       DruidDataSource dataSource = new DruidDataSource();
       dataSource.setDriverClassName("org.elasticsearch.xpack.sql.jdbc.jdbc.JdbcDriver");
       dataSource.setUrl(esUrl);
       return dataSource;
   }

   /**
    * SqlSessionFactory配置
    *
    * @return
    * @throws Exception
    */
   @Bean(name = "esSqlSessionFactory")
   public SqlSessionFactory bigdataSqlSessionFactory(@Qualifier("esDataSource") DataSource dataSource) throws Exception {
       SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
       sqlSessionFactoryBean.setDataSource(dataSource);

       PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
       //配置mapper文件位置
       sqlSessionFactoryBean.setMapperLocations(resolver.getResources(bigdataMapperLocations));
       sqlSessionFactoryBean.setConfigLocation(resolver.getResource(configLocation));
       return sqlSessionFactoryBean.getObject();
   }

}
  1. 至此已经引入完毕,下面就是和你们正常的一样,写一个mapper文件,然后启动springboot项目,下面是我的mapper文件


import org.apache.ibatis.annotations.Mapper;

/**
1. @program: youshu_stat
2. @description: trade表数据库接口
3. @author: sunyf
4. @create: 2018-11-16 18:08
**/
@Mapper
public interface RwTradeMapper {
   Long testSql();
}

-下面是我的mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cc.youshu.eurekaclient.dao.es.RwTradeMapper">
<select id="testSql" resultType="java.lang.Long">
    select trade_no  from rw_trade limit 1
</select>
</mapper>
  1. 最后我给出来我的测试类
import cc.youshu.eurekaclient.EurekaClientApplication;
import cc.youshu.eurekaclient.dao.es.RwTradeMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


/**
* @program: youshu_stat
* @description: 测试
* @author: sunyf
* @create: 2018-11-16 18:16
**/

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaClientApplication.class)
public class ApplicationTests {

   @Autowired
   private RwTradeMapper rwTradeMapper;

   @Test
   @Rollback
   public void testRwTradeMapper() throws Exception {
       Long s= rwTradeMapper.testSql();
       System.out.println("输出订单号为"+s);
   }

}

使用es-sql需要是购买x-pack,本人提供破解的6.4.0版本jar包,其他步骤,网上教程一堆,jar包地址https://download.csdn.net/download/qq_34748569/10866788

你可以找到更多关于 es-sql的信息 https://www.elastic.co/products/stack/elasticsearch-sql.

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论
在Spring Boot中集成MyBatis和Elasticsearch(ES)可以通过以下步骤完成: 1. 添加依赖: 在`pom.xml`文件中添加MyBatis和ES的依赖。 ```xml <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- Elasticsearch --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置数据源: 在`application.properties`或`application.yml`文件中配置MyBatis和ES的数据源信息。 ```yaml # MyBatis mybatis.type-aliases-package=com.example.model mybatis.mapper-locations=classpath:mapper/*.xml # Elasticsearch spring.data.elasticsearch.cluster-name=my-es-cluster spring.data.elasticsearch.cluster-nodes=localhost:9300 ``` 3. 创建实体类和Mapper: 创建实体类和对应的Mapper接口,用于定义数据库表的映射关系和操作。 ```java // 实体类 public class User { private Long id; private String name; // 省略getter和setter } // Mapper接口 public interface UserMapper { User getUserById(Long id); void insertUser(User user); } ``` 4. 编写Mapper XML: 在`resources/mapper`目录下创建对应的Mapper XML文件,定义SQL语句和参数映射。 ```xml <!-- UserMapper.xml --> <mapper namespace="com.example.mapper.UserMapper"> <select id="getUserById" parameterType="java.lang.Long" resultType="com.example.model.User"> SELECT * FROM user WHERE id = #{id} </select> <insert id="insertUser" parameterType="com.example.model.User"> INSERT INTO user (id, name) VALUES (#{id}, #{name}) </insert> </mapper> ``` 5. 编写Elasticsearch Repository: 创建Elasticsearch Repository接口,用于定义ES的索引和操作。 ```java public interface UserRepository extends ElasticsearchRepository<User, Long> { List<User> findByName(String name); } ``` 6. 使用MyBatis和ES: 在Service或Controller层中注入MyBatis的Mapper和ES的Repository,即可进行数据库和ES的操作。 ```java @Service public class UserService { @Autowired private UserMapper userMapper; @Autowired private UserRepository userRepository; public User getUserById(Long id) { return userMapper.getUserById(id); } public void insertUser(User user) { userMapper.insertUser(user); userRepository.save(user); } public List<User> searchUserByName(String name) { return userRepository.findByName(name); } } ``` 这样,你就成功地在Spring Boot中集成MyBatis和Elasticsearch。你可以使用MyBatis进行数据库操作,同时使用ES进行全文搜索等功能。希望对你有帮助!如果还有其他问题,请继续提问。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闻神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值