Home > Backend Development > PHP Tutorial > Sphinx PHP implements search history and recommendation functions for full-text search

Sphinx PHP implements search history and recommendation functions for full-text search

WBOY
Release: 2023-10-03 10:24:02
Original
1121 people have browsed it

Sphinx PHP 实现全文搜索的搜索历史记录与推荐功能

Sphinx PHP implements the search history and recommendation functions of full-text search

Introduction:
With the rapid development of the Internet, full-text search has become an important part of many websites and Essential features in the app. Sphinx is a powerful open source full-text search engine that can quickly search and retrieve large amounts of text data. This article will introduce how to use Sphinx PHP to implement the search history and recommendation functions of full-text search to improve the user's search experience.

  1. Installing and Configuring Sphinx
    First, we need to install and configure Sphinx on the server. This can be accomplished through the following steps:

1.1 Download Sphinx

Visit the Sphinx official website (http://sphinxsearch.com/) to download the latest version of Sphinx. Unzip the file.

1.2 Install Sphinx

Enter the Sphinx decompression directory and execute the following command to install Sphinx:

./configure
make
make install
Copy after login

1.3 Configure Sphinx

In the Sphinx installation directory , create a configuration file sphinx.conf, the example is as follows:

source src1
{
    type = mysql

    sql_host = your_mysql_host
    sql_user = your_mysql_user
    sql_pass = your_mysql_password
    sql_db = your_mysql_database
    sql_port = 3306

    sql_query = 
        SELECT id, title, content 
        FROM articles
}

index idx1
{
    source = src1
    path = /path/to/index
    docinfo = extern

    morphology = stem_ru

    min_stemming_len = 4
}

searchd
{
    listen = 9312
    log = /path/to/log/searchd.log
}
Copy after login

Replace your_mysql_host, your_mysql_user, your_mysql_password, your_mysql_database in the above example with the actual database information.

  1. Writing PHP code
    Next, we will write PHP code to use Sphinx to implement the search history and recommendation functions of full-text search. The sample code is as follows:
<?php
require_once("sphinxapi.php");

// 定义Sphinx服务器的IP地址和端口号
$host = "127.0.0.1";
$port = 9312;

// 创建Sphinx客户端对象
$sphinx = new SphinxClient();

// 设置Sphinx服务器的连接信息
$sphinx->SetServer($host, $port);

// 设置搜索模式为全文搜索模式
$sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);

// 定义关键词
$keyword = "php实现搜索";

// 执行搜索
$result = $sphinx->Query($keyword, "idx1");

if ($result["total"] > 0) {
    // 获取搜索结果
    $matches = $result["matches"];

    // 输出搜索结果
    foreach ($matches as $match) {
        echo "文章标题:" . $match["attrs"]["title"] . "<br>";
        echo "文章内容:" . $match["attrs"]["content"] . "<br>";
        echo "<br>";
    }
} else {
    echo "没有找到相关的文章";
}
?>
Copy after login

In the above code, we first introduced the sphinxapi.php file, which contains the API functions required to communicate with the Sphinx server. Next, we created a SphinxClient object and set the connection information and search mode of the Sphinx server.

Before performing the search, we define a keyword $keyword and pass it as a parameter to the Sphinx Query method. The Query method returns an array of search results $result, which contains the total number of search results $total and information about each matching result $matches. We can output the title and content of the search results by looping through the $matches array.

  1. Search history function
    When implementing the search history function, we can save each user's search keywords into the database. This can be achieved through the following steps:

3.1 Create a search history table
Create a search history table in the database, containing the following fields:

  • id: Primary key
  • user_id: User ID
  • keyword: Search keyword
  • created_at: Creation time

3.2 Insert search history
in After performing a search, the user's search keywords and current time are inserted into the search history table. The sample code is as follows:

<?php
// ...
if ($result["total"] > 0) {
    // ...

    // 将搜索关键词插入到搜索历史记录表中
    $user_id = 1; // 假设用户ID为1
    $keyword = "php实现搜索";
    $created_at = date("Y-m-d H:i:s");

    $sql = "INSERT INTO search_history (user_id, keyword, created_at) VALUES ('$user_id', '$keyword', '$created_at')";
    // 执行SQL语句插入搜索历史记录
    // ...

    // 输出搜索结果
    // ...
}
Copy after login

In the above code, we first define the user ID $user_id, search keyword $keyword and current time $created_at. Next, we use the INSERT INTO statement to insert these values ​​into the search history table. Please modify the values ​​of $keyword and $user_id according to the actual situation.

  1. Recommendation function
    When implementing the recommendation function, we can recommend relevant articles to users based on their search history. This can be achieved through the following steps:

4.1 Obtain user search history
Query the user's search history in the database and save it in an array. The sample code is as follows:

<?php
// ...
$user_id = 1; // 假设用户ID为1

// 查询用户的搜索历史记录
$sql = "SELECT keyword FROM search_history WHERE user_id = '$user_id' ORDER BY created_at DESC LIMIT 5";
// 执行SQL语句查询搜索历史记录
// ...

// 将搜索关键词保存到数组中
$keywords = [];
while ($row = mysqli_fetch_assoc($result)) {
    $keywords[] = $row["keyword"];
}
Copy after login

In the above code, we use the SELECT statement to query the user's search history. Note adjusting the value of LIMIT to obtain the specified number of search history records. Save the query results to the array $keywords.

4.2 Recommendation based on search history
Based on the user’s search history, relevant articles can be queried from the database and recommended results can be output. The sample code is as follows:

<?php
// ...
if (count($keywords) > 0) {
    $sql = "SELECT title, content FROM articles WHERE ";
    foreach ($keywords as $keyword) {
        $sql .= "MATCH('$keyword') ";
        $sql .= "OPTION ranker=expr('sum(word_count)*user_weight') ";
        $sql .= "AGAINST('$keyword') OR ";
    }
    $sql = rtrim($sql, " OR ");
    $sql .= " LIMIT 5";
    // 执行SQL语句查询推荐结果
    // ...

    if (mysqli_num_rows($result) > 0) {
        // 输出推荐结果
        while ($row = mysqli_fetch_assoc($result)) {
            echo "文章标题:" . $row["title"] . "<br>";
            echo "文章内容:" . $row["content"] . "<br>";
            echo "<br>";
        }
    } else {
        echo "没有推荐的文章";
    }
}
Copy after login

In the above code, we first check whether the $keywords array is empty. If not, generate a query statement with OR conditions. We use the MATCH...AGAINST statement to search for related articles and use the ranker option to set the matching weight. Relevance can be improved by assigning a higher weight user_weight to each query keyword. Output the query results to the front end.

Summary:
This article introduces how to use Sphinx PHP to implement the search history and recommendation functions of full-text search. By saving the user's search keywords and query-related articles, the user's search experience can be improved and more personalized recommendation results can be provided for the user. I hope readers can successfully implement the corresponding functions based on the methods and sample codes provided in this article.

The above is the detailed content of Sphinx PHP implements search history and recommendation functions for full-text search. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template