drupaldrupal-7drupal-modules

Drupal Search API custom search field order


I am using search api views module to search my apache Solr Search engine. I would like to have a custom order for the returned results. I would like the jq_articles results to appear first, then books, then mydocuments.

How can I have this customer order (with is neither ASC or DESC) for my returned results?

I need something like $query->orderby('jq_articles, 'books', 'mydocuments');

This is how my query_alter looks at the time being:

<?php
function mymodule_search_api_query_alter(SearchApiQueryInterface $query) {
    $filters = &$query->getFilter()->getFilters();

    foreach ($filters as $i => $filter) {
        $condition = "";

        $finalfilters = &$filter->getFilters();

        foreach($finalfilters as $z => $singlefilter){
            if($singlefilter[0] == 'type') {
                $condition = $singlefilter[1];
                unset($finalfilters[$z]);
            }
        }
    }

    $filter = $query->createFilter('OR');

    switch($condition) {
        case 'journals':
            $filter->condition('type', 'jq_articles');
            break;

        case 'books':
            $filter->condition('type', 'books');
            break;

        case 'mydocuments':
            $filter->condition('type', 'mydocuments');

        default:
            $filter->condition('type', 'mydocuments');
            $filter->condition('type', 'books');
            $filter->condition('type', 'jq_articles');
            break;

    }

    $query->filter($filter);

}

?>

Solution

  • You can do this by adding the following in hook_search_api_query_alter()

    $query->sort('jq_articles', 'DESC');
    

    If you want to sort by multiple fields, you should do like this:

    $query->sort('field1', 'DESC');
    $query->sort('field2', 'ASC');