search
HomeBackend DevelopmentPHP TutorialHow to use php extension Sphinx for full text search

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

);

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.');

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

}

index movies {

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

}

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/

}

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();

} else {

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

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

";

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

}

?>

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!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools