Grouping search results

At times we may need to group our search results by an attribute. For example, to show monthly statistics about our blog posts we will need to group the posts by publish_date, or to show count of books by a particular author we will need to group the search results by author.

Sphinx offers a grouping mode which is enabled with SetGroupBy() API call. All matches are assigned to different groups based on group-by value when grouping is used.

Different functions are available to compute the group-by value:

  • SPH_GROUPBY_DAY: Extracts year, month, and day in YYYYMMDD format from the timestamp attribute
  • SPH_GROUPBY_WEEK: Extracts year and first day of the week number in YYYYNNN format from timestamp
  • SPH_GROUPBY_MONTH: Extracts year and month in YYYYMM format from timestamp
  • SPH_GROUPBY_YEAR: Extracts year in YYYY format from timestamp
  • SPH_GROUPBY_ATTR: Attribute value is used for grouping

The function to be used for grouping is:

SetGroupBy ( $attribute, $func, $groupsort="@group desc" )

The first parameter is the attribute name on which the grouping should be done. The second parameter is the function grouping order to be used (one of the name mentioned above). And finally, the third parameter is a clause that controls how the groups will be sorted. Its syntax is similar to that shown in the example for the SPH_SORT_EXTENDED sorting mode earlier. The third parameter is optional.

The final search result set contains one best match per group. Grouping function value and per-group match count are returned as long as attributes names @groupby and @count respectively.

Example:

$client->SetMatchMode(SPH_MATCH_ANY);
$client->SetGroupBy('author_id', SPH_GROUPBY_ATTR);
$results = $client->Query('php language framework games electronics'),
print_r($results);

The output of the script can be seen in the following screenshot:

Grouping search results
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset