美文网首页其他高性能web中间件
MySql和ElasticSearch搜索谁更快?

MySql和ElasticSearch搜索谁更快?

作者: HeloWxl | 来源:发表于2019-11-14 23:30 被阅读0次

    前几天学习了我ElasticSearch和SpringBoot整合的相关应用,这个项目我也是参考慕课网上视频学习的,大家如果有兴趣的话,也可以去看一下。链接我放这了。
    Springboot + ElasticSearch 构建博客检索系统

    实现的效果就是如下所示:

    MySQL查询出来的结果


    ElasticSearch查询出来的结果
    image.png

    1、开始准备

    • 开发工具的的话,我这里使用的IDEA、MySql、ElasticSearch。
    • 框架:
      1. SpringBoot
      2. MyBatisPlus
    • 这里是使用Spring Boot搭建JSP页面,大家如果不会的话,可以去参考SpringBoot新建JSP页面

    2、系统结构

    系统结构.png
    • 下面我将按照从上到下依次介绍里面的代码。

    2.1config

    @Configuration
    @MapperScan("com.ols.test.online_learning_system.mapper.*")
    public class MybatisPlusConfig {
        /**
         * 打印 sql
         */
        @Bean
        public PerformanceInterceptor performanceInterceptor() {
            PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
            //格式化sql语句
            Properties properties = new Properties();
            properties.setProperty("format", "true");
            performanceInterceptor.setProperties(properties);
            return performanceInterceptor;
        }
    }
    

    2.2 Controller

    @RequestMapping("MySqlAndEsApi")
    @Controller
    public class MySqlAndEsController {
    
     @Autowired
     private CourseService courseService;
     @Autowired
     private EsCourseRepository esCourseRepository;
    
     @GetMapping("/search")
     @ResponseBody
     public Map<String, Object> getCourseKeyWord(@RequestParam("keyword") String keyword, @RequestParam("type") String type) {
       Map<String, Object> map = new HashMap<String, Object>();
       StopWatch watch = new StopWatch();
       watch.start();
       if (type.equalsIgnoreCase("mysql")) {
         //mysql
         List<Course> list = courseService.getCourseList(keyword);
         map.put("courseList", list);
       } else if (type.equalsIgnoreCase("es")) {
         //es
         BoolQueryBuilder builder = QueryBuilders.boolQuery();
         builder.should(QueryBuilders.matchPhraseQuery("courseName", keyword));
         builder.should(QueryBuilders.matchPhraseQuery("courseIntroduce", keyword));
         String s = builder.toString();
         System.out.println(s);
         Iterable<EsCourse> iterable = esCourseRepository.search(builder);
         List<EsCourse> list = new ArrayList<>();
         Iterator it = iterable.iterator();
         while (it.hasNext()) {
           list.add((EsCourse) it.next());
         }
         System.out.println(list);
         map.put("courseList", list);
       } else {
         map.put("msg", "i don`t understand");
         return map;
       }
       watch.stop();
       long totalTimeMills = watch.getTotalTimeMillis();
       map.put("duration", totalTimeMills);
       return map;
     }
    
     @GetMapping("/toMysqlEs")
     public String toMysqlEs(Model model) {
       List<Course> list = courseService.getCourseList();
       model.addAttribute("courseList", list);
       return "mysql_es";
     }
    }
    

    2.3 es

    2.3.1 entity

    @Data
    @Document(indexName = "coursename",type = "course")
    public class EsCourse {
    
        @Id
        private Integer courseId;
    
        @Field(type = FieldType.Text)
        private String courseName;
    
        @Field(type = FieldType.Text)
        private String coursePicture;
    
        @Field(type = FieldType.Text)
        private String courseVideo;
    
        @Field(type = FieldType.Text)
        private String coursePingfen;
    
        @Field(type = FieldType.Long)
        private Integer teacherId;
    
        @Field(type = FieldType.Text)
        private String courseIntroduce;
    }
    

    2.3.2 repository

    public interface EsCourseRepository extends ElasticsearchRepository<EsCourse, Integer> {
    }
    

    2.4 mapper

    @Mapper
    public interface CourseMapper extends BaseMapper<Course> {
        @Select("select * from course c where c.course_name like CONCAT('%',#{param},'%') or c.course_introduce like CONCAT('%',#{param},'%')")
        List<Course> getCourseList(@Param("param") String param);
    }
    

    2.5 model

    @Data
    public class Course {
        @TableId(value = "course_id",type = IdType.AUTO)
        private Integer courseId;
    
        private String courseName;
    
        private String coursePicture;
    
        private String courseVideo;
    
        private String coursePingfen;
    
        private Integer teacherId;
    
        private String courseIntroduce;
    }
    

    2.6 service

    public interface CourseService {
     List<Course> getCourseList();
      List<Course> getCourseList(@Param("param") String param);
    }
    
    

    2.7 serviceImpl

    @Service
    public class CourseServiceImpl implements CourseService {
    
      @Autowired
      private CourseMapper courseMapper;
      @Override
      public List<Course> getCourseList() {
        EntityWrapper entityWrapper = new EntityWrapper();
        return courseMapper.selectList(entityWrapper);
      }
    
      @Override
      public List<Course> getCourseList(String param) {
        return courseMapper.getCourseList(param);
      }
    }
    

    2.8 OnlineLearningSystemApplication

    @SpringBootApplication
    @MapperScan("com.ols.test.online_learning_system.mapper")
    public class OnlineLearningSystemApplication {
      public static void main(String[] args) {
        SpringApplication.run(OnlineLearningSystemApplication.class, args);
      }
    }
    

    2.9 CoureMapper.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="com.ols.test.online_learning_system.mapper.CourseMapper" >
      <resultMap id="BaseResultMap" type="com.ols.test.online_learning_system.model.Course" >
        <id column="course_id" property="courseId" jdbcType="INTEGER" />
        <result column="course_name" property="courseName" jdbcType="VARCHAR" />
        <result column="course_picture" property="coursePicture" jdbcType="VARCHAR" />
        <result column="course_video" property="courseVideo" jdbcType="VARCHAR" />
        <result column="course_pingfen" property="coursePingfen" jdbcType="VARCHAR" />
        <result column="teacher_id" property="teacherId" jdbcType="INTEGER" />
        <result column="course_introduce" property="courseIntroduce" jdbcType="VARCHAR" />
      </resultMap>
    </mapper>
    

    2.10 application.yml

    spring:
      mvc:
        view:
          prefix: /WEB-INF/views/
          suffix: .jsp
      datasource:
        url: jdbc:mysql://127.0.0.1:3306/es?useUnicode=true&characterEncoding=UTF-8
        username: root
        password: hello@
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
      data:
        elasticsearch:
          cluster-name: elasticsearch
          cluster-nodes: 127.0.0.1:9300
    mybatis-plus:
      mapper-locations: classpath:/mapping/*Mapper.xml
      typeAliasesPackage: com.ols.test.online_learning_system.model
      configuration:
          map-underscore-to-camel-case: true
          cache-enabled: true
          lazyLoadingEnabled: true
          multipleResultSetsEnabled: true
    

    2.11 pom.xml

    关键依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        <!--阿里巴巴连接池-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.9</version>
            </dependency>
    
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
        <!--Mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus</artifactId>
                <version>2.3</version>
            </dependency>
    
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>2.3</version>
            </dependency>
    
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.20</version>
                <scope>provided</scope>
            </dependency>
    
            <!--热部署-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
            </dependency>
         <!--JSP配置-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
    
            <!--tomcat的支持.-->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>
    <!--        elasticsearch-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            </dependency>
    

    3.0 测试

    首页

    页面1.png

    mysql测试

    es测试

    image.png

    终于写完了,忙个半死....

    相关文章

      网友评论

        本文标题:MySql和ElasticSearch搜索谁更快?

        本文链接:https://www.haomeiwen.com/subject/lxmhictx.html