<?php
namespace app\cli\controller;
use think\Controller;
use think\Request;
class Es extends Controller
{
/**
* 创建商品索引并导入全部商品文档
* cd public
* php index.php /cli/Es/createAllGoodsDocs
*/
public function createAllGoodsDocs()
{
try{
//实例化ES工具类
$es = new \tools\es\MyElasticsearch();
//创建索引
if($es->exists_index('goods_index')) $es->delete_index('goods_index');
$es->create_index('goods_index');
$i = 0;
while(true){
//查询商品数据 每次处理1000条
$goods = \app\common\model\Goods::with('category')->field('id,goods_name,goods_desc, goods_price,goods_logo,cate_id')->limit($i, 1000)->select();
if(empty($goods)){
//查询结果为空,则停止
break;
}
//添加文档
foreach($goods as $v){
unset($v['cate_id']);
$es->add_doc($v['id'],$v, 'goods_index', 'goods_type');
}
$i += 1000;
}
die('success');
}catch (\Exception $e){
$msg = $e->getMessage();
die($msg);
}
}
}
<?php
namespace app\home\controller;
use think\Controller;
class Goods extends Base
{
public function index($id=0)
{
//接收参数
$keywords = input('keywords');
if(empty($keywords)){
//获取指定分类下商品列表
if(!preg_match('/^\d+$/', $id)){
$this->error('参数错误');
}
//查询分类下的商品
$list = \app\common\model\Goods::where('cate_id', $id)->order('id desc')->paginate(10);
//查询分类名称
$category_info = \app\common\model\Category::find($id);
$cate_name = $category_info['cate_name'];
}else{
try{
//从ES中搜索
$list = \app\home\logic\GoodsLogic::search();
//dump($list);die;
$cate_name = $keywords;
}catch (\Exception $e){
$this->error('服务器异常');
}
}
return view('index', ['list' => $list, 'cate_name' => $cate_name]);
}
}
//报错:服务器异常
//从ES中搜索
// $list = \app\home\logic\GoodsLogic::search();
////dump($list);die;//打印不出数据
3 个回复
森 - Elasticsearch,php
赞同来自:
wanmony
赞同来自:
wanmony
赞同来自: