perf(2meet-data-optimizer): count routed searches from a cached base count minus the excluded posts
- a routed search with post__not_in (HivePress sends a random set per page) caches the COUNT without the exclusion and subtracts a live primary-key count of the excluded posts that match; the total stays exact - the excluded count drops STRAIGHT_JOIN so MySQL starts from posts.ID - Verify: PostQueryRouterFoundRowsTest, unit 698, integration 577, phpcs, stan; dev36 live router suite and keyword + price search - PR: PR-091
This commit is contained in:
@@ -372,7 +372,23 @@ class TMDO_Post_Query_Router {
|
||||
if ( ! $counted ) {
|
||||
return $request;
|
||||
}
|
||||
$matches = preg_replace( '/\s+LIMIT\s+\d+(\s*,\s*\d+)?\s*$/i', '', $request );
|
||||
global $wpdb;
|
||||
$matches = (string) preg_replace( '/\s+LIMIT\s+\d+(\s*,\s*\d+)?\s*$/i', '', $request );
|
||||
$not_in = " AND {$wpdb->posts}.ID NOT IN (";
|
||||
// post__not_in (HivePress sends a random set per page) would give every
|
||||
// search its own cache key: count without it (cached) minus the excluded
|
||||
// posts that match (primary-key lookups, so no forced flat-first order).
|
||||
if ( 1 === substr_count( $matches, $not_in ) && preg_match( '/' . preg_quote( $not_in, '/' ) . '([\d,]+)\)/', $matches, $m ) ) {
|
||||
$excluded = str_replace( $m[0], " AND {$wpdb->posts}.ID IN ({$m[1]})", (string) preg_replace( '/^SELECT STRAIGHT_JOIN /', 'SELECT ', $matches ) );
|
||||
$query->set(
|
||||
self::COUNT_VAR,
|
||||
array(
|
||||
'SELECT COUNT(*) FROM ( ' . str_replace( $m[0], '', $matches ) . ' ) AS tmdo_found',
|
||||
"SELECT COUNT(*) FROM ( {$excluded} ) AS tmdo_found",
|
||||
)
|
||||
);
|
||||
return $request;
|
||||
}
|
||||
$query->set( self::COUNT_VAR, "SELECT COUNT(*) FROM ( {$matches} ) AS tmdo_found" );
|
||||
return $request;
|
||||
}
|
||||
@@ -414,13 +430,18 @@ class TMDO_Post_Query_Router {
|
||||
if ( empty( $count_sql ) ) {
|
||||
return (string) ( $sql ?? '' );
|
||||
}
|
||||
global $wpdb;
|
||||
list( $count_sql, $excluded_sql ) = array_pad( (array) $count_sql, 2, '' );
|
||||
|
||||
$key = md5( $count_sql ) . ':' . wp_cache_get_last_changed( 'posts' );
|
||||
$total = wp_cache_get( $key, self::COUNT_CACHE_GROUP );
|
||||
if ( false === $total ) {
|
||||
global $wpdb;
|
||||
$total = (int) $wpdb->get_var( $count_sql );
|
||||
wp_cache_set( $key, $total, self::COUNT_CACHE_GROUP, HOUR_IN_SECONDS );
|
||||
}
|
||||
if ( '' !== $excluded_sql ) {
|
||||
$total = max( 0, (int) $total - (int) $wpdb->get_var( $excluded_sql ) );
|
||||
}
|
||||
return 'SELECT ' . (int) $total;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user