Remove duplicate records from view result with pager using search api

1.7k Views Asked by At

My project is setup in Drupal 7 and i am using search API for display my custom search result. Actually i want to show search result based on two content types content so i have configure the search api for those content type and select the fields which i want for search and then indexing the content.

For display the search result i am using drupal View of Index node type. But the problem is that in my search result i am getting duplicate result because of some contents have same titles but having different body text.

I want to remove search result which have duplicate title. (Custom field created by myself)

I have tried some custom solution by View hook but its not working properly its give pager issue

function custom_views_pre_render(&$view) {
    if ($view->name == 'search_books') {
        $view_ISBN = array();
        foreach ($view->result AS $key => $res_view) {
            $ISBN = $res_view->entity->field_isbn[und][0]['value'];
            if (!in_array($ISBN,$view_ISBN)) {
                $view_ISBN[] = $ISBN;
                unset($view->result[$key]);
            }
        }

        $view->query->pager->total_items = count($view->result);
        $view->query->pager->update_page_info();
    } 
}

This remove the duplicate result but it gives wrong pager result.

I have also tried the Query alter hook but its not working for me.

function custom_query_alter($query) {

if (isset($query->alterMetaData)) {
    if (isset($query->alterMetaData['view'])) {
        if($query->alterMetaData['view']->name == 'search_books') {
            $fields =& $query->getGroupBy();
                // Tried various fields to check which was the field creating the problem.

                $query->groupBy('field_isbn');
                $query->distinct = TRUE;
        }
    }
}
}

I have also tried to install "views_distinct" module and distinct the field from view but its also gives me pager issue.

Any Idea how to solve this issue?

2

There are 2 best solutions below

0
code.rider On

You can use Grouping field to use Grouping field from you views Format or you can Use
Use aggregation from view Advanced section

1
Mhamed Hmimid On

aggregation in drupal 10 does not avoid the duplicates