I would like to run custom WP_Query calls through ElasticPress. How can I do this?

By default, ElasticPress integrates with all search queries on your WordPress site that use the WP_Query ‘s‘ parameter. Depending on additional Features you activate, such as Facets, ElasticPress may also integrate with certain other queries, such as Taxonomy Archive queries.

But what if you want to run a custom, complex query directly through ElasticPress/Elasticsearch instead of MySQL? It’s easy with ElasticPress! Simply add the ep_integrate => true parameter to any WP_Query, and your search will be routed through Elasticsearch instead of MySQL. Learn more about ElasticPress’ ep_integrate and other supported WP_Query parameters here.

While it can be tempting to route queries through Elasticsearch, keep in mind that there are tradeoffs inherent in using Elasticsearch vs MySQL. First and foremost, simple queries are almost always faster in MySQL, since Elasticsearch requires an HTTP connection to send and return its query. Additionally, queries referencing indexed IDs (like Post or metadata IDs) are often faster in MySQL.

The best way to use ElasticPress for custom queries is to analyze where your site experiences poor query performance, and then selectively replace those queries by routing them through Elasticsearch. For example, if you have a metadata query expressing a complex relationship, this query can become quite slow, especially with a large set of Posts.

This query looks for posts that contain meta value in the key_name meta field, but do not contain meta value within key_name2.

PHP
new WP_Query(
	[
		'meta_query' => [
			[
				'key'   => 'key_name',
				'value' => 'meta value',
				'compare' => '=',
			],
			[
				'key'   => 'key_name2',
				'value' => 'meta value',
				'compare' => '!=',
			],
			'relation' => 'AND',
		],
	]
);

Given a large database of a few hundred thousand posts, this query can take hundreds of milliseconds or longer within MySQL but can be replaced with an Elasticsearch query running in a fraction of the time. To do this, simply add the ep_integrate => true parameter to the previous query, either directly or through a filter like pre_get_posts.

PHP
new WP_Query(
	[
		'ep_integrate' => true,
		'meta_query'   => [
			[
				'key'   => 'key_name',
				'value' => 'meta value',
				'compare' => '=',
			],
			[
				'key'   => 'key_name2',
				'value' => 'meta value',
				'compare' => '!=',
			],
			'relation' => 'AND',
		],
	]
);

Now the query will run through Elasticsearch, bypassing MySQL, even though it’s not a search. You can apply the ep_integrate parameter to almost any WP_Query to take advantage of ElasticPress’ ability to easily route complex queries to Elasticsearch–give it a try!