Slow meta query with multi meta keys

The problem here is that post meta wasn’t designed for these kinds of searches, that’s why the taxonomy tables exist, else categories and tags would be stored as post meta

  • Post meta is optimised for fetching data when you already know the post ID
  • Taxonomies are optimised for finding posts when you already know the data

A lot of your custom fields would be more appropriate as non-hierarchical taxonomies of the same name.

As for speeding up your meta query, I’m sorry to say but what you’re trying to do is fundamentally expensive, and there’s no way of getting around it. You can try to cache the result, but that’s sub-optimal.

You will need to change your query to use taxonomies, which means modifying your data. Either by moving some post meta data to taxonomies, or storing the data in both post meta and taxonomies at the same time.

Potential ways to mitigate this involve elastic search clusters

You’ve also specified -1 for the max number of posts, which could be dangerous. If 10,000 posts are returned your server may timeout, and your Database may be overloaded. Always set an upper limit, even if it’s one you never expect to reach

Summary

  • Using meta queries to find posts is super expensive
  • Post meta isn’t built for filtering
  • Taxonomies were built for filtering, and they’re significantly faster for this
  • Post meta is designed for when you already know which posts, so get_post_meta is a fast function
  • Always put an upper limit on how many posts you’re fetching

Leave a Comment