在 MariaDB 中的 Laravel 全文搜索中按相关性对搜索结果进行排序

问题描述 投票:0回答:1

执行全文搜索时,如何根据 Laravel 中的搜索词的相关性进行排序?

迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::dropIfExists('posts');

        Schema::create('posts',function (Blueprint $table){
            // More columns will be added in next migrations.
            $table->id();
            $table->string('name');
            $table->fulltext(['name']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

型号

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   use HasFactory;
   protected $table="posts";
}

我在控制器中执行全文搜索,如下所示:

class PostController extends Controller
{
  public function search()
  {
     $searchterm = $request->get('searchterm');
     $qb = Post::query();
     
     if(!empty($searchterm)){
         $qb=$qb->whereFullText(['name'],$searchterm);
     }

     $page = $request->get('page')??1;
     $limit = $request->get('limit')??20;

     $results = $qb->offset(($page - 1) * $limit)
            ->simplePaginate($limit);

     return new JsonResponse($results,200);
  }
}

但是,我需要弄清楚如何返回控制器中按相关性排序的结果。我希望最接近的匹配项首先出现。我怎样才能实现这个目标?

php laravel eloquent full-text-search
1个回答
0
投票

放置原始查询部分的方法,例如:

class PostController extends Controller
{
  public function search()
  {
     $searchterm = $request->get('searchterm');
     $qb = Post::query();
     
     if(!empty($searchterm)){
        $qb=$qb->whereRaw("MATCH(name) AGAINST(? IN BOOLEAN MODE)",["*".$searchterm."*"])
                ->orderByRaw("MATCH(name) AGAINST(?) DESC", ["*".$searchterm."*"]);
     }

     $page = $request->get('page')??1;
     $limit = $request->get('limit')??20;

     $results = $qb->offset(($page - 1) * $limit)
            ->simplePaginate($limit);

     return new JsonResponse($results,200);
  }
}

我使用

whereRaw
orderByRaw
来对结果进行排序和过滤。这仅适用于使用 mysql 或 mariadb 时,这只是它的缺点,特别是在实现可用于多个 rdbms 的应用程序时(例如,您的应用程序支持 mysql 和 postgres)。

© www.soinside.com 2019 - 2024. All rights reserved.