Using Solarium with SOLR for Search – Implementation

Posted by Unknown on Monday, May 5, 2014

This is the third article in a four-part series on using Solarium, in conjunction with Apache’s SOLR search implementation.


In the first part I introduced the key concepts and we installed and set up SOLR. In part two we installed and configured Solarium, a library which enables us to use PHP to “talk” to SOLR as if it were a native component.


Now we’re finally ready to start building the search mechanism, which is the subject of this installment.




Let’s look at how to implement a really simple search:



$query = $client->createSelect();
$query->setQuery(Input::get('q'));



Input::get('q') is simply Laravel’s way of grabbing a GET or POST variable named q which, you’ll remember, is the name of our search form element.



Or better still, use a placeholder to escape the search phrase:



$query->setQuery('%P1%', array(Input::get('q')));



A placeholder is indicated by the % symbols. The letter “P” means “escape this as a Phrase”. The bound variables are passed as an array, and the number indicates the position in the array of the argument you wish to bind; bearing in mind that (perhaps unusually) 1 indicates the first item.



To run the search:



$resultset = $client->select($query);


You can now retrieve the number of results using the getNumFound() method, for example:



printf('Your search yielded %d results:', $resultset->getNumFound());


$resultset is an instance of Solarium\QueryType\Select\Result\Result, which implements the Iterator interface - so you can iterate through the results as follows:



foreach ($resultset as $document) {
. . .
}


Each result is an instance of Solarium\QueryType\Select\Result\Document, which provides two ways in which you can access the individual fields - either as public properties, e.g.:


<?php print $document->title ?>





Or, you can iterate through the available fields:



foreach($document AS $field => $value)
{
// this converts multi-value fields to a comma-separated string
if(is_array($value)) $value = implode(', ', $value);

print '' . $field . ': ' . $value . '
';
}


Note that multi-value fields - such as cast - will return an array; so in the example above, it will simply collapse these fields into a comma-separated list.


Continue reading %Using Solarium with SOLR for Search – Implementation%




more

{ 0 comments... » Using Solarium with SOLR for Search – Implementation read them below or add one }

Post a Comment

Popular Posts