How to use php extension Sphinx for full text search

WBOY
Release: 2023-07-29 10:10:02
Original
1139 people have browsed it

How to extend Sphinx for full-text search using PHP

Full-text search is one of the common requirements in modern web applications. In order to satisfy users' efficient query and retrieval of data, we can use Sphinx, a powerful open source search engine, to implement full-text search functionality. Sphinx is written in C and provides PHP extensions for us to use in PHP projects.

This article will introduce how to use PHP to extend Sphinx for full-text search. First, we need to make sure we have the Sphinx engine installed and configured as our data source.

Step one: Install Sphinx engine
We can download the latest version of Sphinx engine from Sphinx’s official website (http://sphinxsearch.com/downloads/release/). After the download is complete, follow the instructions in the official documentation to install it.

Step 2: Configure the data source
Before using Sphinx for full-text search, we need to configure the data source and tell Sphinx where the content to be searched is. Sphinx supports a variety of data sources, including MySQL, PostgreSQL, XML, and more.

We take the MySQL data source as an example. First, we need to create a data table in MySQL and import the content to be searched into the table. For example, we create a table called "movies" and insert the title and synopsis of the movie into it.

CREATE TABLE movies (

id INT PRIMARY KEY,
title VARCHAR(255),
description TEXT
Copy after login

);

INSERT INTO movies (id, title, description) VALUES

(1, 'Avatar', 'A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.'),
(2, 'The Avengers', 'Earth''s mightiest heroes must come together and learn to fight as a team if they are going to stop the mischievous Loki and his alien army from enslaving humanity.'),
(3, 'Inception', 'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a CEO.');
Copy after login

Save and close the MySQL database.

Step 3: Configure Sphinx configuration file
In the Sphinx installation directory, execute the following command to create a new Sphinx configuration file.

$ sudo cp sphinx.conf.dist sphinx.conf

Then, open the sphinx.conf file and configure it according to our needs. Add the following:

source movies {

type            = mysql

sql_host        = localhost
sql_user        = username
sql_pass        = password
sql_db          = database
sql_port        = 3306

sql_query_pre   = SET NAMES utf8
sql_query       = 
    SELECT id, title, description 
    FROM movies

sql_attr_uint   = id
sql_attr_uint   = gid

sql_query_info  = SELECT * FROM movies WHERE id=$id
Copy after login

}

index movies {

source          = movies
path            = /var/data/movies
docinfo         = extern
min_prefix_len  = 1
charset_type    = utf-8
Copy after login

}

searchd {

listen          = 9306:mysql41
log             = /var/log/sphinxsearch/searchd.log
query_log       = /var/log/sphinxsearch/query.log
read_timeout    = 5
max_children    = 30
pid_file        = /var/run/sphinxsearch/searchd.pid
seamless_rotate = 1
preopen_indexes = 1
unlink_old      = 1
workers         = threads
binlog_path     = /var/data/sphinxsearch/
Copy after login

}

Replace username, password, and database with the connection information of your MySQL database. Save and close the sphinx.conf configuration file.

Step 4: Start the Sphinx service
Execute the following command in the terminal to start the Sphinx service.

$ searchd

Step 5: Create PHP script
Now we can search data through PHP script. Create a file called search.php and insert the following code:

require 'sphinxapi.php';

$cl = new SphinxClient( );

//Connect Sphinx service
$cl->SetServer('localhost', 9312);
$cl->SetConnectTimeout(1);
$cl-> ;SetArrayResult(true);

//Set search mode and search keywords
$cl->SetMatchMode(SPH_MATCH_EXTENDED2);
$cl->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
$cl->SetSortMode(SPH_SORT_RELEVANCE);
$cl->SetLimits(0, 10);
$cl->SetFieldWeights(array('title' => 10, 'description' => ; 3));

$query = 'Avatar';

$result = $cl->Query($query, 'movies');

if ( $result === false) {

echo 'Query failed: ' . $cl->GetLastError();
Copy after login

} else {

if ($cl->GetLastWarning()) {
    echo 'Warning: ' . $cl->GetLastWarning();
}

echo 'Total matches: ' . $result['total_found'] . "
Copy after login

";

foreach ($result['matches'] as $match) {
    echo 'Title: ' . $match['attrs']['title'];
    echo 'Description: ' . $match['attrs']['description'];
}
Copy after login

}

?>

Replace the search keywords with what you want to search for. Save and close the search.php file.

Step 6: Perform the search
In the terminal, enter the directory where search.php is located and execute the following Command:

$ php search.php

You will see that the results contain data matching the search keyword.

Through the above steps, we can Sphinx is used in the project for full-text search. Sphinx provides many powerful search functions and options that can be configured according to our needs. I hope this article can help you understand how to use PHP to extend Sphinx for full-text search.

The above is the detailed content of How to use php extension Sphinx for full text search. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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