Skip to content

Instantly share code, notes, and snippets.

@damienalexandre
Created May 28, 2013 08:30
Show Gist options
  • Save damienalexandre/5661320 to your computer and use it in GitHub Desktop.
Save damienalexandre/5661320 to your computer and use it in GitHub Desktop.
Here is an example of how to get a query Filter from a list of Facet and user query (how to apply a facet on a query) with Elastica.
<?php
/**
* Return query Filter from a list of query string & allowed Facets
*
* @param array $query The user query (facet_name => query, facet_name => query...)
* @param array $allowed_facets An array of Elastica\Facet
*
* @return \Elastica\Filter\AbstractFilter (if multiple filters, they are combined in BoolAnd filter)
*/
private function getFacetsFilters($query, $allowed_facets)
{
$filters = array();
if (!is_array($query)) {
return false;
}
if (!$allowed_facets || !is_array($allowed_facets) || empty($allowed_facets)) {
return false;
}
foreach ($query as $facet_name => $term)
{
$facet = false;
foreach ($allowed_facets as $allowed_facet) {
if ($allowed_facet->getName() === $facet_name) {
$facet = $allowed_facet; break;
}
}
if ($facet instanceof AbstractFacet) {
switch (get_class($facet))
{
case 'Elastica\Facet\Terms':
$filters[] = new \Elastica\Filter\Terms($facet->getParam('field'), array($term));
break;
case 'Elastica\Facet\Range':
$ranges = $facet->getParam('ranges');
if (isset($ranges[(int) $term])) {
$filters[] = new \Elastica\Filter\NumericRange($facet->getParam('field'), $ranges[(int) $term]);
}
break;
case 'Elastica\Facet\Filter':
$facet_filters = $facet->toArray();
if (isset($facet_filters['filter']['exists'])) {
$filters[] = new \Elastica\Filter\Exists($facet_filters['filter']['exists']['field']);
} else {
throw new \Exception(sprintf('The "%s" facet query filter cant be set', $facet_name));
}
break;
default:
throw new \Exception(sprintf('The "%s" facet query filter is not implemented!!', $facet_name));
}
}
}
if (count($filters) > 1) {
$and = new \Elastica\Filter\BoolAnd();
foreach ($filters as $filter) {
$and->addFilter($filter);
}
return $and;
} elseif (count($filters) === 1) {
return $filters[0];
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment