Score:1

Is there a way to specify order in a search_api query manually given a set of node ids?

cn flag

Using search_api I have an query with the following condition

$query->condition('nid', [1,5,3,7,10], 'IN')

I know I can sort by things like created date or title, but what if I knew the exact order I wanted everything returned in. So in the above example where I'm grabbing the nodes with ids [1,5,3,7,10] what if I want the results returned in that order too. So after executing in the array of results the nodes appear in 1,5,3,7,10 order.

I tried using orderBy but that does not appear to be a method of the search_api query class

Call to undefined method Drupal\search_api\Query\Query::orderBy()

UPDATE:

I tried passing a sort function into sort on the query like so

      $query->sort(function($a,$b) use ($allowed_nids){
        $pos_a = array_search($a->nid, $allowed_nids);
        $pos_b = array_search($b->nid, $allowed_nids);
        if(($pos_a == $pos_b)){
          return 0;
        }
        return ($pos_a < $pos_b) ? -1 : 1;
      });

But that gave me the error

TypeError: Illegal offset type in isset or empty in Drupal\search_api\Query\Query->sort() (line 465 of modules/contrib/search_api/src/Query/Query.php).

Which I assume means that it can only take strings for the sort function and not anonymous methods.

Score:1
de flag

The error you are receiving is due to the first argument of sort() expecting the field name, not a function: https://git.drupalcode.org/project/search_api/-/blob/8.x-1.x/src/Query/Query.php#L462

As to your issue, I don't believe you can sort them in the query itself, but you can sort the results by the array:

$nids = [1,5,3,7,10];
$query->condition('nid', $nids, 'IN')
$results = $query->execute();

$sorted_results = array_merge(array_flip($nids), $results);
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.