首页 > 解决方案 > 反向搜索全文/类似脏搜索词

问题描述

我有一个关于针对数据库搜索字符串的小问题。

想象一下这种情况。我有一张包含所有汽车品牌和型号的表格,类似于以下内容:

+---------------------------+-------------------+
|           name            | alternative_names |
+---------------------------+-------------------+
| Peugeot 207               |                   |
| Peugeot 208               |                   |
| Peugeot 308               |                   |
| Peugeot 308 Station Wagon | estate sw         |
| Peugeot 307               |                   |
+---------------------------+-------------------+

我需要从大多数时候都是脏的字符串开始识别保存在数据库中的汽车。

“标致 308”应该返回标致 308

“标致308旅行车”应该返回标致308旅行车

“自动标致308”应该返回标致308

“sw peugeot 308”应该返回Peugeot 308 Station Wagon

知道我应该如何处理和解决这个问题吗?

标签: phpmysqlfull-text-search

解决方案


很难预见所有可能的脏词,所以最好在 PHP 中创建帮助器,什么会用大写首字母生成单词并替换单词sw喜欢Station Wagon

function modelNormalizer($model)
{

    $possible_replace = [
        'sw' => 'Station Wagon',
    ];

    $byWord = explode(' ', $model);

    foreach ($byWord as $i => $word) {
        foreach ($possible_replace as $from => $to) {
            $byWord[$i] = ucfirst(strtolower(str_replace($from, $to, $word)));
        }
    }

    return implode(' ', $byWord);
}

您还可以对 DB 中的数据进行规范化,例如将单词从前移动peugeot到末尾。

SELECT
   CONCAT(SUBSTR(t.name, LOCATE('peugeot 308', t.name)), ' ', SUBSTR(t.name, 1, LOCATE('peugeot 308', t.name)-1)) AS model
FROM yourtable AS t
WHERE t.name like "%peugeot 308%" #WARNING YOUR INDEX WILL NOT WORK WITH % PREFIX

推荐阅读