search
HomeBackend DevelopmentPHP TutorialSimple example of php sphinx

Let me introduce you to a simple example of php sphinx. Friends in need can refer to it.

The code is as follows:

<?php
//sphinx简单例子
//参数筛选
//筛选cat_id=2
$cl->SetFilter("cat_id",array(2));
//仅在id为1、3、7的子论坛中搜索
$cl->SetFilter("forum_id",array(1,3,7));
 
//范围筛选
//筛选发布时间为今天,参数为int时间戳
$cl->SetFilterRange("starttime",123,124);
//筛选价格
$cl->SetFilterRange("price",10.0,99.9);
 
// 分组
//按照item_id分组,并且按照order desc排序
$cl->SetGroupBy("item_id",SPH_GROUP_ATTR,"order desc");
 
//排序模式
//按照price desc排序
$cl->SetSortMode(SPH_SORT_ATTR_DESC,"price");
 注意:会被SetGroupBy中的排序覆盖 

// 匹配查询词中的任意一个
$cl->SetMatchMode ( SPH_MATCH_ANY );
SPH_MATCH_ALL, 匹配所有查询词(默认模式);
SPH_MATCH_ANY, 匹配查询词中的任意一个;
SPH_MATCH_PHRASE, 将整个查询看作一个词组,要求按顺序完整匹配;
SPH_MATCH_BOOLEAN, 将查询看作一个布尔表达式 (参见 第 5.2 节 “布尔查询语法”);
SPH_MATCH_EXTENDED, 将查询看作一个CoreSeek/Sphinx内部查询语言的表达式 (参见 第 5.3 节 “扩展查询语法”). 从版本Coreseek 3/Sphinx 0.9.9开始, 这个选项被选项SPH_MATCH_EXTENDED2代替,它提供了更多功能和更佳的性能。保留这个选项是为了与遗留的旧代码兼容——这样即使 Sphinx及其组件包括API升级的时候,旧的应用程序代码还能够继续工作。
SPH_MATCH_EXTENDED2, 使用第二版的“扩展匹配模式”对查询进行匹配.
SPH_MATCH_FULLSCAN, 强制使用下文所述的“完整扫描”模式来对查询进行匹配。注意,在此模式下,所有的查询词都被忽略,尽管过滤器、过滤器范围以及分组仍然起作用,但任何文本匹配都不会发生.

//从0开始查询,查询30条,返回结果最多为1000
$cl->setLimits(0,30,1000);
 
// 从名称为index的sphinx索引查询“电影票”
 $cl->Query("电影票","index");
 
// 从名称为index的sphinx索引查询“电影票”
$sp->SetGroupBy('item_id',SPH_GROUP_ATTR,'s_order desc');
$sp->SetFilter('city_id','1');
$sp->SetFilter('cat_id',array(1));
$sp->SetLimit(0,10,1000);
$sp->AddQuery('电影票','index');
$sp->ResetFilters();//重置筛选条件
$sp->ResetGroupBy();//重置分组
 
$sp->SetGroupBy('item_id', SPH_GROUPBY_ATTR, 's_order desc');
$sp->setFilter('city_id', '2');
$sp->setFilter('cat_id', array(2));
$sp->setLimits(0, 20, 1000);
$sp->AddQuery('温泉', 'index');
$sp->ResetFilters();// 重置筛选条件
$sp->ResetGroupBy();//重置分组
$results = $sp->RunQuries();
//by http://bbs.it-home.org
?>

For the official introduction of php sphinx, please refer to the document: http://bbs.it-home.org/shouce/php5/book.sphinx.html.

Batch queries (or multi-queries) enable searchd to perform possible internal optimizations and reduce overhead in terms of network connections and process creation in any case. Relative to individual queries, batch queries do not introduce any additional overhead. So when your Web page runs several different queries, be sure to consider using batch queries.

For example, running the same full-text query multiple times but using different sorting or grouping settings will cause searchd to run the expensive full-text search and relevance calculation only once, and then generate multiple grouped results based on this.

Sometimes it is not only necessary to simply display the search results, but also to display some category-related counting information, such as the number of products grouped by manufacturer. In this case, batch query will save a lot of overhead. Without batch queries, you would have to run these essentially identical queries multiple times and retrieve the same matches, resulting in different result sets. If you use batch queries, you simply combine these queries into a batch query, and Sphinx will optimize these redundant full-text searches internally.

AddQuery() internally stores all current setting status and queries, and you can also change settings in subsequent AddQuery() calls. Queries added earlier will not be affected, there is really no way to change them.

Using the above code, the first query will query "hello world" on the "documents" index and sort the results by relevance. The second query will query "ipod" on the "products" index and sort the results by price. , the third query searches for "harry potter" on the "books" index, and the results are still sorted by price. Note that the second SetSortMode() call does not affect the first query (because it has already been added), but the next two queries will.

In addition, any filtering set before AddQuery() will continue to be used by subsequent queries. Therefore, if you use SetFilter() before the first query, the second query executed via AddQuery() (and subsequent batch queries) will have the same filtering applied, unless you first call ResetFilters() to clear the filtering rules. At the same time, you can add new filtering rules at any time.

AddQuery() does not modify the current state. That is, all existing sorting, filtering, and grouping settings will not be changed by this call, so subsequent queries can easily reuse existing settings.

AddQuery() returns an index in the array returned by the RunQueries() result. It is an incrementing integer starting from 0, i.e. the first call returns 0, the second returns 1, and so on. This convenient feature saves you from having to record the subscripts manually when you need them.



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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment