Programmatically, with a view not using search api, we can do this to retrieve the total of results without loading the nodes / rows :

use Drupal\views\Views;
$view = Views::getView('view_name');
$view->build('display_id');
$count = $view->query->query()->countQuery()->execute()->fetchField();

But with search api we can't :

Error: Call to a member function countQuery() on null

Is there another way to do this ? I know I could do $view->get_total_rows = TRUE; and then $view->execute(); but doing this it seems that the loading of the rows decrease performance a lot ! :(

thanks

Comments

Salvor_Hardin created an issue. See original summary.

salvor_hardin’s picture

More precisely : the problem is that I have to count total rows for each content type, not global count. That's why I make a $view->setArguments([$content_type]); and I want to just do a queryCount() and not a complete execute(). That is possible with views but it seems not with search api.

salvor_hardin’s picture

Status: Active » Closed (won't fix)

I found a workaround

rroblik’s picture

@Salvor_Hardin can you please provide us for information ?

marcvangend’s picture

Status: Closed (won't fix) » Closed (works as designed)

I just happened to solve the same problem, before I ran into this issue :-)

This was the best I could come up with:

function getSearchCount($keywords) {
  $count = NULL;

  $view = Views::getView('search');
  $view->setArguments([$keywords]);
  $view->build('page');
  $count = $view->query->getSearchApiQuery()->execute()->getResultCount();

  return $count;
}

As you can see I did need to execute the Search API query, but I'm not executing the entire view. I did not measure the difference in performance, but if anyone does, please let me know the results.

mbatterton’s picture

@marcvangend this was a great help for me thanks. We have then built on this to create this to help us set no-index no-follow tags on views and taxonomy terms that have no results for SEO.

  $current_route_name = \Drupal::service('current_route_match')->getRouteName();
  $route = \Drupal::routeMatch()->getRouteObject();
  if (
    $current_route_name === 'entity.taxonomy_term.canonical' ||
    strpos($current_route_name, 'view.') !== FALSE
  ) {

    //Gets the view id and display id
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    $current_path = explode('/', \Drupal::service('path.current')->getPath());
    $term_id = $current_path[3];

    // Bail out if its not a search view with taxonomy arguments.
    if (!in_array($view_id, ['product_search', 'tags_taxonomy_term'])) {
      return;
    }

    $count = NULL;
    $view = Views::getView($view_id);
    $view->setArguments([$term_id]);
    $view->build($display_id);
    $view->execute();
    $query_count = count($view->result);

If you think this can be improved please let me know.