Hi, I have a custom entity which has a price field(not Field API). I have an index for fulltext search and also for the price(to sort results by it). I need to find the highest and lowest value of the price for all of the found items. How should my query look like? Currently I am using this:

$index = search_api_index_load('items');
$query = $index->query();
$query->fields($index->getFulltextFields());
$query->keys($string);
$query->range($offset, $limit);
$query->execute();

Comments

drunken monkey’s picture

There is no built-in way to do this. You can either pick it from the results yourself (you have to request all of them in that case, of course) or use two queries, each with limit 1 and sorted by the price once ascending and once descending.
See also search_api_ranges_minmax() from the Search API Ranges project.

Another way would be to use facets on the price field to return all prices associated with the matched items, sort them and then obtain the minimum and maximum this way.

However, this is only true if you want a clean solution that works with the Search API generically. If you need this for a custom module on your site, and are using the Database Search backend, you could also subclass the SearchApiDbService class to provide a way to easily retrieve the min and max values of fields along with the query result.