Is there any way I can access the field in which a ->search() found the keyword?
I’m working on very complex pages with different fields, not just a single text field. My search function looks something like that:
foreach ($site->index()->search($keyword) as $result):
But $result seems to be a page object without further information about the whereabouts of the keyword. Using strpos() on every single possible field would probably slow things down too much.
Does anyone know a solution to that? A third-party search plugin? Overwriting the ->search() function in the core? Or did I miss something that’s already built-in?
the search function returns a sorted collection. the pages contain additional fields for searchHits and searchScore but not which search params matched – as far as I can tell. but maybe that would make a nice feature request.
You are right, the native search method only returns a collection of pages without any further information. So it loops through each field, and as @bnomei mentioned above, it weighs results by hits and score, but nothing else.
There is the Algolia plugin as an alternative, but as far as I know, it only returns pages as well.
You could create a custom search function that loops through all fields of a page and saves that information in an array, I don’t know how much that would slow down the search though. The native search methods goes through all fields as well…
// before the loop
$page->searchMatches = ''; // add this
//... inside the loop
$page->searchHits += $matches;
$page->searchScore += $matches * $score;
$page->searchMatches .= ltrim(',', $page->searchMatches . ',' .implode(',', $r)); // add this as well
// maybe down below at 'full match' again, don't know. ;-)
now each page should have a seachMatches property with comma separated strings.
one could sort match-strings by score but i leave that to the kirby team.