From a5728a283107a72f4643e435c1c7f214f918aa53 Mon Sep 17 00:00:00 2001 From: eileenmcnaugton Date: Sat, 22 Aug 2015 20:18:32 +1200 Subject: [PATCH] CRM-12326 alter quicksearch to improve speed. This commit removes the OR in favour of a union. With the Or the query does not index properly. On a DB of 300k contacts this commit showed quicksearch query going from 3.895 seconds to 0.015 seconds --- api/v3/Contact.php | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/api/v3/Contact.php b/api/v3/Contact.php index 84227531db..aa9ce567c8 100644 --- a/api/v3/Contact.php +++ b/api/v3/Contact.php @@ -847,16 +847,13 @@ function civicrm_api3_contact_getquick($params) { } } else { + $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} "; + $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; if ($config->includeEmailInName) { if (!in_array('email', $list)) { $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )"; } - $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} "; - $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; - } - else { - $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} "; - $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; + $emailWhere = " WHERE email LIKE '$strSearch'"; } } @@ -893,21 +890,28 @@ function civicrm_api3_contact_getquick($params) { {$select} FROM civicrm_contact cc {$from} {$aclFrom} - {$additionalFrom} {$includeEmailFrom} + {$additionalFrom} {$whereClause} {$orderByInner} LIMIT 0, {$limit} ) "; - if ($whereClause != $exactWhereClause) { - $query .= "UNION - ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select} - FROM civicrm_contact cc {$from} - {$aclFrom} - {$additionalFrom} {$includeEmailFrom} - {$whereClause} - {$orderByInner} - LIMIT 0, {$limit} )"; - } + + if (!empty($emailWhere)) { + $query .= " + UNION ( + SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ', + {$actualSelectElements} ) + as data + {$select} + FROM civicrm_contact cc {$from} + {$aclFrom} + {$additionalFrom} {$includeEmailFrom} + {$emailWhere} + {$orderByInner} + LIMIT 0, {$limit} + ) + "; + } $query .=") t {$orderByOuter} LIMIT 0, {$limit} -- 2.25.1