Blog / Linux/ Implementing Efficient Search in WordPress with Manticore Search on CentOS

Implementing Efficient Search in WordPress with Manticore Search on CentOS

WordPress使用Manticore search实现高效搜索-CentOS系统

Manticore Search is a fork of the Sphinx search engine, offering improvements, bug fixes, easier usage, real-time search, SNIPPET syntax, and advanced features. For details, visit the official website.

System Support

Manticore Search supports 32-bit and 64-bit versions of:

  • CentOS/RHEL 6
  • CentOS/RHEL 7
  • CentOS/RHEL 8

This guide uses a WordPress site on CentOS 6.8 64-bit as an example.

Install Required Components

Install necessary libraries. If you only index from MySQL, install the MySQL library. If you don't use the indexer tool, these packages are optional.

yum install mysql-libs postgresql-libs expat unixODBC -y

For ICU support (advanced character handling), install:

yum install libicu -y

Install Manticore Search

Method 1: YUM Installation (Recommended)

yum install https://repo.manticoresearch.com/manticore-repo.noarch.rpm -y
yum install manticore -y

After installation, you'll see confirmation and notes on starting the service (service manticore start/stop), config file location (/etc/manticoresearch/manticore.conf), and the official documentation.

Method 2: RPM Package Installation

wget https://github.com/manticoresoftware/manticoresearch/releases/download/3.4.0/manticore-3.4.0_200327.b212975-1.el7.centos.x86_64.rpm
rpm -Uhv manticore-3.4.0_200327.b212975-1.el7.centos.x86_64.rpm

Service Control Commands

Start Service

  • CentOS 7: systemctl start manticore
  • CentOS 6: service manticore start

Or with a custom config:

searchd --config /etc/manticoresearch/wpindex.conf

Stop Service

service manticore stop

Or for a custom config:

searchd --config /etc/manticoresearch/wpindex.conf --stop

Enable on Boot

chkconfig --level 345 manticore on

Configure Index for WordPress

Create a configuration file for WordPress indexing. Adjust database credentials and paths as needed.

Create directories and set permissions:

mkdir -p /var/lib/manticore/data
cd /var/lib/manticore
chmod 777 data

Create and edit the config file (ensure searchd is stopped):

cd /etc/manticoresearch
vi /etc/manticoresearch/wpindex.conf

Insert the following configuration, replacing sql_pass and sql_db with your MySQL password and database name.

source src_my_blog {
    type = mysql
    sql_host = 127.0.0.1
    sql_user = root
    sql_pass = your_mysql_root_password
    sql_db = your_wordpress_database
    sql_query_pre = SET NAMES utf8
    sql_query = 
    SELECT DISTINCT 
    wp_posts.ID as ID, 
    wp_posts.post_title as title, 
    wp_posts.post_content as body, 
    wp_posts.guid as urlid, 
    UNIX_TIMESTAMP(wp_posts.post_date) AS date_added 
    FROM 
    wp_posts 
    WHERE 
    wp_posts.post_type = 'post' AND 
    wp_posts.post_status = 'publish';
    sql_field_string = title
    sql_field_string = body
    sql_field_string = urlid
    sql_attr_timestamp = date_added
}

index idx_blog {
    type   = plain
    source = src_my_blog
    path = /var/lib/manticore/data/idx_blog
    min_word_len = 1
    charset_table = 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F
    ngram_len = 1
    ngram_chars = U+3000..U+2FA1F
    html_strip = 1
    html_index_attrs = img=alt,title; a=title;
    html_remove_elements = style, script, object, embed, span
}

indexer
{
    mem_limit = 256M
}

searchd
{
    listen          = 127.0.0.1:9312
    listen          = 127.0.0.1:9306:mysql41
    log             = /var/log/manticore/searchd.log
    query_log       = /var/log/manticore/query.log
    pid_file        = /var/run/manticore/searchd.pid
    read_timeout = 5
    client_timeout = 300
    max_children = 30
    persistent_connections_limit = 30
    seamless_rotate = 1
    preopen_indexes = 1
    unlink_old = 1
    max_packet_size = 8M
    max_filters = 256
    max_filter_values = 4096
    max_batch_queries = 32
    workers = threads
    binlog_path = /var/lib/manticore/data
}

Build the Index Manually

indexer --config /etc/manticoresearch/wpindex.conf --all --rotate
searchd --config /etc/manticoresearch/wpindex.conf

Test the search service via MySQL client:

mysql -h0 -P9306

Schedule Index Updates

To keep results fresh, schedule a cron job (e.g., daily at 4 AM).

Create a shell script (e.g., /codefiles/crontab/manticore.sh):

#!/bin/bash
searchd --config /etc/manticoresearch/wpindex.conf --stop
indexer --config /etc/manticoresearch/wpindex.conf --all --rotate
searchd --config /etc/manticoresearch/wpindex.conf
exit 0

Make it executable:

chmod +x /codefiles/crontab/manticore.sh

Add to crontab:

crontab -e

Add line (adjust path):

0 4 * * * /codefiles/crontab/manticore.sh

Integrate Search Frontend in WordPress

1. Create JavaScript File

Create manticore_search.js in your theme root:

function displaysort() {
    var q = document.getElementById("manticoresearch").value;
    if (q == "") return;
    var x = document.getElementById("sort");
    if (x.style.display === "none") x.style.display = "block";
    var sort = document.getElementById("sortoption").value;
    search(sort);
}
function search(str) {
    if (str == "") return;
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("searchresult").innerHTML = this.responseText;
        }
    }
    var q = document.getElementById("manticoresearch").value;
    var url = "//yourdomain.com/wp-content/themes/your-theme/manticore_search.php?q=" + encodeURIComponent(q) + "&sort=" + str;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

2. Create PHP Handler

Create manticore_search.php in your theme root:

<?php
$q = isset($_GET['q']) ? $_GET['q'] : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : '1';
$manticore = new mysqli("127.0.0.1", "", "", "", 9306);
if ($manticore->connect_error) die("Connection failed: " . $manticore->connect_error);
$q = $manticore->real_escape_string($q);
if ($sort == "1") {
    $sphinxQl = "SELECT *, SNIPPET(title,'" . $q . "','limit=100') as snippet FROM idx_blog WHERE MATCH('" . $q . "') OPTION max_matches=100";
} else {
    $sphinxQl = "SELECT *, SNIPPET(title,'" . $q . "','limit=100') as snippet FROM idx_blog WHERE MATCH('" . $q . "') ORDER BY date_added DESC";
}
$result = $manticore->query($sphinxQl);
echo "<p>Advanced Search Results:</p>";
echo "<ul class='search-page'>";
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $clean_url = str_ireplace('?p=', '', $row['urlid']);
        $title = highlight_word($row['title'], $q);
        echo "<li class='entry-title'><a href='" . htmlspecialchars($clean_url) . "'>" . $title . "</a></li>";
    }
} else {
    echo "<li>No results found.</li>";
}
echo "</ul>";
function highlight_word($content, $word) {
    mb_internal_encoding("UTF-8");
    $replace = '<span style="background-color: #FF0;">' . htmlspecialchars($word) . '</span>';
    $content = str_ireplace($word, $replace, $content);
    return $content;
}
?>

3. Modify Theme Search Template

Add the following to your theme's search.php or desired location:

<script type="text/javascript" src="//yourdomain.com/wp-content/themes/your-theme/manticore_search.js"></script>
<p>
    <input id="manticoresearch" name="search" type="text" placeholder="Enter keywords..." />
    <button type="button" onclick="displaysort()">Advanced Search</button>
</p>
<div id="sort" style="display:none; margin-top:10px;">
    <form>
        <select id="sortoption" onchange="search(this.value)">
            <option value="1">Sort by Relevance</option>
            <option value="2">Sort by Date</option>
        </select>
    </form>
</div>
<div id="searchresult" style="margin-top:20px;"></div>

Your WordPress site now has efficient search powered by Manticore Search. Adjust HTML and CSS to match your theme.

Post a Comment

Your email will not be published. Required fields are marked with *.