I would like to search for words that contains the keyword when a user executes a search. I have tried to hook into hook_query_alter()
:
function MYMODULE_query_alter(&$query) {
// Check if this is a search query
if (!$query->hasTag('search_node')) {
return;
}
$conditions = &$query->conditions();
$conditions = &$conditions[1]['field']->conditions();
// Change the condition to '%<keyword>%'
// and add LIKE as operator
$conditions[0]['value'] = "%" . $conditions[0]['value'] . "%";
$conditions[0]['operator'] = 'LIKE';
}
I can alter the search query, but I'm not getting any results.
The modified query that gets executed looks like this:
SELECT FROM {search_index} i
INNER JOIN {node} n ON n.nid = i.sid
INNER JOIN {search_total} t ON i.word = t.word
WHERE (n.status = :db_condition_placeholder_0)
AND ((i.word LIKE :db_condition_placeholder_1 ESCAPE '\\'))
AND (i.type = :db_condition_placeholder_2)
GROUP BY i.type, i.sid
HAVING (COUNT(*) >= :matches)
And the placeholders in the SelectQuery
object are set to:
[:db_condition_placeholder_0] => 1
[:db_condition_placeholder_1] => %liv%
[:db_condition_placeholder_2] => node
I can verify that the tables search_index
and search_total
both contain a couple of words that contain liv
, so this should return some results.
I have also tried Fuzzy Search module, but I don't know how I can connect the provided search to the ordinary search form.
Notice that I have tried db_like()
, but without any success.
I don't understand why it should be so hard to change the default search to search through the index using a LIKE
rather than =
condition?
Something like this should work if I only knew how to implement it:
$keyword = $_GET['s'];
$status = 1;
$types = array('article', 'contact');
db_query("SELECT node.nid FROM {node} n
INNER JOIN {search_index} si
ON si.sid = n.nid
AND si.word LIKE :keyword
INNER JOIN {search_dataset} sd ON sd.sid = n.nid
WHERE n.status = :status AND n.type IN (:types)
GROUP BY n.nid", array(
':keyword' => '%' . db_like($keyword) . '%',
':status' => $status,
':types' => $types
)
);
$query
argument and after I have modified it using the code above it looks fine and updated, but it still don't returns any results. If I search for a whole word that is inside the index for instanceliving
then I get a result as expected. It feels like the modification to the search query does not get applied.$where
, which doesn't exist in that local scope. What's that line supposed to do? I'd wager It ain't doing it