Forcing fields to be re-indexed on node update

1
Categories:
drupal search index

On a few of the projects I've worked on it's been an important requirement for the client to have a real fine grain control over the search results displayed for each keyword when using the core search module.

To achieve this level of control I’ve always opted for a CCK text field which is hidden from the typical node output. If the text in this field needs to have a higher weighting than any other content on the node then the field can be indexed inside a <h1> tag. Another requirement has also been to have this field automatically indexed whenever it is updated, which can be achieved with the following code:

/**
* Implementation of hook_nodeapi()
* For adding additional data to search index
*
*/
function MODULENAME_nodeapi(&$node, $op, $teaser, $page) {
    switch ($op) {

        //Update search index with keyword fields contents
        case 'update':
            if($node->type == 'product') {
                //Add field data to be indexed.
                search_index($node->nid,'node', $node->field_search_keywords[0]['value']);
            }
            break;
    }
}

The above snippet implements the nodeapi hook and runs on every node update. If the node type matches then the search_index function is called parsing the cck field value that we want to add to the index. This eliminates the requirement of either explaining to the client that they need to run cron.php, or that they have to wait x minutes until cron is invoked automatically. Obviously with the above code you would need to substitute the module name, node type and cck field value.

Comments

Anonymous's picture
Feb 18
arrow

Interesting stuff! looking forward to the next post.. I've hooked your rss up to my outlook..

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Image CAPTCHA
Enter the characters (without spaces) shown in the image.