首页 > 解决方案 > 为什么我的 MySQL 全文搜索不起作用?

问题描述

我正在使用 MySQL 全文搜索并且它可以工作,但我无法获得以下结果。

前任:

SELECT * FROM countries WHERE MATCH (name)
     AGAINST ("Chinese*" IN BOOLEAN MODE);

它应该给我国家记录“中国”,但它不起作用,有什么建议可以让这个功能更好/工作吗?

我的完整代码:

 protected function fullTextWildcards($term)
    {

        // removing symbols used by MySQL
        $reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
        $term = str_replace($reservedSymbols, '', $term);

        $words = explode(' ', $term);

        foreach($words as $key => $word) {
            /*
             * applying + operator (required word) only big words
             * because smaller ones are not indexed by MySQL
             */

            if(strlen($word) >= 3) {

                $words[$key] = '' . $word . '*';
            }
        }

        $searchTerm = implode( ' ', $words);

        return $searchTerm;
    }

    /**
     * Scope a query that matches a full text search of term.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $term
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $term)
    {
        $columns = implode(',',$this->searchable);

        $query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)" , $this->fullTextWildcards($term));
        return $query;
    }

标签: phpmysqllaravelfull-text-indexing

解决方案


我的解决方案是把单词变小:

if(strlen($word) >= 7){
                    $split_string = str_split($word, 4);

                    $join = implode( '*', $split_string);

                    $words[$key] = '' . $join . '*';
                }else{
                    $words[$key] = '' . $word . '*';
                }

推荐阅读