1. 程式人生 > WINDOWS開發 >xunsearch 在 window 下測試實踐(2)

xunsearch 在 window 下測試實踐(2)

# 在 Laravel框架 下,還有 Xunsearch 生成的骨架程式碼基礎上,測試 Xunsearch 基礎用法;程式碼匯入資料、更新、刪除、搜尋,基本功能就有了;

<?php

namespace App\Http\Controllers;

use App\Post;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;

//載入XS.php
require_once "../vendor/xunsearch/lib/XS.php";

class XunsearchController extends Controller { public function __construct() { } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $keyword = !empty($request->all()[‘wd‘]) ? $request
->all()[‘wd‘] : ‘‘; $page = !empty($request->all()[‘page‘]) ? $request->all()[‘page‘] : 1; // TODO xunsearch 迅搜測試 if($keyword){ $count = $total = $search_cost = 0; $docs = $related = $corrected = $hot = array(); $error = $pager = ‘‘;
try { $xs = new \XS(‘laravel‘); //// 建立 XS 物件 $index = $xs->index; // 獲取索引物件 $search = $xs->search; // 獲取搜尋物件 // TODO 清空索引 $index->clean(); die; $arr = Post::all()->toArray(); foreach ($arr as $v){ $document = new \XSDocument($v); // TODO 新增資料,不管是否已經存在相同主鍵資料 $index->add($document); // TODO 更新資料,同主鍵則更新資料,不同則新增(推薦) $index->update($document); // TODO 刪除資料,傳入主鍵,單個可直接傳,多個放陣列中,例如 array(1,3,5) if(in_array($v[‘id‘],[2,4])){ // 刪除掉主鍵為 2,4的資料 $index->del($v[‘id‘]); } } // 同步索引資料 $index->flushIndex(); } catch (\XSException $e) { echo $e->getMessage() . PHP_EOL; exit; } $listRows = 3; $search->setLimit($listRows,$listRows*($page-1)); // 設定偏移量 $search_begin = microtime(true); $docs = $search->setQuery($keyword)->search(); // 查詢 $search_cost = microtime(true) - $search_begin; // $count = $search->count($keyword); // // 直接檢索關鍵詞的數量 $count = $search->getLastCount(); // 獲取搜尋總數,這個和count()的不一樣是不用傳入搜尋詞 $total = $search->getDbTotal(); // TODO 返回糾正後的關鍵片語成的陣列 if ($count < 1 || $count < ceil(0.001 * $total)) { $corrected = $search->getCorrectedQuery(); } $hot = $search->getHotQuery(); $related = $search->getRelatedQuery($keyword,5); $post = []; foreach ($docs as $key=>$doc){ $post[$key]->id = $doc->id; // 高亮處理標題 $post[$key]->title = $search->highlight($doc->title); // 高亮處理標題 $post[$key]->body = $search->highlight($doc->body); // 高亮處理標題 } $paginator = new LengthAwarePaginator($post,$count,$listRows,$page, [ ‘path‘ => Paginator::resolveCurrentPath(),‘pageName‘ => ‘page‘, ]); // TODO 新增引數到分頁連結 $paginator->appends([‘wd‘=>$keyword]); $data = array( ‘post‘=>$post,‘paginator‘=>$paginator,‘count‘ => $count,‘total‘ => $total,‘search_cost‘ => $search_cost,‘corrected‘ => $corrected,‘hot‘ => $hot,‘related‘ => $related, ); return view(‘post.index‘,$data); }
}

# 功能測試效果:

技術分享圖片