如何使用自由文本搜索条目在MySQL表中查找项目?
例如,我有一个简单的葡萄酒表,如下所示:
id | wine
================================
1 Bollinger Special Cuvée Brut
2 Bollinger R.D. Extra Brut
3 Bollinger La Grande Année
4 Bollinger La Grande Année Brut
我之前使用过LIKE模式方法来搜索“ La Grande”(WHERE wine LIKE '%La Grande%'
),它对于更精确的搜索短语也可以正常工作。
但是,如果用户提供的字符串如“ Bollinger Brut”或“ Cuvee”(不带有重音符号),则LIKE模式方法将找不到任何匹配项。我可以使用一些MySQL技巧来解决此问题,还是需要其他方法/算法来进行更多临时搜索?
如果您有这样的FULLTEXT索引:
CREATE TABLE `wine` (
`id` int DEFAULT NULL,
`wine` varchar(200) DEFAULT NULL,
FULLTEXT KEY `wine` (`wine`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
然后:
select * from wine where match(wine) against('Bollinger Brut' in boolean mode);
将选择:
+------+--------------------------------+
| id | wine |
+------+--------------------------------+
| 1 | Bollinger Special Cuvée Brut |
| 2 | Bollinger R.D. Extra Brut |
| 4 | Bollinger La Grande Année Brut |
| 3 | Bollinger La Grande Année |
+------+--------------------------------+
和:
mysql> select * from wine where match(wine) against('Cuvee' in boolean mode);
+------+------------------------------+
| id | wine |
+------+------------------------------+
| 1 | Bollinger Special Cuvée Brut |
+------+------------------------------+
注意:
select
id,
wine,
ROUND(match(wine) against('Bollinger Brut' in boolean mode) ,5) score
from wine
where match(wine) against('Bollinger Brut' in boolean mode);
将会呈现:
+------+--------------------------------+---------+
| id | wine | score |
+------+--------------------------------+---------+
| 1 | Bollinger Special Cuvée Brut | 0.01561 |
| 2 | Bollinger R.D. Extra Brut | 0.01561 |
| 4 | Bollinger La Grande Année Brut | 0.01561 |
| 3 | Bollinger La Grande Année | 0.00000 |
+------+--------------------------------+---------+
因为“布林格·拉格兰德·安妮”没有“布鲁特”的得分较低。(但不是0!)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句