博客 / Linux/ WordPress使用Manticore search实现高效搜索-CentOS系统

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

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

Manticore Search 是 Sphinx 搜索引擎的一个分支版本,它在原版基础上进行了改进,修复了部分错误,使用更简单,支持实时搜索和 SNIPPET 语法,并提供了更多高级功能。更多详细信息请访问其官方网站:manticoresearch.com

系统支持

Manticore Search 支持以下 CentOS/RHEL 系统的 32 位和 64 位版本:

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

本文将以一个运行在 CentOS 6.8 64 位系统上的 WordPress 站点为例,记录 Manticore Search 的安装与配置过程。

一、安装必要的环境组件

首先,安装一些必要的库文件。根据你的数据源,通常只需要安装对应的客户端库。例如,如果只从 MySQL 数据库创建索引,安装 MySQL 库即可。如果完全不使用 indexer 工具,则这些包都不是必需的。

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

如果需要 ICU 开发包支持(例如用于更复杂的字符处理),可以额外安装,但本教程不涉及:

yum install libicu -y

二、安装 Manticore Search

有两种安装方式,推荐使用 yum 安装。

方法一:通过 yum 安装(推荐)

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

安装完成后,终端会显示类似以下信息,表明安装成功:

Running Transaction
Installing : manticore-3.4.0_200327.b212975-1.el6.x86_64 1/1
...
Installed:
manticore.x86_64 0:3.4.0_200327.b212975-1.el6

同时会提示:

方法二:通过 RPM 包安装

你也可以手动下载并安装特定版本的 RPM 包。

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

三、Manticore Search 服务控制命令

启动服务

使用默认配置启动服务:

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

或者,使用指定的配置文件(例如 wpindex.conf)启动:

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

启动后,请注意服务监听的端口(通常是 9312 和 9306),并测试服务是否正常运行。

停止服务

停止默认配置的服务:

service manticore stop

停止指定配置的服务:

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

设置开机自启

chkconfig --level 345 manticore on

四、为 WordPress 配置索引

此步骤需要为 WordPress 创建索引配置文件。以下是一个基础示例,你需要根据实际情况修改数据库连接信息和路径。

首先,创建必要的目录并设置权限:

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

然后,创建并编辑配置文件。确保 searchd 服务已停止。

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

将以下配置内容写入文件。请务必替换 sql_passsql_db 为你的 MySQL 数据库密码和数据库名。

#
# INDEX GROUP:
# MY BLOG
#
# SOURCES:
# src_my_blog
#
# INDEXES:
# idx_blog
#
#
source src_my_blog {
    type = mysql
    sql_host = 127.0.0.1
    sql_user = root
    sql_pass = 你的MySQL_root密码
    sql_db = 你的WordPress数据库名
    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 settings
#############################################################################
indexer
{
    mem_limit = 256M
}

#############################################################################
## searchd settings
#############################################################################
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
}
# --eof--

手动建立索引

配置文件保存后,使用以下命令创建索引:

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

然后,使用指定的配置文件启动搜索服务:

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

可以通过 MySQL 客户端连接到 Manticore 的 MySQL 接口(端口 9306)来测试搜索是否正常:

mysql -h0 -P9306

五、设置定时更新索引

为了保持搜索结果的时效性,可以设置定时任务(例如每天凌晨 4 点)自动更新索引。

首先,创建一个 Shell 脚本(例如 /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

给脚本添加执行权限:

chmod +x /codefiles/crontab/manticore.sh

然后,编辑当前用户的 crontab:

crontab -e

在打开的编辑器中添加一行(注意替换为你自己的脚本路径):

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

六、在 WordPress 中集成搜索前端

最后一步是在 WordPress 主题中集成一个使用 AJAX 的前端搜索界面。

1. 创建 JavaScript 文件

在主题根目录下创建 manticore_search.js,内容如下:

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;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = 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 = "//你的网站域名/wp-content/themes/你的主题文件夹/manticore_search.php?q=" + encodeURIComponent(q) + "&sort=" + str;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

2. 创建 PHP 处理文件

在主题根目录下创建 manticore_search.php,内容如下:

<?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("连接失败: " . $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>高级搜索结果:</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>未找到相关结果。</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. 修改主题搜索模板

最后,在你主题的 search.php 文件(或任何你想显示搜索框的地方)合适位置加入以下 HTML 和脚本引用:

<!-- Manticore Search 前端 -->
<script type="text/javascript" src="//你的网站域名/wp-content/themes/你的主题文件夹/manticore_search.js"></script>
<p>
    <input id="manticoresearch" name="search" type="text" placeholder="输入关键词..." />
    <button type="button" onclick="displaysort()">高级搜索</button>
</p>
<div id="sort" style="display:none; margin-top:10px;">
    <form>
        <select id="sortoption" onchange="search(this.value)">
            <option value="1">按相关性排序</option>
            <option value="2">按发布时间排序</option>
        </select>
    </form>
</div>
<div id="searchresult" style="margin-top:20px;"></div>
<!-- Manticore Search 前端结束 -->

完成以上步骤后,你的 WordPress 站点就集成了基于 Manticore Search 的高效搜索功能。请根据你的主题样式调整前端代码的 HTML 结构和 CSS。

  1. avatar
    一诺千金

    来学习学习

发表评论

您的邮箱不会公开。必填项已用 * 标注。