PHP code example of heyday / silverstripe-elastica
1. Go to this page and download the library: Download heyday/silverstripe-elastica library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
heyday / silverstripe-elastica example snippets
class Page extends SiteTree
{
public function getSomeCustomFieldSimple()
{
return 'some dynamic text or something';
}
public function getSomeCustomFieldComplicatedConfig()
{
return 'the config does not have anyting to do with me';
}
}
class SearchController extends Page_Controller
{
/**
* @var array
*/
private static $allowed_actions = [
'index'
];
/**
* @var \Heyday\Elastica\ElasticaService
*/
protected $searchService;
/**
* Search results page action
*
* @return HTMLText
*/
public function index()
{
return $this->renderWith(['SearchResults', 'Page']);
}
/**
* @param \Heyday\Elastica\ElasticaService $searchService
*/
public function setSearchService(\Heyday\Elastica\ElasticaService $searchService)
{
$this->searchService = $searchService;
}
/**
* @return bool|\Heyday\Elastica\PaginatedList
*/
public function Results()
{
$request = $this->getRequest();
if ($string = $request->requestVar('for')) {
$query = new \Elastica\Query\BoolQuery();
$query->addMust(
new \Elastica\Query\QueryString(strval($string))
);
$results = $this->searchService->search($query);
return new \Heyday\Elastica\PaginatedList($results, $request);
}
return false;
}
/**
* Query all Page fields and RelatedObjects nested fields.
*
* @return bool|\SilverStripe\ORM\PaginatedList
*/
public function ResultsWithRelatedObjects()
{
$request = $this->getRequest();
if ($string = $request->requestVar('for')) {
$queryString = new \Elastica\Query\QueryString(strval($string));
$boolQuery = new \Elastica\Query\BoolQuery();
$nestedQuery = new \Elastica\Query\Nested();
$nestedQuery->setPath('RelatedDataObjects');
$nestedQuery->setQuery($queryString);
$boolQuery->addShould($queryString);
$boolQuery->addShould($nestedQuery);
$results = $this->searchService->search($boolQuery);
return new \SilverStripe\ORM\PaginatedList($results, $request);
}
return false;
}
/**
* @return mixed
*/
public function SearchString()
{
return Convert::raw2xml($this->getRequest()->requestVar('for'));
}
}