Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Elasticsearch.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
21  private $client;
22 
26  private $clientOptions;
27 
31  private $pingResult;
32 
36  private $serverVersion;
37 
45  public function __construct(
46  $options = [],
47  $elasticsearchClient = null
48  ) {
49  if (empty($options['hostname']) || ((!empty($options['enableAuth']) &&
50  ($options['enableAuth'] == 1)) && (empty($options['username']) || empty($options['password'])))) {
51  throw new LocalizedException(
52  __('The search failed because of a search engine misconfiguration.')
53  );
54  }
55 
56  if (!($elasticsearchClient instanceof \Elasticsearch\Client)) {
57  $config = $this->buildConfig($options);
58  $elasticsearchClient = \Elasticsearch\ClientBuilder::fromConfig($config, true);
59  }
60  $this->client[getmypid()] = $elasticsearchClient;
61  $this->clientOptions = $options;
62  }
63 
69  private function getClient()
70  {
71  $pid = getmypid();
72  if (!isset($this->client[$pid])) {
73  $config = $this->buildConfig($this->clientOptions);
74  $this->client[$pid] = \Elasticsearch\ClientBuilder::fromConfig($config, true);
75  }
76  return $this->client[$pid];
77  }
78 
84  public function ping()
85  {
86  if ($this->pingResult === null) {
87  $this->pingResult = $this->getClient()->ping(['client' => ['timeout' => $this->clientOptions['timeout']]]);
88  }
89 
90  return $this->pingResult;
91  }
92 
98  public function testConnection()
99  {
100  return $this->ping();
101  }
102 
109  private function buildConfig($options = [])
110  {
111  $host = preg_replace('/http[s]?:\/\//i', '', $options['hostname']);
112  $protocol = parse_url($options['hostname'], PHP_URL_SCHEME);
113  if (!$protocol) {
114  $protocol = 'http';
115  }
116  if (!empty($options['port'])) {
117  $host .= ':' . $options['port'];
118  }
119  if (!empty($options['enableAuth']) && ($options['enableAuth'] == 1)) {
120  $host = sprintf('%s://%s:%s@%s', $protocol, $options['username'], $options['password'], $host);
121  }
122 
123  $options['hosts'] = [$host];
124  return $options;
125  }
126 
133  public function bulkQuery($query)
134  {
135  $this->getClient()->bulk($query);
136  }
137 
145  public function createIndex($index, $settings)
146  {
147  $this->getClient()->indices()->create([
148  'index' => $index,
149  'body' => $settings,
150  ]);
151  }
152 
159  public function deleteIndex($index)
160  {
161  $this->getClient()->indices()->delete(['index' => $index]);
162  }
163 
170  public function isEmptyIndex($index)
171  {
172  $stats = $this->getClient()->indices()->stats(['index' => $index, 'metric' => 'docs']);
173  if ($stats['indices'][$index]['primaries']['docs']['count'] == 0) {
174  return true;
175  }
176  return false;
177  }
178 
187  public function updateAlias($alias, $newIndex, $oldIndex = '')
188  {
189  $params['body'] = ['actions' => []];
190  if ($oldIndex) {
191  $params['body']['actions'][] = ['remove' => ['alias' => $alias, 'index' => $oldIndex]];
192  }
193  if ($newIndex) {
194  $params['body']['actions'][] = ['add' => ['alias' => $alias, 'index' => $newIndex]];
195  }
196 
197  $this->getClient()->indices()->updateAliases($params);
198  }
199 
206  public function indexExists($index)
207  {
208  return $this->getClient()->indices()->exists(['index' => $index]);
209  }
210 
218  public function existsAlias($alias, $index = '')
219  {
220  $params = ['name' => $alias];
221  if ($index) {
222  $params['index'] = $index;
223  }
224  return $this->getClient()->indices()->existsAlias($params);
225  }
226 
233  public function getAlias($alias)
234  {
235  return $this->getClient()->indices()->getAlias(['name' => $alias]);
236  }
237 
246  public function addFieldsMapping(array $fields, $index, $entityType)
247  {
248  $params = [
249  'index' => $index,
250  'type' => $entityType,
251  'body' => [
252  $entityType => [
253  '_all' => $this->prepareFieldInfo([
254  'enabled' => true,
255  'type' => 'text',
256  ]),
257  'properties' => [],
258  'dynamic_templates' => [
259  [
260  'price_mapping' => [
261  'match' => 'price_*',
262  'match_mapping_type' => 'string',
263  'mapping' => [
264  'type' => 'float',
265  'store' => true,
266  ],
267  ],
268  ],
269  [
270  'string_mapping' => [
271  'match' => '*',
272  'match_mapping_type' => 'string',
273  'mapping' => $this->prepareFieldInfo([
274  'type' => 'text',
275  'index' => false,
276  ]),
277  ],
278  ],
279  [
280  'position_mapping' => [
281  'match' => 'position_*',
282  'match_mapping_type' => 'string',
283  'mapping' => [
284  'type' => 'int',
285  ],
286  ],
287  ],
288  ],
289  ],
290  ],
291  ];
292  foreach ($fields as $field => $fieldInfo) {
293  $params['body'][$entityType]['properties'][$field] = $this->prepareFieldInfo($fieldInfo);
294  }
295 
296  $this->getClient()->indices()->putMapping($params);
297  }
298 
306  private function prepareFieldInfo($fieldInfo)
307  {
308 
309  if (strcmp($this->getServerVersion(), '5') < 0) {
310  if ($fieldInfo['type'] == 'keyword') {
311  $fieldInfo['type'] = 'string';
312  $fieldInfo['index'] = isset($fieldInfo['index']) ? $fieldInfo['index'] : 'not_analyzed';
313  }
314 
315  if ($fieldInfo['type'] == 'text') {
316  $fieldInfo['type'] = 'string';
317  }
318  }
319 
320  return $fieldInfo;
321  }
322 
330  public function deleteMapping($index, $entityType)
331  {
332  $this->getClient()->indices()->deleteMapping([
333  'index' => $index,
334  'type' => $entityType,
335  ]);
336  }
337 
344  public function query($query)
345  {
346  $query = $this->prepareSearchQuery($query);
347 
348  return $this->getClient()->search($query);
349  }
350 
358  private function prepareSearchQuery($query)
359  {
360  if (strcmp($this->getServerVersion(), '5') < 0) {
361  if (isset($query['body']) && isset($query['body']['stored_fields'])) {
362  $query['body']['fields'] = $query['body']['stored_fields'];
363  unset($query['body']['stored_fields']);
364  }
365  }
366 
367  return $query;
368  }
369 
376  public function suggest($query)
377  {
378  return $this->getClient()->suggest($query);
379  }
380 
386  private function getServerVersion()
387  {
388  if ($this->serverVersion === null) {
389  $info = $this->getClient()->info();
390  $this->serverVersion = $info['version']['number'];
391  }
392 
393  return $this->serverVersion;
394  }
395 }
$config
Definition: fraud_order.php:17
__construct( $options=[], $elasticsearchClient=null)
$fields
Definition: details.phtml:14
__()
Definition: __.php:13
$settings
Definition: bootstrap.php:29
if(!trim($html)) $alias
Definition: details.phtml:20
foreach( $_productCollection as $_product)() ?>" class $info
Definition: listing.phtml:52
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$index
Definition: list.phtml:44