Mysql ft min word len

I just had and solved a similar problem of my own. The problem in my case is that the my.ini file I needed to edit in order to change the ft_min_word_len variable was in a directory that’s hidden/protected by default in Windows 7. That’s: «c:/programdata/mysql/mysql server 5.7».

Windows file explorer and searches don’t show this location until you go into folder options and specify that you want to see hidden files/folders (and possibly protected operating system files—I did both).

Initially I created a my.cnf file under Program Files/MySQL Server 5.7. But when I restarted the server the ft_min_word_len variable hadn’t changed. Then I typed in some random text that I knew should trigger an error, but the server started up like normal. It seems that MySQL wasn’t reading the file, even though it was in one of the locations specified in the help text from the MySQL client shell.

My thinking is that the MySQL server starts searching for .cnf/.ini files in the order specified in the help text, but once it finds a valid file, stops searching. Just a theory, but I can say for sure that it wasn’t recognizing configuration files in the other places it was supposed to be looking.

I figured it was like CSS, where each new CSS file overrides settings in the previous. Evidently not.

Anyway, I hope this will be of help to anyone else who runs into the same problem.

Средство полнотекстового поиска MySQL пока имеет только несколько настраиваемых пользователем параметров, несмотря на то, что задача добавления новых обладает высоким приоритетом в планах того, что должно быть нами сделано. Вы можете получить больший контроль над поведением полнотекстового поиска, если у вас есть исходный дистрибутив MySQL, потому что некоторые изменения требуют модификации исходного кода.

Отметим, что полнотекстовый поиск был тщательно настроен для обеспечения наилучшей эффективности. Модификация поведения по умолчанию может в большинстве случаев только ухудшить результат. Не изменяйте исходных текстов MySQL, если только вы точно не знаете, что делаете!
Большинство переменных, имеющих отношение к полнотекстовому поиску, и описанных ниже, могут быть установлены во время запуска сервера. Для того чтобы изменить эти переменные, требуется перезапуск сервера; динамическая модификация во время работы сервера не предусмотрена.
Некоторые изменения переменных требуют перестройки FULLTEXT-индексов ваших таблиц. Инструкции приведены в конце настоящего раздела.

   * Минимальная и максимальная длина слов, подлежащих индексации, определяется системными переменными ft_min_word_len и ft_max_word_len (доступными, начиная с версии MySQL 4.0.0). Минимальное значение по умолчанию — четыре символа. Максимум по умолчанию зависит от вашей версии MySQL. Если вы изменяете любое из этих значений, то должны перестроить свои FULLTEXT-индексы. Например, если выхотите, чтобы можно было искать трёх символьные слова, то можете изменить значение переменной ft_min_word_len, поместив следующие строки в файл опций:

[mysqld] ft_min_word_len=3

Затем перезапустите сервер и перестройте существующие FULLTEXT-индексы. Обратите особое внимание на примечания относительно myisamchk в инструкциях, следующих за настоящим списком.

  1. Чтобы переопределить список стоп-слов по умолчанию, установите системную переменную ft_stopword_file (применяется, начиная с MySQL 4.0.10). Значением переменной должен быть полный путь к файлу, содержащему список стоп слов, либо пустая строка, если надо отключить фильтрацию по стоп-словам. После изменения этой переменной перестройте существующие FULLTEXT-индексы.
  2. 50%-ный порог для естественного языкового поиска определяется выбором определённой схемы «весовых соотношений». Чтобы отключить её, найдите в файле myisam/ftdefs.h следующую строку:

#define GWS_IN_USE GWS_PROB
Измените ее следующим образом:
#define GWS_IN_USE GWS_FREQ

Затем перекомпилируйте MySQL. В этом случае перестраивать индексы не потребуется.

На заметку!
Сделав это, вы значительно снизите способность MySQL присваивать строкам адекватные релевантные значения функцией MATCH (). Если вам действительно нужно выполнять поиск по таким часто употребляемым словам, будет лучше вместо этого применить поиск с IN BOOLEAN MODE, который не обращает внимания на 50%-ный порог.

* Чтобы изменить операции, применяемые для булевского полнотекстового поиска,установите системную переменную ft_boolean_syntax (доступна, начиная с MySQL 4.0.1). Эта переменная также может быть изменена на работающем сервере, но вы должны иметь привилегию SUPER для того, чтобы сделать это. Перестраивать индексы не нужно.

Если вы модифицируете полнотекстовые переменные, которые затрагивают индексацию (ft_min_word_len, ft_max_word_len или ft_stopword_file), то после внесения изменений должны перестроить все свои FULLTEXT-индексы и перезапустить сервер. Чтобы перестроить индексы в этом случае, достаточно выполнить операцию быстрого восстановления таблицы:

mysql> REPAIR TABLE имя_таблицы QUICK;

Специально в связи с использованием средства IN BOOLEAN MODE, если вы обновляете сервер MySQL 3.23 до версии 4.0 или выше, также необходимо заменить заголовок индекса. Чтобы сделать это, выполните следующее:

mysql> REPAIR TABLE имя_таблицы USE_FRM;

Это необходимо потому, что булевский полнотекстовый поиск требует наличия флага в заголовке индекса, которого не было в MySQL 3.23, и который не добавляется, если вы осуществляете только восстановление QUICK. При попытке выполнить булевский полнотекстовый поиск без такой перестройки индексов, он вернет некорректный результат.
Отметим, что если вы используете myisamchk для операции, которая модифицирует индексы (такой как анализ или восстановление), FULLTEXT-индексы перестраиваются с использованием значений по умолчанию для параметров минимальной и максимальной длины слова, а также файла стоп-слов на сервере, если вы не укажете другого. Это может приводить к аварийному завершению запросов.

Проблема возникает из-за того, что эти параметры известны только серверу. Они не сохраняются в индексных файлах MyISAM. Чтобы избежать проблем, когда вы модифицируете длину минимального и максимального слова или файл стоп-слов на сервере, нужно указывать те же значения ft_min_word_len, ft_max_word_len и ft_stopword_file программе myisamchk, что используются в mysqld. Например, если минимальная длина слова установлена в 3 символа, вы можете восстановить таблицу с помощью myisamchk следующим образом:

shell> myisamchk -recover -ft_min_word_len=3 имя_таблицы

Чтобы гарантировать, что myisamchk и сервер используют те же значения параметров полнотекстового поиска, можно поместить каждый из них в оба раздела [mysqld] и [mysqlchk] файла опций.

[mysqld]
ft_min_word_len=3
[myisamchk]
ft_min_word_len=3

Альтернативой применению myisamchk являются операторы REPAIR TABLE, ANALYZE TABLE, OPTIMIZE TABLE или ALTER TABLE. Эти операторы выполняются сервером, которо­му известны правильные значения параметров полнотекстового поиска.

Home / Change the full text index minimum word length with MySQL

The MySQL full text index by default only indexes words which are 4 characters or longer, which means on a blog like mine if you search for «PHP» nothing will be returned. This post shows how to change minimum word length in MySQL so words or 3 characters (or even 2 if you want) can be indexed as well.

Edit the MySQL configuration file my.cnf which is usually located on a *nix box at /etc/my.cnf or /etc/mysql/my.cnf and add the following line under the [mysqld] section to change the default to 3:

ft_min_word_len = 3

If the ft_min_word_len value is already in the file then change the number to the minimum length required.

After making this change the MySQL server must be restarted for it to take effect. It is not possible to change the size with a set query (e.g. «SET ft_min_word_len = 3» which will result in the error «#1193 – Unknown system variable ‘ft_min_word_len’»).

Now that the minimum word length has changed, and new or updated records will use the new minimum word length, but existing records will not be affected. To rebuild the full text index on a column for an example table called my_table, run this query:

REPAIR TABLE my_table QUICK;

I have seen comments by some people who have suggested that on large tables it may be faster to drop the index and create it again depending on the size, and also that the repairing it may mean the query cache is not flushed whereas dropping and re-indexing will solve this.

Note however that if you drop the index and then re-create it you may get SQL query errors on your website. As always it is advisable to test this sort of thing out on a development server configured in the same way as a production server before doing it to the production server to ensure you don’t have any issues.

Normally it is not recommended to change variables that control MySQL fulltext index behaviour (such as ft_min_word_len or ft_max_word_len) but if you really need to…

MySQL config file would usually be found on Windows under C:Windowsmy.ini and on Linux under /etc/my.cnf Edit the file and add

[mysqld]
ft_min_word_len = 3

The default value is 4 and the above will change it to 3. You can change ft_max_word_len in the same manner:

[mysqld]
ft_max_word_len = 150

After changing the variable(s) in config file restart MySQL server and you’re done. You can then check the values in phpMyAdmin under «Show MySQL system variables» to make sure your changes have taken place.

And finally rebuilt fulltext index by running following sql:
(replace prefix for your tables if required  kbp_kb_entry -> your_prefix_kb_entry)

REPAIR TABLE kbp_kb_entry, kbp_kb_comment, kbp_kb_rating_feedback, kbp_feedback, kbp_file_entry,  kbp_news;

Check variable:

SHOW VARIABLES LIKE ‘ft_min_word_len’;

When doing MySQL full-text search IN BOOLEAN MODE and the length of your search keyword is less than 4 characters, there won’t be match although there is matching record in database. It means your search hits ft_min_word_len «minimum word length of 4» rule IN BOOLEAN MODE search modifiers. To get around of this limitation, do the following.

Dummy table

# Create table.
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `index2` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

# Populate table.
INSERT INTO `person` (`name`) VALUES ('abc');

Check the current status

By default, variable ft_min_word_len is set to 4 in MySQL and the query to search «abc» won’t return anything.

inanzzz@ubuntu:~$ mysql -u root -p
Enter password:

# Check 'ft_min_word_len' variable.
mysql> SHOW VARIABLES LIKE 'ft_min_word_len';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| ft_min_word_len | 4 |
+-----------------+-------+
1 row in set (0.00 sec)

# Run example query
mysql> SELECT *
-> FROM person
-> WHERE
-> MATCH(`name`) AGAINST ('abc' IN BOOLEAN MODE);
Empty set (0.00 sec)

Update ft_min_word_len variable in MySQL config

Trying to use SET GLOBAL ft_min_word_len = 3; command would produce error «#1238 — Variable ‘ft_min_word_len’ is a read only variable» so you should manually update MySQL config file.

inanzzz@ubuntu:~$ sudo gedit /etc/mysql/my.cnf

# Then add key-value pair in [mysqld] block as:
[mysqld]
ft_min_word_len = 3

Restart MySQL

inanzzz@ubuntu:~$ sudo service mysql restart
mysql stop/waiting
mysql start/running, process 3797

Rebuild indexes

You cannot use REPAIR command on InnoDB storage engine otherwise you get «The storage engine for the table doesn’t support repair» error. You can use ALTER TABLE

ENGINE=MyISAM;

mysql> REPAIR TABLE person QUICK;
+----------------+--------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+----------------+--------+----------+----------+
| inanzzz.person | repair | status | OK |
+----------------+--------+----------+----------+
1 row in set (0.00 sec)

Query again

mysql> SELECT *
-> FROM person
-> WHERE
-> MATCH(`name`) AGAINST ('abc' IN BOOLEAN MODE);
+----+------+
| id | name |
+----+------+
| 1 | abc |
+----+------+
1 row in set (0.00 sec)

to convert InnoDB to MyISAM.

Понравилась статья? Поделить с друзьями:
  • Mysql for excel что это такое
  • Mysql for excel установка
  • Mysql for excel скачать
  • Mysql for excel кодировка
  • Mysql for excel workbench