-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathQuery.php
547 lines (505 loc) · 17.3 KB
/
Query.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
<?php
/**
* Copyright (c) 2015, Muhannad Shelleh
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace ItvisionSy\EsMapper;
use Exception;
use Elasticsearch\Client;
/**
* The main query class to make querying/fetching data from elasticsearch easy.
*
* It is a general class used for querying one specific index. If you are
* looking for a general-index search, then use the official client sdk
* libraries directly.
*
* @package ItvisionSy\EsMapper
* @author Muhannad Shelleh <[email protected]>
*
* @method Result query(string $type, array $parameters=[])
* @method-static Result query(string $type, array $parameters=[])
* @method AutoQueryBuilder builder()
* @method-static AutoQueryBuilder builder()
* @method Result all(string $type)
* @method-static Result all(string $type)
* @method Result find(string $type, int|string|int[]|string $id)
* @method-static Result find(string $type, int|string|int[]|string $id)
* @method IModel create(array $data, string $index, int|string $id, array $parameters=[])
* @method-static IModel create(array $data, string $index, int|string $id, array $parameters=[])
* @method array delete(string|string $index, string|string[] $type, int|string $id, array $parameters=[])
* @method-static array delete(string|string $index, string|string[] $type, int|string $id, array $parameters=[])
* @property-read Client $client
*/
abstract class Query {
protected $config;
protected $client;
/**
* Factory method for creating query objects
*
* @param array $config The config to use for the client
* @return Query
*/
public static function make(array $config = []) {
return new static($config);
}
/**
* Query object constructor
*
* @param array $config
*/
public function __construct(array $config = []) {
$config += $this->defaults();
$this->config = $config;
$this->establish($config, true);
}
/**
* The index name to be used.
* Should return a string ends with namespace separator path or
* contains the {type} string as a placeholder for the actual model class name.
*
* i.e.
*
* return "\\";
* //means the model classes for Foo and Bar will be \Foo and \Bar
*
* return "\\Models\\";
* //means the model classes for Foo and Bar will be \Models\Foo and
* // \Models\Bar
*
* return "\\Models\\{type}Model";
* //means the model classes for Foo and Bar will be \Models\FooModel and
* // \Models\BarModel
*
* @return string
*/
abstract public function index();
/**
* Gets the namespace/class pattern will be used to create Model objects.
* Should end with \\
* Default value is \ means the root global namespace.
*
* @return string
*/
public function modelClassNamePattern() {
return "\\";
}
/**
* Gets the index name for this query class
* @return string
*/
public function getIndex() {
return $this->index();
}
/**
* Gets the current ES client in use for the object.
*
* @return Client
*/
public function getClient() {
return $this->client;
}
/**
* Establishes the ES client using the provided config.
* Provided config values will take place over the object's config attribute.
* Finally, the defaults() result will be used as a final config source.
*
* @param array $config Config value to override the general config params
* @return Client
*/
public function establish(array $config = [], $assign = false) {
$client = new Client($config + $this->config + $this->defaults());
if ($assign) {
$this->client = $client;
}
return $client;
}
/**
* A decorator class to get all index type documents.
*
* @param string $type
* @return Result|Model[]
*/
protected function _all($type) {
return $this->__query($this->index(), $type);
}
/**
* A decorator method to search for ES documents.
*
* @param string $type
* @param array $query
* @return Result|Model[]
*/
protected function _query($type, array $query = []) {
return $this->__query($this->index(), $type, $query);
}
/**
* A decorator method to get specific document by its id.
* If the id is and array of strings or integers,
* then multiple documents will be retreived by id.
*
* @param string $type
* @param mixed|string|integer|mixed[]|int[]|string[] $id
* @return Model
*/
protected function _find($type, $id) {
if (is_array($id)) {
return $this->__mfind($this->index(), $type, $id);
} else {
return $this->__find($this->index(), $type, $id);
}
}
/**
* Index a new document
*
* @param array $data the document data
* @param string $type
* @param string|number $id
* @param array $parameters
* @return array
*/
protected function _create(array $data, $type, $id = null, array $parameters = []) {
return $this->__create($data, $this->index(), $type, $id, $parameters);
}
/**
* Index a new document
*
* @param array $data the document data
* @param string $index
* @param string $type
* @param string|number $id
* @param array $parameters
* @return array
*/
protected function __create(array $data, $index, $type, $id = null, array $parameters = []) {
$parameters+=["api" => "create"];
$api = strtolower($parameters["api"]) == "index" ? "index" : "create";
unset($parameters["api"]);
$result = $this->client->$api([
'index' => $index,
'type' => $type,
'body' => $data] + ($id ? ['id' => $id] : []) + $parameters);
if (array_key_exists('_shards', $result) && array_key_exists('failed', $result['_shards']) && $result['_shards']['failed'] > 0) {
throw new Exception('Failed to create the document. Serialized results: ' + json_encode($result));
} else {
$result = $this->__find($result['_index'], $result['_type'], $result['_id']);
}
return $result;
}
/**
* Deletes a document
*
* @param string $type
* @param string|number $id
* @param array $parameters
* @return array
*/
protected function _delete($type, $id = null, array $parameters = []) {
return $this->__delete($this->index(), $type, $id, $parameters);
}
/**
* Deletes a document
*
* @param string $index
* @param string $type
* @param string|number $id
* @param array $parameters
* @return array
*/
protected function __delete($index, $type, $id, array $parameters = []) {
$result = $this->client->delete([
'index' => $index,
'type' => $type,
'id' => $id] + $parameters);
return $result;
}
/**
* Add fixed query part to the called query
*
* To add a fixed per-class condition. I.e. specific flag to be set to
* specific value.
*
* Note that this is to be called for the query (not find) calls only.
*
* @return array The query part to be merged into the original part.
*/
protected function additionalQuery() {
return [];
}
/**
* The actual method to call client's search method.
* Returns Result object
*
* @param string $index
* @param string $type if null, then all types will be searched
* @param array $query
* @return Result|Model[]
*/
protected function __query($index, $type = null, array $query = []) {
$result = $this->client->search([
'index' => $index,
'body' => array_merge_recursive($query, $this->additionalQuery())
] + ($type ? ['type' => $type] : []));
return $this->_makeResult($result);
}
/**
* The actual method to call client's get method.
* Returns either a Model object or null on failure.
*
* @param string $index
* @param string $type
* @param sring|int $id
* @return null|Model
*/
protected function __find($index, $type, $id) {
try {
$result = $this->client->get([
'index' => $index,
'type' => $type,
'id' => $id
]);
if ($result['found']) {
return $this->_makeModel($result);
} else {
return null;
}
} catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
return null;
}
}
/**
* The actual method to call client's mget method.
* Returns either a result of Model objects or null on failure.
*
* @param string $index
* @param string $type
* @param sring[]|int[] $ids
* @return null|Model
*/
protected function __mfind($index, $type, $ids) {
try {
$docs = $this->client->mget([
'index' => $index,
'type' => $type,
'body' => [
"ids" => $ids
]
]);
$result = ['ids' => $ids, 'found' => [], 'missed' => [], 'docs' => []];
$missed = [] + $ids;
foreach ($docs['docs'] as $doc) {
if ($doc['found']) {
$result['docs'][] = $doc;
$result['found'][] = $doc['_id'];
unset($missed[array_search($doc['_id'], $missed)]);
}
}
$result['missed'] = $missed;
return $this->_makeMultiGetResult($result);
} catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
return null;
}
}
/**
* Creates a results set for ES query hits
*
* @param array $result
* @return Result
*/
protected function _makeResult(array $result) {
return Result::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern());
}
/**
* Creates a results set for ES query hits
*
* @param array $result
* @return Result
*/
protected function _makeMultiGetResult(array $result) {
return MultiGetResult::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern());
}
/**
* Creates a model object for a specific es result hits entry
*
* @param array $source
* @return Model
*/
protected function _makeModel(array $source) {
return Model::MakeOfType($source, $this->_fullModelClassNamePattern(), $this->getClient());
}
/**
* Returns the full namespace string for the model.
* If the provided namespace contains {type} then use it,
* otherwize add {type} to the end.
*
* @return string
*/
protected function _fullModelClassNamePattern() {
return stripos($this->modelClassNamePattern()? : "", '{type}') !== false ? $this->modelClassNamePattern() : "{$this->modelClassNamePattern()}{type}";
}
public static function __callStatic($name, $arguments) {
if (array_search($name, static::_allowPublicAccess()) !== false) {
//pass specific methods
return call_user_func_array([new static(), $name], $arguments);
}
if (strpos($name, 'get', 0) === 0) {
//pass getAll() as an internal query
return call_user_func_array([new static(), $name], $arguments);
}
trigger_error("Call to undefined static method " . static::class . "::{$name}", E_USER_ERROR);
}
public function __call($name, $arguments) {
if (array_search($name, static::_allowPublicAccess()) !== false) {
//pass specific methods
return call_user_func_array([$this, "_{$name}"], $arguments);
}
if (strpos($name, 'get', 0) === 0) {
//pass getAll() as an internal query
$methodName = lcfirst(substr($name, 3));
return call_user_func_array([$this, "_{$methodName}"], $arguments);
}
trigger_error("Call to undefined method " . static::class . "::{$name}", E_USER_ERROR);
}
/**
* The default values for the client
*
* @return array
*/
protected function defaults() {
return [
'hosts' => [
'http://localhost:9200/'
]
];
}
/**
* Used to expose extra methods to the public static or public calls
*
* Should return an array of strings.
* i.e.
* return ['any','top'];
* Will allow public static and public access to the two new methods:
* protected _any() and protected _top($rows)
*
* Note that the protected methods should be prefixed with _
*
* When overriding in sub classes use this form:
* protected _allowPublicAccess(){
* return array_merge(parent::_allowPublicAccess(), ['method',...,...]);
* }
* This way you will save the allowed methods from the parent.
*
* @return array
*/
protected static function _allowPublicAccess() {
return [
'all',
'query',
'find',
'meta',
'create',
'delete',
'builder',
'metaSettings',
'metaAliases',
'metaMappings',
'metaWarmers'
];
}
/**
* Retreives the meta data of an index
* @param string|array $features a list of meta objects to fetch. null means
* everything. Can be
* * 1 string (i.e. '_settings'),
* * csv (i.e. '_settings,_aliases'),
* * array (i.e. ['_settings','_aliases']
* @param array $options can contain:
* ['ignore_unavailable']
* (bool) Whether specified concrete indices should be ignored
* when unavailable (missing or closed)
* ['allow_no_indices']
* (bool) Whether to ignore if a wildcard indices expression
* resolves into no concrete indices. (This includes `_all`
* string or when no indices have been specified)
* ['expand_wildcards']
* (enum) Whether to expand wildcard expression to concrete
* indices that are open, closed or both.
* ['local']
* (bool) Return local information, do not retrieve the state
* from master node (default: false)
* @return array
*/
protected function _meta($features = null, array $options = []) {
if ($features) {
$features = join(',', array_map(function($item) {
return '_' . strtolower(trim($item, '_'));
}, is_scalar($features) ? explode(",", $features) : $features));
}
$options = ['index' => $this->index()] + $options + ($features ? ['feature' => $features] : []);
$result = $this->client->indices()->get($options);
$result = array_pop($result);
return $result;
}
/**
* Retreives just the settings of the index
* @param array $options check _meta() for details
* @return array
*/
protected function _metaSettings(array $options = []) {
$result = $this->_meta('_settings', $options);
return array_pop($result);
}
/**
* Retreives just the aliases of the index
* @param array $options check _meta() for details
* @return array
*/
protected function _metaAliases(array $options = []) {
$result = $this->_meta('_aliases', $options);
return array_pop($result);
}
/**
* Retreives just the mappings of the index
* @param array $options check _meta() for details
* @return array
*/
protected function _metaMappings(array $options = []) {
$result = $this->_meta('_mappings', $options);
return array_pop($result);
}
/**
* Retreives just the warmers of the index
* @param array $options check _meta() for details
* @return array
*/
protected function _metaWarmers(array $options = []) {
$result = $this->_meta('_warmers', $options);
return array_pop($result);
}
/**
* Creates a builder for this query
*
* @param array $query A query array to start using it
* @return AutoQueryBuilder
*/
protected function _builder(array $query = []) {
return $this->__builder($query);
}
/**
* Creates a builder for this query
*
* @param array $query A query array to start using it
* @return AutoQueryBuilder
*/
protected function __builder(array $query = []) {
return AutoQueryBuilder::makeForQueryInstance($this, $query);
}
}