比较MYSQL和ElasticSearch的全文搜索差距

起源

  • 商城项目需要根据商品标题或者商品详情,进行模糊查询,在数据量较大的时候,MYSQL进行模糊查询就吃力了,需要使用全文搜索工具,例如使用人数较多的Elasticsearch。为直观比较两者的性能区别,进行了这个实验,并记录下来。

实验基础

1:MYSQL5.7版本 产品表,7万条数据
2:elasticsearch6.8版本
3:composer 加载 下面这两个依赖,用于发送请求和连接数据库,操作ES,自己基于guzzle写

  • “guzzlehttp/guzzle”: “^6.5”,
  • “illuminate/database”: “5.8.*”
    4:PHP版本7.4
为啥不用别人写好的ES包?
  • ES不同版本,区别较大,之前使用Laravel框架,构建全文检索,很费劲,看网上前人经验,没找到合适的。应该主要是版本对应不起来。就使用guzzle直接发请求了。

实验相关代码

index.php

<?php
ini_set("display_error", true);
error_reporting(-1);
require dirname(__FILE__,2) . '\pro1\vendor\autoload.php';//composer依赖自动载入
require './function.php';

$capsule = new Illuminate\Database\Capsule\Manager;
// 创建链接
$capsule->addConnection(  [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'meihui',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix'    => 'ims_',
    ]);

// 设置全局静态可访问DB
$capsule->setAsGlobal();

use Illuminate\Database\Capsule\Manager as DB;

//获取ES版本
//echo ES::getVersion();

$index_name='goods';//ES索引库名,类型名(ES6只支持一个索引库一个类型)

//用于建立ES索引
$mapping=array(
	'mappings'=>[
		$index_name=>[
			'properties'=>[
				'title'=>[
					'type'=>'text',
					'analyzer'=>'ik_max_word'
				],
				'cover'=>[
					'type'=>'keyword'
				],
				'price'=>[
					'type'=>'double'
				]
			]
		]
	]
);

//建立索引
//ES::newIndex($index_name,$mapping);

//将MYSQL数据插入ES

// ini_set('max_execution_time', '0');
// $obj_list = DB::table('zxsite_shop_goods')
//     ->select('id','title','cover','price')
//     ->orderBy('id')
//     ->chunk(200,function($products)use($index_name){
//     		foreach($products as $product){
//     			ES::newDocByID($index_name,$product->id,(array)$product);
//     		}
//     		echo 'OK_';
//     });

$keyword='焦点自动烟盒';//查哪几个关键字
$fields=['title'];//查哪几个字段

$start = microtime(true);
var_dump(ES::keywordSearch($index_name,$keyword,$fields,10,$page=1,$analyzer='ik_max_word'));
// $re=DB::table('zxsite_shop_goods')->where('title','like','%焦点自动烟盒%')->select('id','title','cover')->limit(10)->get();
// var_dump($re);
$end = microtime(true);
$time=$end-$start;
echo '执行了'.$time.'秒';


// var_dump(ES::getMapping($index_name));
// ES::deleteIndex($index_name);

function.php

<?php
class ES{

	public static $host='http://localhost:9200';
	//获取ES版本
	public static function getVersion(){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->get(self::$host);
			$es=json_decode($response->getBody());
			return 'ElasticSearch版本:'.$es->version->number;
		}catch(\Exception $e){
			return '无法连接ES服务器';
		}
	}

	//创建索引
	public static function newIndex($index_name,$mapping){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->put(self::$host.'/'.$index_name,
		    	[GuzzleHttp\RequestOptions::JSON=>$mapping]);
			return json_decode($response->getBody())->acknowledged;
		}catch(\Exception $e){
			return '创建索引失败';
		}
	}

	//删除索引
	public static function deleteIndex($index_name){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->delete(self::$host.'/'.$index_name);
			return json_decode($response->getBody())->acknowledged;
		}catch(\Exception $e){
			return '删除索引失败';
		}
	}

	//获取映射
	public static function getMapping($index_name){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->get(self::$host.'/'.$index_name.'/_mapping');
			return json_decode($response->getBody());
		}catch(\Exception $e){
			return '获取索引失败';
		}
	}

	//添加文档(若已经存在,自动更新)
	public static function newDocByID($index_name,$id,$data){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->put(self::$host.'/'.$index_name.'/'.$index_name.'/'.$id,[GuzzleHttp\RequestOptions::JSON=>$data]);
			return json_decode($response->getBody())->result;
		}catch(\Exception $e){
			return '添加文档失败';
		}
	}
	//更新文档
	public static function updateDocByID($index_name,$id,$data){
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->put(self::$host.'/'.$index_name.'/'.$index_name.'/'.$id.'/_update',[GuzzleHttp\RequestOptions::JSON=>['doc'=>$data]]);
			return json_decode($response->getBody())->result;
		}catch(\Exception $e){
			return '更新文档失败';
		}
	}

	//关键字查询
	public static function keywordSearch($index_name,$keyword,$fields,$size=10,$page=1,$analyzer='ik_max_word'){
		$temp=['query'=>[
			'query_string'=>[
				'query'=>$keyword,
				'analyzer'=>$analyzer,
				'fields'=>$fields]
			],
			'size'=>$size,
			'from'=>($page-1)*$size
		];
		try{
			$http = new GuzzleHttp\Client;
		    $response = $http->get(self::$host.'/'.$index_name.'/'.$index_name.'/_search',[GuzzleHttp\RequestOptions::JSON=>$temp]);
			return json_decode($response->getBody());
		}catch(\Exception $e){
			return '查询文档失败';
		}
	}
}
//创建索引

实验结果

ES 查询,内部4(结果中的took)毫秒,代码中代码段的执行时间10ms左右;
MYSQL查询,内部150毫秒左右,代码中代码段的执行时间180ms左右

七万条数据中查,单从内部查询差异来看对这个结果差异,就30多倍。如果数据量更大,差异应该会更大。MYSQL 的like 全文扫描,是一条数据一条数据校对,而ES是使用直接查索引,拿到结果。

  • mysql内部时间查询: show profiles;
    在这里插入图片描述
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值