Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Adapter.php
Go to the documentation of this file.
1 <?php
7 
14 use \Magento\Elasticsearch\SearchAdapter\ResponseFactory;
15 use Psr\Log\LoggerInterface;
16 
20 class Adapter implements AdapterInterface
21 {
27  protected $mapper;
28 
34  protected $responseFactory;
35 
39  protected $connectionManager;
40 
45 
49  private $queryContainerFactory;
50 
56  private static $emptyRawResponse = [
57  "hits" =>
58  [
59  "hits" => []
60  ],
61  "aggregations" =>
62  [
63  "price_bucket" => [],
64  "category_bucket" =>
65  [
66  "buckets" => []
67 
68  ]
69  ]
70  ];
71 
75  private $logger;
76 
85  public function __construct(
89  AggregationBuilder $aggregationBuilder,
90  \Magento\Elasticsearch\SearchAdapter\QueryContainerFactory $queryContainerFactory,
91  LoggerInterface $logger = null
92  ) {
93  $this->connectionManager = $connectionManager;
94  $this->mapper = $mapper;
95  $this->responseFactory = $responseFactory;
96  $this->aggregationBuilder = $aggregationBuilder;
97  $this->queryContainerFactory = $queryContainerFactory;
98  $this->logger = $logger ?: ObjectManager::getInstance()
99  ->get(LoggerInterface::class);
100  }
101 
108  public function query(RequestInterface $request)
109  {
110  $client = $this->connectionManager->getConnection();
112  $query = $this->mapper->buildQuery($request);
113  $aggregationBuilder->setQuery($this->queryContainerFactory->create(['query' => $query]));
114 
115  try {
116  $rawResponse = $client->query($query);
117  } catch (\Exception $e) {
118  $this->logger->critical($e);
119  // return empty search result in case an exception is thrown from Elasticsearch
120  $rawResponse = self::$emptyRawResponse;
121  }
122 
123  $rawDocuments = isset($rawResponse['hits']['hits']) ? $rawResponse['hits']['hits'] : [];
124  $queryResponse = $this->responseFactory->create(
125  [
126  'documents' => $rawDocuments,
127  'aggregations' => $aggregationBuilder->build($request, $rawResponse),
128  ]
129  );
130  return $queryResponse;
131  }
132 }
__construct(ConnectionManager $connectionManager, Mapper $mapper, ResponseFactory $responseFactory, AggregationBuilder $aggregationBuilder, \Magento\Elasticsearch\SearchAdapter\QueryContainerFactory $queryContainerFactory, LoggerInterface $logger=null)
Definition: Adapter.php:85