How do I order a search query by best match? I am using the following code.

$query = \Drupal::entityQuery('node');
  $query-&gt;condition('status', 1);
  $query-&gt;condition('type', 'article');
  for ($i = 0; $i &lt; count($split_keys); $i++){
  $group = $query-&gt;orConditionGroup()
  -&gt;condition('title', '%'.$keys.'%' ,'LIKE')
  -&gt;condition('body', '%'.$keys.'%' ,'LIKE')
  -&gt;condition('title', '%'.$split_keys[$i].'%' ,'LIKE')
  -&gt;condition('body', '%'.$split_keys[$i].'%' ,'LIKE');
  }
  $query-&gt;range(10,20);
  $query-&gt;addExpression('CASE WHEN title like %'.$key.'% THEN 0 
       WHEN title like %'.$split_keys[$i].'% THEN 1 
       WHEN body like %'.$keys.'% THEN 2 
       WHEN body like %'.$split_keys[$i].'% THEN 3 
       ELSE 4 END', 'order_col');
  $query-&gt;sort('order_col', 'ASC');
  $entity_search = $query-&gt;condition($group)-&gt;execute();


I am trying to sort by best match, but I get the following error. 


  Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()


How can I fix the code?
An entity query can't have arbitrary expressions added to it. To proceed with your current approach you'll need to execute a raw query against the database.

But to address your actual question, How to create search query in Drupal 8 order by best match, the answer is to use the Search API module:


  This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module.


In my experience the Solr integration is excellent, but if you don't have a Solr server handy, you can always fall back on the included database backend module. I would imagine that the results you get using search API will be better than any query you can put together yourself in any short amount of time.