Skip to content

Backgrounds

How-to Guides

Technical References

Enterprise Search /

Offload any WP_Query to Elasticsearch

With Enterprise Search, standard search queries (which have an s argument) are automatically sent to Elasticsearch. No code changes are needed.

All other queries need either very minor or possibly more advanced work to integrate with Elasticsearch, depending on the query complexity.

Be sure to test each query as you go, make sure the results are what you expect, and adjust as needed.

Adding the query argument

If you need to ES enable non-search queries, you’ll need to add an extra WP_Query argument.

The standard (and very easy) way to do this leverages the built-in es-wp-query adapter, which will handle transforming the query into an Elasticsearch request, obtain the search results (generally, a list of Post IDs), and then obtain the post data from the database.

You can do this via a pre_get_posts filter, or by adding it in the argument list where you already use WP_Query (or get_posts) directly.

You simply add one line to the query arguments: 'es' => true

$query = new WP_Query(
	array(
		'post_type'      => 'post',
		'post_status'    => 'publish',
		'posts_per_page' => 10,
		'es'             => true,
	)
);

Now, queries that use es should go to Enterprise Search (i.e. Elasticsearch) rather than MySQL.

However, if any of those queries are filtering by terms (or taxonomy, e.g. categories), the terms feature will need to be enabled.

Advanced use

If you’re offloading existing MySQL queries to Elasticsearch, please use the approach above, with the es parameter. That parameter activates an adapter called es-wp-query that does a very good job of mapping most SQL queries to Elasticsearch, and should cover most use cases.

Direct MySQL

In other cases, you may wish to query MySQL directly. For example, if you’re just providing a list of post IDs, and the query is very fast, there may be no need to use Elasticsearch. Omit the es parameter. Monitor both the results and the speed using tools such as New Relic and Query Monitor / Debug Bar.

ElasticPress offloading via ep_integrate

If es, or a direct DB query, does not produce the search results you need, you may wish to use the ElasticPress approach for offloading select queries – which looks similar but behaves differently.

Instead of es in the WP_Query arguments, use ep_integrate (set to true). You can do this on a case-by-case basis; for example, almost all offloaded queries might use es, and one very specialized query might use ep_integrate.

Please be sure to review the ElasticPress documentation before using this option. And of course, if the query involves terms or users, those features will need to be enabled.

Last updated: May 14, 2021