Entity query for distinct field
I don't think it's possible to write a single entity query to accomplish this. You could take your $entity_ids result, use loadMultiple to load all the line_item entities, and then iterate through them to get all the products. Something like this:

$line_items = $this-&gt;entity_type_manager-&gt;getStorage('line_item')-&gt;loadMultiple($entity_ids);

$products = [];
foreach ($line_items as $line_item) {
  $product = $line_item-&gt;getProduct();
  if ($product &amp;&amp; !isset($products[$product-&gt;id()])) {
    $products[$product-&gt;id() = $product;
  }
}


Another possibility would be to use the database service to construct a select query with actual database table names and fields (\Drupal\Core\Database\Connection).

See:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Connection.php/function/Connection%3A%3Aselect/8.2.x

and for the list of methods you can use to construct the select:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/8.2.x