I am using the following code.

$query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'article');
  for ($i = 0; $i < count($split_keys); $i++){
  $group = $query->orConditionGroup()
  ->condition('title', '%'.$keys.'%' ,'LIKE')
  ->condition('body', '%'.$keys.'%' ,'LIKE')
  ->condition('title', '%'.$split_keys[$i].'%' ,'LIKE')
  ->condition('body', '%'.$split_keys[$i].'%' ,'LIKE');
  $query->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->sort('order_col', 'ASC');
  $entity_search = $query->condition($group)->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?

1 Answer 1


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.

  • Thank you for your suggestion @Clive, is there any solution besides using Search API, or any suggest if using another query to get that result? I'm very noob to integrate Search API module with my custom theme
    – sidikidis
    Oct 30, 2018 at 6:05
  • I don’t have another suggestion, sorry. If you’re happy that your SQL logic with the cases etc is correct, then converting it to use a raw query instead of entity query is the best I can advise
    – Clive
    Oct 31, 2018 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.