bkstar123/mysql-search

为laravel/mysql应用程序启用全文搜索和通配符搜索

1.0.5 2019-09-28 06:01 UTC

This package is auto-updated.

Last update: 2024-09-28 17:54:48 UTC


README

一个轻量级的包,用于为laravel/mysql应用程序启用全文搜索和部分搜索

1. 要求

  • PHP 7.1.3+
  • Laravel 5.5+
  • MySQL 5.6+

2. 安装

composer require bkstar123/mysql-search  

3. 使用方法

例如,您的数据库有一个articles表,包含id, title, content, status, user_id, created_at, updated_at列。

您希望允许用户在title, content列中对一个词/关键词进行搜索。

为了做到这一点,只需按照以下步骤操作
a) 在Article模型中,导入并使用特质Bkstar123\MySqlSearch\Traits\MySqlSearch
b) 在Article模型中,定义一个名为$mysqlSearchable的公共静态属性,例如

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Bkstar123\MySqlSearch\Traits\MySqlSearch;

class Article extends Model
{
    use MySqlSearch;

    public static $mysqlSearchable = ['title', 'content'];

    //...
}

c) 如果您想使用MySQL全文搜索功能(由MyIASM、InnoDB - 自MySQL 5.6+存储引擎支持),则需要完成以下额外工作

-> 为articles表创建FullTEXT索引
php artisan mysql-search:init "App\Article"

注意:要从articles表中移除FULLTEXT索引
php artisan mysql-search:reset "App\Article"

d) 搜索查询

全文搜索(默认):

<?php
App\Article::search($searchTerms, true, 'natural')
App\Article::search($searchTerms) // full-text search in natural language mode
App\Article::search($searchTerms, true, 'boolean') // Full-text search in boolean mode
App\Article::search($searchTerms, true, 'query') // Full-text search with query expansion

// Better to use with try...catch as follows
try {
    $articles = App\Article::search($searchText)
                    ->paginate(10)
                    ->appends([
                        'search' => $searchText
                ]);
} catch (Exception $e) {
    $articles = [];
}

默认情况下,默认全文搜索模式是自然语言。您可以通过在.env文件中使用FULLTEXT_SEARCH_MODE变量来更改此默认值,可能的值:natural, boolean, query

有关自然语言和布尔模式的详细信息,请参阅https://www.w3resource.com/mysql/mysql-full-text-search-functions.php。由于查询扩展模式会在搜索结果中产生很多噪音,因此不推荐使用。

全文索引的最大问题是它们与常规索引不太友好。如果您在对其他常规索引进行全文搜索查询时结合使用,您将会得到一个非常低效的查询(性能不佳)。请参阅https://medium.com/@kirkbackus/using-full-text-index-for-innodb-when-a-search-engine-is-not-feasible-d666830b4000

部分搜索(使用运算符LIKE %$searchTerms%)

<?php
App\Article::search($searchTerms, false) // partial search with LIKE operator against a wildcard term e.g: %searchTerm%