Time for action - adding code to perform a search query

  1. Modify the Sphinx configuration file /var/local/sphinx/etc/feeds.conf and add section for searchd:
    # Other options (not shown for brevity)
    index feed-items-delta : feed-items
    {
    source = feeds-delta
    path = /usr/local/sphinx/var/data/feed-items-delta
    }
    indexer
    {
    mem_limit = 64M
    }
    searchd
    {
    listen = 9312
    log = /usr/local/sphinx/var/log/feeds-searchd.log
    query_log = /usr/local/sphinx/var/log/feeds-query.log
    max_children = 30
    pid_file = /usr/local/sphinx/var/log/feeds-searchd.pid
    }
    
  2. Stop the searchd daemon (as root). You need to do this only if searchd is already running:
    $ /usr/local/sphinx/bin/searchd -c /path/to/sphinx.conf --stop
    
  3. Start the searchd daemon (as root):
    $ /usr/local/sphinx/bin/searchd c /usr/local/sphinx/etc/feeds.conf i feed-items
    
    Time for action - adding code to perform a search query
  4. Modify search.php and add the following (highlighted) code:
    <?php
    /**
    * File: /path/to/webroot/feeds/search.php
    */
    include('init.php'),
    // Get the data from post if form is submitted
    // else initialize variables to empty strings
    $q = !empty($_POST['q']) ? $_POST['q'] : '';
    $author = !empty($_POST['author']) ? $_POST['author'] : '';
    $categories = !empty($_POST['categories']) ? $_POST['categories'] : array();
    $categories = !empty($_POST['categories']) ? $_POST['categories'] : array();
    // Perform the search if we have a search term
    if (!empty($q)) {
    do_search($q, $author, $categories);
    }
    // Get all the categories and their ids
    // This will be used to build the categories filter drop down
    $query = "SELECT id, name FROM categories ORDER BY name";
    foreach ($dbh->query($query) as $row) {
    $viewVars['cat_list'][$row['id']] = $row['name'];
    }
    // Render the page
    render('search'),
    /**
    * Method to perform the search
    *
    * @param string $q Fulltext search query
    * @param string $author Name of the author
    * @param array $categories Id of the categories for filtering
    */
    function do_search($q, $author, $categories)
    {
    global $dbh, $viewVars;
    // Include the api class
    require_once('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)";
    // 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()
    
  5. Modify the search.thtml view and add code to display the results:
    <!-- File: /path/to/webroot/feeds/views/search.thtml -->
    <!-- Code truncated for brevity -->
    <div class="input">
    <label>&nbsp;</label>
    <input type="submit" value="Search" name="search" />
    </div>
    </fieldset>
    </form>
    <div class="results">
    <?php if (isset($viewVars['results']) && empty($viewVars['items'])): ?>
    <div class="information">No matching items found!!!</div>
    <?php endif; ?>
    <?php
    if (!empty($viewVars['items'])) {
    print '<div class="information">Total '.$viewVars['results']['total_found'].' items found</div.';
    print '<ul>';
    foreach ($viewVars['results']['matches'] as $match) {
    print '<li>
    <a
    href="'.$viewVars['items'][$match['id']]['link'].'">'
    .$viewVars['items'][$match['id']]['title'].'</a></li>';
    }
    print '</ul>';
    }
    ?>
    </div>
    
  6. Reload search.php in your browser put any term in the Search for field, and click on the Search button. I searched for 'development' as demonstrated in the following screenshot:
    Time for action - adding code to perform a search query

What just happened?

We first added the searchd configuration options to the Sphinx configuration file. We specified where to create the log files and what port to listen at. After that, we stopped the searchd instance, which was already running. We then started the searchd daemon and passed the option -c to it so that only the feed-items (main) index is served.

After that, we modified the search.php script and added code to handle the posted form. We used the SPH_MATCH_EXTENDED2 match mode so that we can supply a query expression. To search against title and description fields we used @(title,description) ($q) expression. This expression reads: 'search all those documents where title and description matches the query'.

Once we get the results from Sphinx, we fetched the respective item's title and link from the feeds table. The document ID returned by Sphinx is the same as the primary key in our feeds table.

In the view, we added code to loop through the results and display a list of items hyperlinked to their original pages.

Applying filters

We still haven't added code to perform a search against author name and filter the results by selected categories. So let's do that now.

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

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