perf(2meet-data-optimizer): route meta clauses without a value as EXISTS

- WP_Meta_Query adds a value condition only when 'value' is set, so a clause
  like array( 'key' => 'hp_featured' ) only tests that the key exists. The
  router read it as "= ''", declined it, and kept the whole query native
- HivePress runs such a query on every listing search page (featured-listing
  lookup in Attribute::set_search_query(): hp_featured plus the search's own
  filters, ORDER BY RAND()); at 1.3M listings on dev36 it took 2.26 s of a
  2.5 s page, routed or not
- Verify: PostQueryRouterTest (key-only clause routes as IS NOT NULL),
  integration 590, unit 704, phpcs, stan; dev36 front-end
- PR: PR-122
This commit is contained in:
2026-09-27 22:46:52 +08:00
parent eac0955b76
commit 2ed48c3ba3
2 changed files with 35 additions and 5 deletions
@@ -678,6 +678,12 @@ class TMDO_Post_Query_Router {
*/
private static function route_clause( array $clause, array $field ): ?array {
$compare = strtoupper( trim( (string) ( $clause['compare'] ?? '=' ) ) );
// Without 'value', WP_Meta_Query checks only that the key exists (it adds a
// value condition only when one is set): HivePress's featured-listing
// lookup, run on every search page, is array( 'key' => 'hp_featured' ).
if ( ! array_key_exists( 'value', $clause ) && ! in_array( $compare, array( 'EXISTS', 'NOT EXISTS' ), true ) ) {
$compare = 'EXISTS';
}
$type = strtoupper( trim( (string) ( $clause['type'] ?? '' ) ) );
$type = '' === $type ? 'CHAR' : $type;
$value = $clause['value'] ?? '';
+24
View File
@@ -412,4 +412,28 @@ class PostQueryRouterTest extends TestCase {
$this->assertStringContainsString( "LIKE '%B1\\\\_1\\\\%%'", $router->posts_where( '', $query ) );
}
/**
* A clause with no value tests only that the key exists (WP_Meta_Query adds
* a value condition only when 'value' is set), so it routes as EXISTS.
* HivePress's featured-listing lookup on every search page is one:
* array( 'key' => 'hp_featured' ) — it kept the whole query native (2.4 PR-122).
*/
public function test_a_clause_without_a_value_routes_as_exists(): void {
$this->set_post_mode( 'aeav_only' );
$router = new WPDO_Post_Query_Router();
$query = $this->make_query(
array(
'post_type' => 'product',
'meta_query' => array(
array( 'key' => '_stock' ),
array( 'key' => '_price', 'value' => array( 10, 20 ), 'compare' => 'BETWEEN', 'type' => 'NUMERIC' ),
),
)
);
$router->pre_get_posts( $query );
$this->assertEmpty( $query->get( 'meta_query' ), 'both clauses routed' );
$this->assertStringContainsString( '`_stock` IS NOT NULL', $router->posts_where( '', $query ) );
}
}