Sobes.tech
Middle

What is a full-text index?

sobes.tech AI

Answer from AI

A full-text index is a special type of index in a database that allows efficient searching of text within columns containing large volumes of text data (e.g., articles, descriptions).

The difference from regular indexes (such as B-trees) is that a full-text index works not with the full values of columns but with individual words or phrases. It analyzes the text, removes stop words (prepositions, articles), and creates an inverted index, where each word is associated with a list of documents in which it appears.

Advantages:

  • High performance when searching for words and phrases in large text fields.
  • Support for various ranking algorithms (e.g., by relevance).
  • Ability to search by word forms (stemming).

Disadvantages:

  • Requires more disk space compared to regular indexes.
  • Indexing takes more time.
  • Restrictions on supported encodings and languages depending on the DBMS.

Example of creating a full-text index in MySQL:

-- Creating a table with a text field
CREATE TABLE articles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    content TEXT
);

-- Adding a full-text index to the content field
CREATE FULLTEXT INDEX idx_content ON articles (content);

Example of using full-text search:

-- Searching for articles containing the word "PHP"
SELECT *
FROM articles
WHERE MATCH (content) AGAINST ('PHP');

-- Searching for articles containing the phrase "fulltext index"
SELECT *
FROM articles
WHERE MATCH (content) AGAINST ('"fulltext index"' IN BOOLEAN MODE);

Full-text indexes are used in various DBMSs such as MySQL (MyISAM and InnoDB, starting from 5.6), PostgreSQL, SQL Server, and others. In more complex scenarios, specialized search engines like Elasticsearch or Apache Solr can be integrated with the database.