Use ElasticPress’ related posts feature with Elasticsearch 6

A while back I updated to Elasticsearch 6, and with that, the related posts feature of ElasticPress stopped working. First I thought it has to do with an ElasticPress issue, but the reason was a parameter used by ElasticPress that is not supported by Elasticsearch 6 that needs to be modified.

ElasticPress uses $formatted_args['query']['more_like_this']['ids'] to define the post to search related content for. The ids key is no longer present in Elasticsearch 6. Instead, you have to create an array per content for that you want related content for, under $formatted_args['query']['more_like_this']['like']. The _id key then gets the ID of the content that was previously stored in ids (that is described in the »More Like This Query« post of the Elasticsearch 6.2 documentation).

That looks like that, using the ep_formatted_args filter by ElasticPress:

function fbn_ep_formatted_args( $formatted_args ) { // Get the ids (usually only one) and unset the unused key. $ids = $formatted_args['query']['more_like_this']['ids']; unset($formatted_args['query']['more_like_this']['ids']); // Set the id in the Elasticsearch 6 compatible way. $formatted_args['query']['more_like_this']['like'][] = [ '_id' => "$ids[0]", ]; return $formatted_args; } add_filter( 'ep_formatted_args', 'fbn_ep_formatted_args', 20 );
Code language: PHP (php)

First, I save the IDs and remove the key from the array. Usually, that will only be one ID, so I do not need to loop over multiple but can directly set $ids[0] as the value for _id in an array under $formatted_args['query']['more_like_this']['like']. After that, I correctly get related posts again instead of the latest posts.

Leave a Reply

Your email address will not be published. Required fields are marked *