Faceted search with Sphinx and PHP

Tagged:
<?php
/*
 * Faceted implementation in Sphinx
 * 
 * the 10 best match will be stored into 
 * $result_list = array()
 * 
 * the 100 values fore each filters will be stored into
 * $bundle_filters_results = array()
 */

// search exemple
$query_search = "your query";
$attrs_search = array("one"=>10, "three"=>2);

// parameters
$config_index = "your_index";
$config_filters = array('one', 'two', 'three');

//
// 1. get the 10 best matchs documents
//

// Prepare the query
$sphinx_instance->SetLimits( 0, 10, 10 );
$sphinx_instance->SetRankingMode( SPH_RANK_PROXIMITY_BM25 );

foreach($attrs_search as $key => $value) {
    $sphinx_instance->SetFilter($key, $value);
}

// Fetch the results
$result_list = $sphinx_instance->Query($query, $config_index);

//
// 2. get 100 values for each filters tied to the current search
//

// Prepare the queries
$sphinx_instance->SetLimits( 0, 100, 100 );
$sphinx_instance->SetRankingMode ( SPH_RANK_NONE );

for($i=0; $i<count($config_filters); $i++) {
    $current_filter = $config_filters[$i];

    $sphinx_instance->ResetFilters();
    $sphinx_instance->ResetGroupBy();
    $sphinx_instance->ResetQueryString();

    // query every others filters
    foreach($attrs_search as $key => $value) {
        if( $key != $current_filter) {
            $sphinx_instance->SetFilter( $key, $value );
        }

    }
    $sphinx_instance->SetGroupBy($current_filter, SPH_GROUPBY_ATTR, "@count desc");
    $sphinx_instance->AddQuery( $query_search, $config_index );
}

// Fetch all results
$sphinx_instance->SetArrayResult(true);
$tmp_filters_results = $sphinx_instance->RunQueries();

$bundle_filters_results = array();
for($i=0; $i<count($config_filters); $i++) {
    $current_filter = $config_filters[$i];

    $bundle_filters_results[$current_filter] = $tmp_filters_results[0];
}
?>

See also