PHP Tutorial for sphinx full-text search. This is an article that has not been written externally six months ago. I will share it with you now. There may be some incorrect or not rigorous points, some languages may be frivolous, please forgive me. I used the previous article, which was not written externally six months ago. now I will share it with you. There may be some incorrect or not rigorous points, some languages may be frivolous, please forgive me.
Take the previous email data table as an example:
Data structure:
Create table email (emailid mediumint (8) unsigned not null auto_increment COMMENT 'email ID', fromid int (10) unsigned not null default '0' comment' sender ID ', toid int (10) unsigned not null default '0' COMMENT 'recipient ID', content text unsigned not null comment 'email content', subject varchar (100) unsigned not null comment 'mail title', sendtime int (10) not null comment 'sending time', attachment varchar (100) not null comment 'attachment ID, separated by commas ', primary key (emailid),) ENGINE = MyISAM ';
To open the console, you must open the console PHP to connect to the sphinx (make sure you have created an index source ):
D: \ coreseek \ bin \ searchd-c d: \ coreseek \ bin \ sphinx. conf
The PHP interface file sphinxapi. php is provided in the coreseek/api Directory. This file contains a class of SphinxClient.
Introduce this file in PHP, new
$ Sphclient = new SphinxClient (); // the host name and port of sphinx $ sphinx-> SetServer ('loclhost', 9312 ); // Set the returned result set to the php array format $ sphresults-> SetArrayResult (true); // the offset of the matching result. the meaning of the parameters is as follows: start position, number of returned results, maximum number of matched items $ sphquota-> SetLimits (0, 20,100 0); // maximum search time $ sphquota-> SetMaxQueryTime (10); // execute a simple search, this search will query the information of all fields. to query the specified field, continue to see the following $ index = 'e-mail '// The index source is the index class in the configuration file, if multiple index sources are available, separate the numbers: 'Email, diary 'or use' * 'to represent all index sources $ result = $ sphenders-> query ('search keyword', $ index); echo'
';print_r($result);echo '
';
$ Result is an array where
Total is the total number of matched data
Matches is the matching data, including the id and attrs information.
Words is the word segmentation of search keywords.
You may wonder why there is no such information in the mail. In fact, sphenders will not return data arrays like mysql, because sphenders have not recorded complete data, only data after word segmentation is recorded.
For more information, see the matches array. the ID in matches refers to the first field in the SQL _query SELECT statement in the configuration file.
SQL _query = SELECT emailid, fromid, toid, subject, content, sendtime, attachement FROM email
Therefore, the ID in matches refers to the emailid.
Weight refers to the matching weight. Generally, the higher the weight, the highest priority will be returned. for details about the matching weight, see the official documentation.
Attrs is the information in SQL _attr _ in the configuration file. the usage of these attributes will be mentioned later.
After talking about this, even if the search results are not the email data we want, the fact sphinx does not record the real data, therefore, to obtain the real email data, you must search for the mysql email table based on the ID in matches. However, in general, this process is much faster than LIKE in mysql, the premise is that the data volume is more than 100,000; otherwise, the use of sphinx will be slower.
Next we will introduce the usage of sphenders similar to mysql conditions.
// The range of emailid is $ sphange-> SetIdRange ($ min, $ max); // attribute Filtering. to filter attributes, you must set SQL _attr _ in the configuration file _, previously we defined these SQL _attr_uint = fromid SQL _attr_uint = toid SQL _attr_timestamp = sendtime // If you want to modify these attributes again, after the configuration is complete, remember to re-create the index to take effect // specify some values $ sphsf-> SetFilter ('fromid ', array (1, 2 )); // The fromid value can only be 1 or 2. // opposite to the preceding conditions, you can add the third parameter $ sph1_-> SetFilter ('fromid ', array (1, 2), false ); // The fromid value cannot be 1 or 2 // specify the value range $ sphsequence-> SetFilterRange ('toid', 5,200 ); // the value of toid is between 5-5,200 // opposite to the preceding condition. you can add the third parameter $ sphsequence-> SetFilterRange ('toid', false ); // the value of toid is 5-. // execute the search $ result = $ sphworkflow-> query ('keyword ','*');
Sorting mode
You can sort the search results in the following mode:
SPH_SORT_RELEVANCE mode, sorted in descending order of relevance (the best match ranks first)
SPH_SORT_ATTR_DESC mode, which is arranged in descending order of attributes (the higher the attribute value, the more advanced)
SPH_SORT_ATTR_ASC mode, which is arranged in ascending order of attributes (the smaller the attribute value, the more advanced)
In SPH_SORT_TIME_SEGMENTS mode, first sort by time period (last hour/day/week/month) in descending order, then sort by relevance in descending order
In SPH_SORT_EXTENDED mode, columns are combined in a way similar to SQL in ascending or descending order.
SPH_SORT_EXPR mode, sorted by an arithmetic expression
// Use attribute sorting // Sort by fromid in reverse order. Note that when SetSortMode is used again, the previous sorting will be overwritten. $ sphsort-> SetSortMode ("SPH_SORT_ATTR_DESC", 'fromid '); // If you want to sort multiple fields, use the SPH_SORT_EXTENDED mode. // @ id is the built-in keyword of sphenders. here it refers to emailid. why is it emailid, think about $ sphmode-> SetSortMode ("SPH_SORT_ATTR_DESC", 'fromid ASC, toid DESC, @ id DESC '); // execute the search $ result = $ sphtasks-> query ('keyword ','*');
// For more information, see the description of the sorting mode of official documents.
Matching mode
The following matching modes are available:
SPH_MATCH_ALL: Match all query words (default mode );
SPH_MATCH_ANY: matches any of the query words;
SPH_MATCH_PHRASE, which regards the entire query as a phrase and requires a complete match in order;
SPH_MATCH_BOOLEAN: queries are treated as a Boolean expression.
SPH_MATCH_EXTENDED: queries are treated as expressions in the internal query language of CoreSeek/sphsf. starting from Coreseek 3/sph00000.9.9, this option is replaced by SPH_MATCH_EXTENDED2, which provides more functions and better performance. Retain this option to be compatible with the legacy code-so that the old application code can continue to work even when sphenders and its components, including the API, are upgraded.
SPH_MATCH_EXTENDED2: use the second version of "extended matching mode" to match the query.
SPH_MATCH_FULLSCAN: forces the "full scan" mode described below to match the query. Note: In this mode, all query words are ignored. Although the filter, filter range, and grouping still work, no text match will happen.
We need to pay attention to the SPH_MATCH_EXTENDED2 extension matching mode, which allows some condition statements like mysql.
// Set the extended match mode $ sphinx-> SetMatchMode ("SPH_MATCH_EXTENDED2"); // use a conditional statement in the query. The field starts with @ and the search content contains the test, emails whose toid is equal to 1: $ result = $ sphresponse-> query ('@ content (test) & @ toid = 1 ','*'); // use parentheses and & (and), |, (or),-(not, that is! =) Set more complex conditions $ result = $ sphtasks-> query ('(@ content (test) & @ subject = er) | (@ fromid-(100 ))', '*'); // for more syntaxes, see the matching mode description in the official documentation.
In the extended matching mode, the value of a field is the search field. if this field is set to an attribute, the extended matching search field does not contain these attributes by default. only SetFilter () can be used () or SetFilterRange ().
Previously, we set fromid, toid, and sendtime as attributes, but what if we want to use them as conditions in the extended matching mode?
You only need to select this field once in the SQL _query statement.
SQL _query = SELECT emailid, fromid, fromid, toid, toid, subject, content, sendtime, sendtime, attachement FROM email
// After the settings are complete, remember to re-create the index.
More conditional skills
It's just some tips, but it is not recommended to use the deployment environment. for the reason, see the end of the article.
<, <=,>,> =
By default, sph does not have these comparison characters.
What if I want to send an email at a time greater than a certain date? Use SetFilterRange () to simulate
// If the value is greater than or equal to the value of $ time $ sphrange-> SetFilterRange ('sendtime', $ time, 10000000000) at a specific time, the maximum value of the time is 10, if you add 1, you cannot surpass it .. // Beyond a certain time segment $ time $ sphinterval-> SetFilterRange ('sendtime', $ time + 1, 10000000000) // if the value is less than or equal to the value of $ time $ sphrange-> SetFilterRange ('sendtime',-1, $ time), the minimum value of time truncation is 0, so we should subtract 1 // greater than a certain time cut $ time $ sphinx-> SetFilterRange ('sendtime',-1, $ time-1)
IS NOT NULL
How can I search for blank fields? for example, if I want to search for emails with empty attachments, someone may want to @ attachment? In fact, this is to search for two single quotes... Strings searched by sphenders do not need to be enclosed by quotation marks.
Currently, sphinx does not provide such a function. In fact, you can perform the following operations on mysql statements:
SQL _query = SELECT emailid, fromid, toidsubject, content, sendtime, attachement! = ''As attach is not null FROM email // A new field attachisnotnull is returned here. when attachisnotnull is 1, the attachment is not empty.
// After the settings are complete, remember to re-create the index.
FIND_IN_SET ()
Search for emails containing an attachment. mysql is used to using a simple statement like FIND_IN_SET. you must set the attribute SQL _attr_multi-value attribute (MVA) in the configuration of sphinx ):
SQL _attr_multi = attachment # attachment can be an attachment ID separated by commas (,), or sphentries such as spaces and semicolons can be recognized.
// After the settings are complete, remember to re-create the index and then use SetFilter () in PHP // search for emails containing the attachment ID as 1 or 2. mysql syntax is like FIND_IN_SET ('attachment ', '1, 2') $ sphment-> SetFilter ('attachment ', array (1, 2) // you can use SetFilterRange, search for emails with attachment IDs in the range of 50-50,100 $ sphenders-> SetFilterRange ('attachment)
Summary
If you want a free, easy-to-use, and fast full-text search engine, sphinx is undoubtedly the best choice, but do not forget the purpose of sphinx: full-text search. Do not think about the messy conditions. If you want to make sphsf-search as flexible as mysql, you can use it completely separately for complex multi-condition searches, such as advanced searches for some emails, so I suggest you spend more time optimizing PHP or mysql code, because it may slow your search.
The best way is to retrieve the content in the simplest way and return the ID to the mysql database for search.
Bytes. There may be some incorrect or not rigorous points, some languages may be frivolous, please forgive me. Take the previous article...