Restored guide
Creating a custom Lucene search facet from taxonomy and integrating it into the search form block
A facet is a counted filter: vocabulary terms, authors, or a CCK value, shown beside search results. This note adds a taxonomy facet to the Lucene-based search used on Drupal 6 and places it where the search form lives.
What you are solving
Core search returns a list. Lucene (through the Lucene API project of that period) can also return facet counts if the field was stored at index time. The search form block is a separate render. Integrating the facet means the form and the result list agree on the query parameter that narrows the term.
Index the term
Confirm the node type is in the index and the vocabulary is attached to that type. Reindex after you enable the field. A facet on a term that was never stored will stay empty no matter how correct the form is.
Expose the facet
The Lucene API module looks for facet definitions from hooks named along the lines of hook_luceneapi_facet(). Return a definition that points at the taxonomy field you indexed, with a label people will recognise. Keep the machine name stable; it becomes part of the URL.
function custom_luceneapi_facet() {
return array(
'section' => array(
'title' => t('Section'),
'field' => 'taxonomy_section',
'weight' => 0,
),
);
}
Check the installed module's API file for the exact keys. The shape above is the idea: a named facet, a human label, and the indexed field.
Put it on the search form
Alter the search block form and add a select built from the same vocabulary. On submit, send the chosen term id with the parameter the facet already understands. Do not invent a second query string.
function custom_form_search_block_form_alter(&$form, $form_state) {
$terms = taxonomy_get_tree(2);
$options = array('' => t('Any section'));
foreach ($terms as $term) {
$options[$term->tid] = str_repeat('-', $term->depth) . ' ' . $term->name;
}
$form['section'] = array(
'#type' => 'select',
'#title' => t('Section'),
'#options' => $options,
);
}
Check before you deploy
- Search with no facet and confirm counts are non-zero for terms you know exist.
- Pick a term and confirm every result on the first page carries that term.
- Reindex after vocabulary edits. Stale counts are the usual bug.
Restored guide for the 23 November 2010 note on a Lucene taxonomy facet.