forked from pdphilip/laravel-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrammar.php
More file actions
1651 lines (1379 loc) · 51.1 KB
/
Copy pathGrammar.php
File metadata and controls
1651 lines (1379 loc) · 51.1 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace PDPhilip\Elasticsearch\Query;
use DateTime;
use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Grammars\Grammar as BaseGrammar;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use InvalidArgumentException;
use PDPhilip\Elasticsearch\Exceptions\BuilderException;
use PDPhilip\Elasticsearch\Query\DSL\DslBuilder;
use PDPhilip\Elasticsearch\Query\DSL\DslFactory;
use PDPhilip\Elasticsearch\Query\DSL\QueryCompiler;
use PDPhilip\Elasticsearch\Utils\Helpers;
class Grammar extends BaseGrammar
{
// ======================================================================
// Create
// ======================================================================
/**
* Compile the given values to an Elasticsearch insert statement
*
* @param Builder $query
*/
public function compileInsert($query, array $values): array
{
$dsl = new DslBuilder;
if (! isset($values[0])) {
$values = [$values];
}
// Process each document to be inserted
foreach ($values as $doc) {
$docId = $doc['_id'] ?? $doc['id'] ?? null;
// Handle child documents
if (isset($doc['child_documents'])) {
foreach ($doc['child_documents'] as $childDoc) {
$childId = $childDoc['id'];
$childOptions = [];
if ($docId) {
$childOptions['parent'] = $docId;
}
$childIndex = DslFactory::indexOperation(
index: $query->getFrom(),
id: $childId,
options: $childOptions
);
$dsl->appendBody($childIndex);
// Add the child document content
$dsl->appendBody($childDoc['document']);
}
// Remove child_documents from the parent document
unset($doc['child_documents']);
}
// Prepare main document operation options
$options = [];
// Handle routing
if (isset($doc['_routing'])) {
$options['routing'] = $doc['_routing'];
unset($doc['_routing']);
} elseif ($routing = $query->getRouting()) {
$options['routing'] = $routing;
}
// Handle parent ID
if ($parentId = $query->getParentId()) {
$options['parent'] = $parentId;
} elseif (isset($doc['_parent'])) {
$options['parent'] = $doc['_parent'];
unset($doc['_parent']);
}
// We don't want to save the ID as part of the doc
// Unless the Model has explicitly set 'storeIdsInDocument'
if ($query->getOption('store_ids_in_document', false)) {
$doc['id'] = $docId;
unset($doc['_id']);
} else {
unset($doc['id'], $doc['_id']);
}
if (! empty($doc['_op_type'])) {
$options['op_type'] = $doc['_op_type'];
unset($doc['_op_type']);
} elseif ($optType = $query->getOption('op_type')) {
$options['op_type'] = $optType;
}
// Add the document operation
$index = DslFactory::indexOperation(
index: $query->getFrom(),
id: $docId,
options: $options
);
$dsl->appendBody($index);
// Process document properties to ensure proper formatting
foreach ($doc as &$property) {
$property = $this->getStringValue($property);
}
// Add the document content
$dsl->appendBody($doc);
}
// Set refresh option
$dsl->setRefresh($query->getOption('refresh', true));
// Return the built DSL
return $dsl->getDsl();
}
// ======================================================================
// Read
// ======================================================================
/**
* @throws BuilderException
*/
public function compileCount($query)
{
$dsl = new DslBuilder;
$dsl->setIndex($query->getFrom());
$compiled = $this->compileWheres($query);
$query = ! empty($compiled['query']) ? $compiled['query'] : DslFactory::matchAll();
$dsl->setBody(['query'], $query);
return $dsl->getDsl();
}
/**
* Compile a select statement
*
* @param Builder $query
*
* @throws BuilderException
*/
public function compileSelect($query): array
{
// Remove parentField on top level query if present
$query->options()->remove('parentField');
$dsl = new DslBuilder;
$dsl->setIndex($query->getFrom());
$compiled = $this->compileWheres($query);
$dsl->setBody(['query'], $compiled['query']);
if ($compiled['filter']) {
if (! $dsl->getBodyValue(['query', 'bool'])) {
$currentQuery = $dsl->getBodyValue(['query']);
$dsl->unsetBody(['query']);
$dsl->setBody(['query', 'bool', 'must'], $currentQuery);
}
$dsl->setBody(['query', 'bool', 'filter'], $compiled['filter']);
}
if ($compiled['postFilter']) {
$dsl->setBody(['post_filter'], $compiled['postFilter']);
}
$compiledOrders = [];
if ($query->orders) {
$compiledOrders = $this->compileOrders($query, $query->orders);
}
if ($query->sorts) {
$compiledOrders = $this->compileSorts($query, $query->sorts, $compiledOrders);
}
if ($compiledOrders) {
$dsl->setBody(['sort'], $compiledOrders);
}
if ($query->highlight) {
$dsl->setBody(['highlight'], $this->compileHighlight($query, $query->highlight));
}
if ($query->offset) {
$dsl->setBody(['from'], $query->offset);
}
$dsl->setBody(['size'], $query->getLimit());
if (isset($query->columns)) {
$dsl->setSource($query->columns);
}
if ($query->bodyParameters) {
foreach ($query->bodyParameters as $name => $parameter) {
$dsl->setBody([$name], $parameter);
}
}
// Distinct and Aggregations
if ($query->distinct) {
if ($query->columns && $query->columns !== ['*'] || $query->metricsAggregations) {
$fields = $query->columns ?? [];
$aggs = [];
foreach ($query->metricsAggregations as $aggregation) {
if (! in_array($aggregation['key'], $fields)) {
$fields[] = $aggregation['key'];
}
$agg = $this->compileAggregation($query, $aggregation);
$aggs[$aggregation['key']] = reset($agg);
$aggs[$aggregation['key']]['key'] = $aggregation['type'].'_'.$aggregation['key'];
}
$dsl->setBody(['aggs'], $this->compileNestedTermAggregations($fields, $query, $aggs));
$dsl->setBody(['size'], $query->getSetLimit() ?? 0);
$dsl->unsetBody(['sort']);
} else {
// else nothing to aggregate - just a normal query as all records will be distinct anyway
$query->distinct = false;
}
}
// Else if we have bucket aggregations
elseif ($query->bucketAggregations) {
$sorts = $dsl->getBodyValue(['sort']);
if ($afterCount = $dsl->getBodyValue(['from'])) {
$dsl->unsetBody(['from']);
// This of course could be a problem if the user is using from for pagination and they go deep
// Leaving it for now
$query->after = $query->getGroupByAfterKey($afterCount);
}
$dsl->setBody(['aggs'], $this->compileBucketAggregations($query, $sorts));
$dsl->setBody(['size'], 0);
// return $dsl->getDsl();
}
// Else if we have metrics aggregations
elseif ($query->metricsAggregations) {
$dsl->setBody(['aggs'], $this->compileMetricAggregations($query));
$dsl->setBody(['size'], 0);
}
if (! $dsl->getBodyValue(['query'])) {
$dsl->unsetBody(['query']);
}
if ($query->pitId) {
$dsl->setBody(['pit', 'id'], $query->pitId);
$dsl->unsetOption(['index']);
$dsl->setBody(['pit', 'keep_alive'], $query->keepAlive);
$dsl->appendOption(['body', 'sort'], DslFactory::sortByShardDoc());
}
if ($query->searchAfter) {
$dsl->setBody(['search_after'], $query->searchAfter);
}
return $dsl->getDsl();
}
/**
* Compile where clauses for a query
*
* @param Builder $query
*/
public function compileWheres($query): array
{
$compiled['query'] = $this->compileQuery($query, $query->wheres);
$compiled['filter'] = $this->compileQuery($query, $query->filters ?? []);
$compiled['postFilter'] = $this->compileQuery($query, $query->postFilters ?? []);
return $compiled;
}
protected function compileQuery(Builder $builder, array $wheres = []): array
{
if (! $wheres) {
return [];
}
$dslCompiler = new QueryCompiler;
foreach ($wheres as $where) {
$isOr = str_starts_with($where['boolean'], 'or');
$isNot = str_ends_with($where['boolean'], 'not');
if (! empty($where['not'])) {
$isNot = true;
}
// Adjust operator to lowercase
if (isset($where['operator'])) {
$where['operator'] = strtolower($where['operator']);
[$operator, $isNegation] = $this->parseNegationOperator($where['operator'], $this->getValueForWhere($builder, $where));
$where['operator'] = $operator;
if ($isNegation) {
$isNot = ! $isNot;
}
}
// Handle column names
if (isset($where['column'])) {
$where['column'] = (string) $where['column'];
// Adjust the column name if necessary
if ($where['column'] === 'id') {
$where['column'] = '_id';
}
// Remove table prefix from column if present
if (Str::startsWith($where['column'], $builder->from.'.')) {
$where['column'] = Str::replaceFirst($builder->from.'.', '', $where['column']);
}
$where['column'] = $this->prependParentField($where['column'], $builder);
}
$method = 'compileWhere'.$where['type'];
$result = $this->{$method}($builder, $where);
$dslCompiler->setResult($result, $isOr, $isNot);
}
return $dslCompiler->compileQuery();
}
// ----------------------------------------------------------------------
// Where Compilers
// ----------------------------------------------------------------------
public function compileWhereMatchAll(): array
{
return DslFactory::matchAll();
}
/**
* Compile a general where clause
*
* @throws BuilderException
*/
protected function compileWhereBasic(Builder $builder, array $where): array
{
$value = $this->getValueForWhere($builder, $where);
$field = $where['column'];
$options = $where['options'] ?? [];
$operatorsMap = [
'>' => 'gt',
'>=' => 'gte',
'<' => 'lt',
'<=' => 'lte',
];
if (is_null($value) || $where['operator'] == 'exists') {
$query = DslFactory::exists($field, $options);
} elseif (in_array($where['operator'], ['like', 'not like'])) {
$field = $this->getIndexableField($field, $builder);
$wildcardValue = str_replace('%', '*', $value);
// Add wildcards to if not present
if (! Str::contains($wildcardValue, '*')) {
$wildcardValue = '*'.$wildcardValue.'*';
}
$query = DslFactory::wildcard($field, $wildcardValue, $options);
} elseif (in_array($where['operator'], array_keys($operatorsMap))) {
$operator = $operatorsMap[$where['operator']];
$field = $this->getIndexableField($field, $builder);
$query = DslFactory::range($field, [$operator => $value], $options);
} else {
$field = $this->getIndexableField($field, $builder);
$query = DslFactory::term($field, $value, $options);
}
return $this->applyOptionsToClause($query, $where);
}
protected function compileWhereMatch(Builder $builder, array $where): array
{
$field = $where['column'];
$values = $this->getValueForWhere($builder, $where);
$options = $where['options'] ?? [];
$options['operator'] = $options['operator'] ?? 'and';
$query = DslFactory::match($field, $values, $options);
return $this->applyOptionsToClause($query, $where);
}
/**
* Compile an in clause
*
* @throws BuilderException
*/
protected function compileWhereIn(Builder $builder, array $where, $not = false): array
{
$field = $this->getIndexableField($where['column'], $builder);
$values = $this->getValueForWhere($builder, $where);
$options = $where['options'] ?? [];
$query = DslFactory::terms($field, $values, $options);
return $this->applyOptionsToClause($query, $where);
}
/**
* Compile a null clause
*
* @throws BuilderException
*/
protected function compileWhereExists(Builder $builder, array $where): array
{
$where['operator'] = '=';
return $this->compileWhereBasic($builder, $where);
}
/**
* Compile a date clause
*
* @throws BuilderException
*/
protected function compileWhereDate(Builder $builder, array $where): array
{
if ($where['operator'] == '=') {
$value = $this->getValueForWhere($builder, $where);
$where['value'] = [$value, $value];
return $this->compileWhereBetween($builder, $where);
}
return $this->compileWhereBasic($builder, $where);
}
/**
* Compile a where between clause
*/
protected function compileWhereBetween(Builder $builder, array $where): array
{
$column = $where['column'];
$values = $this->getValueForWhere($builder, $where);
$options = $where['options'] ?? [];
$conditions = [
'gte' => $values[0],
'lte' => $values[1],
];
return DslFactory::range($column, $conditions, $options);
}
/**
* Compile where for function score
*/
protected function compileWhereFunctionScore(Builder $builder, array $where): array
{
$compiled = $this->compileWheres($where['query']);
foreach ($compiled as $queryPart => $clauses) {
$compiled[$queryPart] = array_map(function ($clause) use ($where) {
if ($clause) {
$this->applyOptionsToClause($clause, $where);
}
return $clause;
}, $clauses);
}
$compiled = array_filter($compiled);
$functionType = $where['functionType'];
$functionOptions = $where['options'];
return DslFactory::functionScore($compiled['query'], $functionType, $functionOptions);
}
/**
* Compile a geo distance clause
*
* @param Builder $builder
* @param array $where
*/
protected function compileWhereGeoDistance($builder, $where): array
{
$options = $where['options'] ?? [];
return DslFactory::geoDistance($where['column'], $where['distance'], $where['location'], $options);
}
/**
* Compile a where geo bounds clause
*/
protected function compileWhereGeoBox(Builder $builder, array $where): array
{
$options = $where['options'] ?? [];
return DslFactory::geoBoundingBox($where['column'], $where['bounds'], $options);
}
/**
* Compile a nested clause
*/
protected function compileWhereNested(Builder $builder, array $where): array
{
$compiled = $this->compileWheres($where['query']);
foreach ($compiled as $queryPart => $clauses) {
$compiled[$queryPart] = array_map(function ($clause) use ($where) {
if ($clause) {
$this->applyOptionsToClause($clause, $where);
}
return $clause;
}, $clauses);
}
$compiled = array_filter($compiled);
return reset($compiled);
}
/**
* Compile a where nested clause
*
* @param array $where
*/
protected function compileWhereNestedObject(Builder $builder, $where): array
{
// Compile the inner query
$wheres = $this->compileWheres($where['query']);
$path = $where['column'];
if (! $wheres['query']) {
$wheres['query'] = DslFactory::exists($path);
}
$options = $where['options'] ?? [];
$wheres = array_filter($wheres);
$query = DslFactory::nested($path, $wheres, $options);
return $this->applyOptionsToClause($query, $where);
}
public function _buildInnerHits($innerQuery)
{
$innerHits = [];
$compiledOrders = [];
if ($innerQuery->orders) {
$compiledOrders = $this->compileOrders($innerQuery, $innerQuery->orders);
}
if ($innerQuery->sorts) {
$compiledOrders = $this->compileSorts($innerQuery, $innerQuery->sorts, $compiledOrders);
}
if ($compiledOrders) {
$innerHits['sort'] = $compiledOrders;
}
if ($innerQuery->offset) {
$innerHits['from'] = $innerQuery->offset;
}
if ($size = $innerQuery->getSetLimit()) {
$innerHits['size'] = $size;
}
return $innerHits;
}
/**
* Compile a where nested clause
*
* @param array $where
*/
protected function compileWhereInnerNested(Builder $builder, $where): array
{
// Compile the inner filter
$innerQuery = $where['query'];
$query = $this->compileWheres($innerQuery);
$innerHits = $this->_buildInnerHits($innerQuery);
return DslFactory::innerNested($where['column'], $query['query'], $innerHits);
}
/**
* Compile a parent clause
*/
protected function compileWhereParent(Builder $builder, array $where): array
{
return $this->applyWhereRelationship($builder, $where, 'parent');
}
/**
* @return array
*/
protected function compileWhereParentId(Builder $builder, array $where)
{
$type = $where['relationType'];
$id = $where['id'];
$options = $where['options'] ?? [];
return DslFactory::parentId($type, $id, $options);
}
/**
* @throws BuilderException
*/
protected function compileWherePrefix(Builder $builder, array $where): array
{
$field = $this->getIndexableField($where['column'], $builder);
$value = $where['value'];
$options = $where['options'] ?? [];
return DslFactory::prefix($field, $value, $options);
}
protected function compileWhereRaw(Builder $builder, array $where): array
{
return $where['sql']; // Return the raw query as-is
}
/**
* Compile a date clause
*
* @throws BuilderException
*/
protected function compileWhereRegex(Builder $builder, array $where): array
{
// Define the allowed options for regex queries
// TODO: Catch this upfront in the builder
$allowedArgs = [
'flags',
'case_insensitive',
'max_determinized_states',
'rewrite',
];
$options = $this->getAllowedOptions($where['options'] ?? [], $allowedArgs);
$field = $this->getIndexableField($where['column'], $builder);
$value = Helpers::escape($where['value']);
return DslFactory::regexp($field, $value, $options);
}
/**
* Compile a match_phrase clause
*/
protected function compileWherePhrase(Builder $builder, array $where): array
{
$field = $where['column'];
$value = $where['value'];
$options = $where['options'] ?? [];
return DslFactory::matchPhrase($field, $value, $options);
}
/**
* Compile a match_phrase clause
*/
protected function compileWherePhrasePrefix(Builder $builder, array $where): array
{
$field = $where['column'];
$value = $where['value'];
$options = $where['options'] ?? [];
return DslFactory::matchPhrasePrefix($field, $value, $options);
}
/**
* Compile a term fuzzy clause
*/
protected function compileWhereFuzzy(Builder $builder, array $where): array
{
$field = $where['column'];
$value = $where['value'];
$options = $where['options'] ?? [];
return DslFactory::fuzzy($field, $value, $options);
}
/**
* Compile a term clause
*
* @throws BuilderException
*/
protected function compileWhereTerm(Builder $builder, array $where): array
{
$field = $this->getIndexableField($where['column'], $builder);
$value = $where['value'];
$options = $where['options'] ?? [];
return DslFactory::term($field, $value, $options);
}
/**
* Compile a script clause
*/
protected function compileWhereScript(Builder $builder, array $where): array
{
$source = $where['script'];
$options = $where['options'] ?? [];
return DslFactory::script($source, $options);
}
/**
* Compile a search clause for Elasticsearch.
*/
protected function compileWhereSearch(Builder $builder, array $where): array
{
$value = $where['value'];
$options = $where['options'] ?? [];
$constantScore = false;
if (isset($options['constant_score'])) {
$constantScore = $options['constant_score'];
unset($options['constant_score']);
}
$query = DslFactory::multiMatch($value, $options);
if ($constantScore) {
return DslFactory::constantScore($query);
}
return $query;
}
/**
* Compile a child clause
*/
protected function compileWhereChild(Builder $builder, array $where): array
{
return $this->applyWhereRelationship($builder, $where, 'child');
}
/**
* Compile a relationship clause
*/
protected function applyWhereRelationship(Builder $builder, array $where, string $relationship): array
{
$compiled = $this->compileWheres($where['value']);
$relationshipFilter = "has_{$relationship}";
$type = $relationship === 'parent' ? 'parent_type' : 'type';
// pass filter to query if empty allowing a filter interface to be used in relation query
// otherwise match all in relation query
if (empty($compiled['query'])) {
$compiled['query'] = empty($compiled['filter']) ? ['match_all' => (object) []] : $compiled['filter'];
} elseif (! empty($compiled['filter'])) {
throw new InvalidArgumentException('Cannot use both filter and query contexts within a relation context');
}
$query = [
$relationshipFilter => [
$type => $where['documentType'],
'query' => $compiled['query'],
],
];
return $this->applyOptionsToClause($query, $where);
}
// ----------------------------------------------------------------------
// Order and Highlight
// ----------------------------------------------------------------------
/**
* Compile the orders section of a query
*
* @param array $orders
*
* @throws BuilderException
*/
protected function compileOrders(Builder|BaseBuilder $builder, $orders = []): array
{
$compiledOrders = [];
foreach ($orders as $order) {
$column = $order['column'];
if (Str::startsWith($column, $builder->from.'.')) {
$column = Str::replaceFirst($builder->from.'.', '', $column);
}
$column = $this->prependParentField($column, $builder);
$column = $this->getIndexableField($column, $builder);
$type = $order['type'] ?? 'basic';
switch ($type) {
case 'geoDistance':
$orderSettings = [
$column => $order['options']['coordinates'],
'order' => $order['direction'] < 0 ? 'desc' : 'asc',
];
if (! empty($order['options']['unit'])) {
$orderSettings['unit'] = $order['options']['unit'];
}
if (! empty($order['options']['mode'])) {
$orderSettings['mode'] = $order['options']['mode'];
}
if (! empty($order['options']['distance_type'])) {
$orderSettings['distance_type'] = $order['options']['distance_type'];
}
$column = '_geo_distance';
break;
default:
$orderSettings = [
'order' => $order['direction'] < 0 ? 'desc' : 'asc',
];
$allowedOptions = ['missing', 'mode', 'nested'];
$options = isset($order['options']) ? array_intersect_key($order['options'], array_flip($allowedOptions)) : [];
$orderSettings = array_merge($options, $orderSettings);
}
$compiledOrders[] = [
$column => $orderSettings,
];
}
return $compiledOrders;
}
/**
* @throws BuilderException
*/
protected function compileSorts(Builder $builder, $sorts, $compiledOrders): array
{
foreach ($sorts as $column => $sort) {
$found = false;
$column = $this->prependParentField($column, $builder);
$column = $this->getIndexableField($column, $builder);
if ($compiledOrders) {
foreach ($compiledOrders as $i => $compiledOrder) {
if (array_key_exists($column, $compiledOrder)) {
$compiledOrders[$i][$column] = array_merge($compiledOrder[$column], $sort);
$found = true;
break;
}
}
}
if (! $found) {
$compiledOrders[] = [$column => $sort];
}
}
return $compiledOrders;
}
/**
* Compile the highlight section of a query
*
* @param array $highlight
*/
protected function compileHighlight(Builder $builder, mixed $highlight = []): array
{
$allowedArgs = [
'boundary_chars',
'boundary_max_scan',
'boundary_scanner',
'boundary_scanner_locale',
'encoder',
'fragmenter',
'force_source',
'fragment_offset',
'fragment_size',
'highlight_query',
'matched_fields',
'number_of_fragments',
];
$compiledHighlights = $this->getAllowedOptions($highlight['options'], $allowedArgs);
foreach ($highlight['column'] as $column => $value) {
if (is_array($value)) {
$compiledHighlights['fields'][] = [$column => $value];
} elseif ($value != '*') {
$compiledHighlights['fields'][] = [$value => (object) []];
} else {
$compiledHighlights['fields'][] = ['*' => (object) []];
}
}
$compiledHighlights['pre_tags'] = $highlight['preTag'];
$compiledHighlights['post_tags'] = $highlight['postTag'];
return $compiledHighlights;
}
// ======================================================================
// Aggregations
// ======================================================================
/**
* @throws BuilderException
*/
protected function compileNestedTermAggregations($fields, Builder $query, $aggs = []): array
{
// Get the current field to process
$currentField = array_shift($fields);
$field = $this->getIndexableField($currentField, $query);
$metricAggs = [];
if (! empty($aggs[$currentField])) {
$key = $aggs[$currentField]['key'];
$metricAgg = $aggs[$currentField];
unset($metricAgg['key']);
$metricAggs[$key] = $metricAgg;
}
// Prepare sorting
$sorts = $query->sorts;
$orders = collect($query->orders);
$termsOrders = [];
// Add count-based sorting if specified
if (isset($sorts['_count'])) {
$termsOrders[] = $sorts['_count'] == 1 ? ['_count' => 'asc'] : ['_count' => 'desc'];
}
// Add field-based sorting if specified
$fieldOrder = $orders->where('column', $currentField)->first();
if ($fieldOrder) {
$termsOrders[] = $fieldOrder['direction'] == 1 ? ['_key' => 'asc'] : ['_key' => 'desc'];
}
// Process nested fields recursively
$subAggs = [];
if (! empty($fields)) {
$subAggs = $this->compileNestedTermAggregations($fields, $query, $aggs);
}
return DslFactory::nestedTermsAggregation(
fieldName: $currentField,
field: $field,
size: $query->getLimit(),
orders: $termsOrders,
metricAggs: $metricAggs,
subAggs: $subAggs
);
}
/**
* Compile all aggregations
*/
protected function compileBucketAggregations(Builder $builder, $sorts = null): array
{
$aggregations = collect();
$metricsAggregations = [];
if ($builder->metricsAggregations) {
$metricsAggregations = $this->compileMetricAggregations($builder);
}
// Process each bucket aggregation
foreach ($builder->bucketAggregations as $aggregation) {
// Apply metric aggregations inside the bucket if they exist
if (! empty($metricsAggregations)) {
$aggregation['aggregations'] = $builder->newQuery();
// @phpstan-ignore-next-line
$aggregation['aggregations']->metricsAggregations = $builder->metricsAggregations;
}
$result = $this->compileAggregation($builder, $aggregation);
$aggregations = $aggregations->mergeRecursive($result);
}
if ($sorts) {
$aggregations = collect(DslFactory::applySortsToAggregations($aggregations->all(), $sorts));
}
return $aggregations->all();
}
/**
* Compile all aggregations
*/
protected function compileMetricAggregations(Builder $builder): array
{
$aggregations = [];
foreach ($builder->metricsAggregations as $aggregation) {
$result = $this->compileAggregation($builder, $aggregation);
$aggregations = array_merge_recursive($aggregations, $result);
}
return $aggregations;
}
/**
* Compile a single aggregation
*/
protected function compileAggregation(Builder $builder, array $aggregation): array
{
$key = $aggregation['key'];
$method = 'compile'.ucfirst(Str::camel($aggregation['type'])).'Aggregation';
$compiledPayload = $this->$method($builder, $aggregation);
$compiled = [$key => $compiledPayload];
if (isset($aggregation['aggregations']) && $aggregation['aggregations']->metricsAggregations) {