Time for action - adding code to filter the results

  1. Modify the function do_search() in search.php and add the following highlighted code:
    function do_search($q, $author, $categories)
    {
    global $dbh, $viewVars;
    // Include the api class
    require('sphinxapi.php'),
    $client = new SphinxClient();
    // Set search options
    $client->SetServer('localhost', 9312);
    $client->SetConnectTimeout(1);
    $client->SetArrayResult(true);
    // Set the mode to SPH_MATCH_EXTENDED2
    $client->SetMatchMode(SPH_MATCH_EXTENDED2);
    // Match the search term against title and description
    $query = "@(title,description) ($q)";
    // If we have author then match it against author field
    if (!empty($author)) {
    $query .= "@author $author";
    }
    // If categories were selected then filter the results
    if (!empty($categories)) {
    $client->SetFilter('category_id', $categories);
    }
    // Fire the search query against feed-items index (main index)
    $viewVars['results'] = $client->Query($query, 'feed-items'),
    $viewVars['items'] = array();
    // Get the item title and link for the matches
    if (!empty($viewVars['results']['matches'])) {
    foreach ($viewVars['results']['matches'] as $match) {
    $itemIds[] = $match['id'];
    }
    $query = "SELECT id, title, link FROM items
    WHERE id IN (" . implode(',', $itemIds) . ")";
    $stmt = $dbh->prepare($query);
    $stmt->execute();
    while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $viewVars['items'][$item['id']] = $item;
    }
    }
    }//end do_search()
    

What just happened?

We added code to include author in the search query if a user has entered the author name in the search form. The final search query looks something like this:

@(title,description) ($q) @author $author

The search query will match $q against the title and description, and in addition to this the author field should also match $author.

The second bit of code filters the results by categories. So, only those results that match the full-text query and have the selected categories assigned to them will be finally returned by Sphinx.

We have one final addition to complete our Feed Search application.

..................Content has been hidden....................

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