When rewriting a Search API query (using database backend) to order by RAND(), the facets are lost. I have found the issue, steps are as follows:

1. Query is rewritten using $db_query->orderRandom(). This adds an RAND() expression field and a sort on that field alias.

2. Search query is executed properly, results are randomised.

3. Facets are built, and populated by calling the Database::getTemporaryResultsTable() method. This method re-uses the database query, but removes all the expressions. There is still a sort added on the RAND() expression, and therefor the query will fail, resulting in empty facets.

The fix is to also remove the ORDER BY clause from the query. This seems to have no effect on the facet order, as they are sorted at a later stage anyway. I will attach a patch.

Comments

Martijn Houtman created an issue. See original summary.

martijn houtman’s picture

Patch attached.

drunken monkey’s picture

Component: Facets » Database backend
Status: Active » Needs review

Looks good, thanks a lot for reporting and already providing the solution!
Let's just get green light from the test bot, too, and I can commit it. (I don't think we need tests, as the bug only occurs with custom adaptions.)

drunken monkey’s picture

Status: Needs review » Fixed

Test bot is fine with the patch, too, so: committed.
Thanks again!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.