Add Expression for Entity Query I've been working with the entityQuery to query the db and get an array of filtered nids however I need to add an expression to my query.

I've checked the Query class and found a protected sqlQuery attribute that has access to addExpression(). In my case I'm not extending the class but rather instantiating it through \Drupal::entityQuery('node').

Also after checking a bit I found that the Select class has a function addExpression() that does exactly what I need, but then I lose the entityQuery and has to addJoin/addField and so on for each of the fields I would like to include in my conditions.

My objective:

$expression = "
    (
        6371000
        * acos(
            cos( radians({$latitude}) )
            * cos( radians( {$latitudeField} ) )
            * cos(
                radians( {$longitudeField} )
                - radians({$longitude})
            )
            + sin( radians({$latitude}) )
            * sin( radians( {$latitudeField} ) )
        )
    )";
$query = \Drupal::entityQuery('node')
-&gt;condition('status', 1)
-&gt;condition(`field_city`,1,'=')
-&gt;addExpression($expression, 'distance');

$nids = $query-&gt;execute();


Did I miss something ? Is there any other way to achieve what I want ?

EDIT: I found this approach but doesn't seem straight forward 

EDIT2: Better approach is this
I am not sure if following is what you're looking for, it helped me when I was doing something similar
$sql_snippet = &lt;&lt;&lt;EOF

ROUND(
CASE $this-&gt;tableAlias.$unit_column
WHEN 'kg' THEN $this-&gt;tableAlias.$this-&gt;realField * :kg_coefficient
WHEN 'lb' THEN $this-&gt;tableAlias.$this-&gt;realField * :lb_coefficient
END
, :precision) = :value
EOF;
// The difference in this invocation of ::addWhereExpression() compared to
// the invocation in the filter handler is that here part of the DB
// placeholders come from $this-&gt;options (such as precision) and others come
// from the actual argument we have received, i.e. derived from
// $this-&gt;argument.
$this-&gt;query-&gt;addWhereExpression(0, $sql_snippet, [
  ':value' =&gt; round($arg['value'], $this-&gt;options['precision']),
  ':kg_coefficient' =&gt; $kg_coefficient,
  ':lb_coefficient' =&gt; $lb_coefficient,
  ':precision' =&gt; $this-&gt;options['precision'],
]);

}
Lifted from Here