Completed
Push — master ( 68e6db...837b11 )
by Nicolas
03:15 queued 12s
created

Query::setTrackTotalHits()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Elastica;
4
5
use Elastica\Aggregation\AbstractAggregation;
6
use Elastica\Exception\InvalidException;
7
use Elastica\Query\AbstractQuery;
8
use Elastica\Query\MatchAll;
9
use Elastica\Query\QueryString;
10
use Elastica\Script\AbstractScript;
11
use Elastica\Script\ScriptFields;
12
use Elastica\Suggest\AbstractSuggest;
13
14
/**
15
 * Elastica query object.
16
 *
17
 * Creates different types of queries
18
 *
19
 * @author Nicolas Ruflin <[email protected]>
20
 *
21
 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html
22
 */
23
class Query extends Param
24
{
25
    /**
26
     * Suggest query or not.
27
     *
28
     * @var int Suggest
29
     */
30
    protected $_suggest = 0;
31
32
    /**
33
     * Creates a query object.
34
     *
35
     * @param array|\Elastica\Query\AbstractQuery $query OPTIONAL Query object (default = null)
36
     */
37
    public function __construct($query = null)
38
    {
39
        if (\is_array($query)) {
40
            $this->setRawQuery($query);
41
        } elseif ($query instanceof AbstractQuery) {
42
            $this->setQuery($query);
43
        } elseif ($query instanceof Suggest) {
44
            $this->setSuggest($query);
45
        } elseif ($query instanceof Collapse) {
46
            $this->setCollapse($query);
47
        }
48
    }
49
50
    /**
51
     * Transforms the argument to a query object.
52
     *
53
     * For example, an empty argument will return a \Elastica\Query with a \Elastica\Query\MatchAll.
54
     *
55
     * @param mixed $query
56
     *
57
     * @throws InvalidException For an invalid argument
58
     *
59
     * @return self
60
     */
61
    public static function create($query)
62
    {
63
        switch (true) {
64
            case $query instanceof self:
65
                return $query;
66
            case $query instanceof AbstractQuery:
67
                return new self($query);
68
            case empty($query):
69
                return new self(new MatchAll());
70
            case \is_array($query):
71
                return new self($query);
72
            case \is_string($query):
73
                return new self(new QueryString($query));
74
            case $query instanceof AbstractSuggest:
75
                return new self(new Suggest($query));
0 ignored issues
show
Documentation introduced by
new \Elastica\Suggest($query) is of type object<Elastica\Suggest>, but the function expects a array|object<Elastica\Query\AbstractQuery>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
77
            case $query instanceof Suggest:
78
                return new self($query);
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Suggest>, but the function expects a array|object<Elastica\Query\AbstractQuery>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
79
80
            case $query instanceof Collapse:
81
                return new self($query);
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Collapse>, but the function expects a array|object<Elastica\Query\AbstractQuery>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
82
        }
83
84
        throw new InvalidException('Unexpected argument to create a query for.');
85
    }
86
87
    /**
88
     * Sets query as raw array. Will overwrite all already set arguments.
89
     *
90
     * @param array $query Query array
91
     *
92
     * @return $this
93
     */
94
    public function setRawQuery(array $query)
95
    {
96
        $this->_params = $query;
97
98
        return $this;
99
    }
100
101
    /**
102
     * Sets the query.
103
     *
104
     * @param \Elastica\Query\AbstractQuery $query Query object
105
     *
106
     * @return $this
107
     */
108
    public function setQuery(AbstractQuery $query)
109
    {
110
        return $this->setParam('query', $query);
111
    }
112
113
    /**
114
     * Gets the query object.
115
     *
116
     * @return array|\Elastica\Query\AbstractQuery
117
     **/
118
    public function getQuery()
119
    {
120
        return $this->getParam('query');
121
    }
122
123
    /**
124
     * Sets the start from which the search results should be returned.
125
     *
126
     * @param int $from
127
     *
128
     * @return $this
129
     */
130
    public function setFrom($from)
131
    {
132
        return $this->setParam('from', $from);
133
    }
134
135
    /**
136
     * Sets sort arguments for the query
137
     * Replaces existing values.
138
     *
139
     * @param array $sortArgs Sorting arguments
140
     *
141
     * @return $this
142
     *
143
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html
144
     */
145
    public function setSort(array $sortArgs)
146
    {
147
        return $this->setParam('sort', $sortArgs);
148
    }
149
150
    /**
151
     * Adds a sort param to the query.
152
     *
153
     * @param mixed $sort Sort parameter
154
     *
155
     * @return $this
156
     *
157
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html
158
     */
159
    public function addSort($sort)
160
    {
161
        return $this->addParam('sort', $sort);
162
    }
163
164
    /**
165
     * Keep track of the scores when sorting results.
166
     *
167
     * @param bool $trackScores
168
     *
169
     * @return $this
170
     *
171
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_track_scores
172
     */
173
    public function setTrackScores($trackScores = true): self
174
    {
175
        return $this->setParam('track_scores', (bool) $trackScores);
176
    }
177
178
    /**
179
     * Sets highlight arguments for the query.
180
     *
181
     * @param array $highlightArgs Set all highlight arguments
182
     *
183
     * @return $this
184
     *
185
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html
186
     */
187
    public function setHighlight(array $highlightArgs)
188
    {
189
        return $this->setParam('highlight', $highlightArgs);
190
    }
191
192
    /**
193
     * Adds a highlight argument.
194
     *
195
     * @param mixed $highlight Add highlight argument
196
     *
197
     * @return $this
198
     *
199
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html
200
     */
201
    public function addHighlight($highlight)
202
    {
203
        return $this->addParam('highlight', $highlight);
204
    }
205
206
    /**
207
     * Sets maximum number of results for this query.
208
     *
209
     * @param int $size OPTIONAL Maximal number of results for query (default = 10)
210
     *
211
     * @return $this
212
     */
213
    public function setSize($size = 10)
214
    {
215
        return $this->setParam('size', $size);
216
    }
217
218
    /**
219
     * Enables explain on the query.
220
     *
221
     * @param bool $explain OPTIONAL Enabled or disable explain (default = true)
222
     *
223
     * @return $this
224
     *
225
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-explain.html
226
     */
227
    public function setExplain($explain = true)
228
    {
229
        return $this->setParam('explain', $explain);
230
    }
231
232
    /**
233
     * Enables version on the query.
234
     *
235
     * @param bool $version OPTIONAL Enabled or disable version (default = true)
236
     *
237
     * @return $this
238
     *
239
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-version.html
240
     */
241
    public function setVersion($version = true)
242
    {
243
        return $this->setParam('version', $version);
244
    }
245
246
    /**
247
     * Sets the fields to be returned by the search
248
     * NOTICE php will encode modified(or named keys) array into object format in json format request
249
     * so the fields array must a sequence(list) type of array.
250
     *
251
     * @param array $fields Fields to be returned
252
     *
253
     * @return $this
254
     *
255
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-fields.html
256
     */
257
    public function setStoredFields(array $fields)
258
    {
259
        return $this->setParam('stored_fields', $fields);
260
    }
261
262
    /**
263
     * Sets the fields not stored to be returned by the search.
264
     *
265
     * @param array $fieldDataFields Fields not stored to be returned
266
     *
267
     * @return $this
268
     *
269
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-fielddata-fields.html
270
     */
271
    public function setFieldDataFields(array $fieldDataFields)
272
    {
273
        return $this->setParam('docvalue_fields', $fieldDataFields);
274
    }
275
276
    /**
277
     * Set script fields.
278
     *
279
     * @param array|\Elastica\Script\ScriptFields $scriptFields Script fields
280
     *
281
     * @return $this
282
     *
283
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html
284
     */
285
    public function setScriptFields($scriptFields)
286
    {
287
        if (\is_array($scriptFields)) {
288
            $scriptFields = new ScriptFields($scriptFields);
289
        }
290
291
        return $this->setParam('script_fields', $scriptFields);
292
    }
293
294
    /**
295
     * Adds a Script to the query.
296
     *
297
     * @param string                          $name
298
     * @param \Elastica\Script\AbstractScript $script Script object
299
     *
300
     * @return $this
301
     */
302
    public function addScriptField($name, AbstractScript $script)
303
    {
304
        if (isset($this->_params['script_fields'])) {
305
            $this->_params['script_fields']->addScript($name, $script);
306
        } else {
307
            $this->setScriptFields([$name => $script]);
308
        }
309
310
        return $this;
311
    }
312
313
    /**
314
     * Adds an Aggregation to the query.
315
     *
316
     * @param AbstractAggregation $agg
317
     *
318
     * @return $this
319
     */
320
    public function addAggregation(AbstractAggregation $agg)
321
    {
322
        $this->_params['aggs'][] = $agg;
323
324
        return $this;
325
    }
326
327
    /**
328
     * Converts all query params to an array.
329
     *
330
     * @return array Query array
331
     */
332
    public function toArray()
333
    {
334
        if (!isset($this->_params['query']) && (0 == $this->_suggest)) {
335
            $this->setQuery(new MatchAll());
336
        }
337
338
        if (isset($this->_params['post_filter']) && 0 === \count(($this->_params['post_filter'])->toArray())) {
339
            unset($this->_params['post_filter']);
340
        }
341
342
        $array = $this->_convertArrayable($this->_params);
343
344
        if (isset($array['suggest'])) {
345
            $array['suggest'] = $array['suggest']['suggest'];
346
        }
347
348
        return $array;
349
    }
350
351
    /**
352
     * Allows filtering of documents based on a minimum score.
353
     *
354
     * @param float $minScore Minimum score to filter documents by
355
     *
356
     * @throws \Elastica\Exception\InvalidException
357
     *
358
     * @return $this
359
     */
360
    public function setMinScore($minScore)
361
    {
362
        if (!\is_numeric($minScore)) {
363
            throw new InvalidException('has to be numeric param');
364
        }
365
366
        return $this->setParam('min_score', $minScore);
367
    }
368
369
    /**
370
     * Add a suggest term.
371
     *
372
     * @param \Elastica\Suggest $suggest suggestion object
373
     *
374
     * @return $this
375
     */
376
    public function setSuggest(Suggest $suggest)
377
    {
378
        $this->setParam('suggest', $suggest);
379
380
        $this->_suggest = 1;
381
382
        return $this;
383
    }
384
385
    /**
386
     * Add a Rescore.
387
     *
388
     * @param mixed $rescore suggestion object
389
     *
390
     * @return $this
391
     */
392
    public function setRescore($rescore)
393
    {
394
        if (\is_array($rescore)) {
395
            $buffer = [];
396
397
            foreach ($rescore as $rescoreQuery) {
398
                $buffer[] = $rescoreQuery;
399
            }
400
        } else {
401
            $buffer = $rescore;
402
        }
403
404
        return $this->setParam('rescore', $buffer);
405
    }
406
407
    /**
408
     * Sets the _source field to be returned with every hit.
409
     *
410
     * @param array|bool $params Fields to be returned or false to disable source
411
     *
412
     * @return $this
413
     *
414
     * @see   https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html
415
     */
416
    public function setSource($params)
417
    {
418
        return $this->setParam('_source', $params);
419
    }
420
421
    /**
422
     * Sets post_filter argument for the query. The filter is applied after the query has executed.
423
     *
424
     * @param array|\Elastica\Query\AbstractQuery $filter
425
     *
426
     * @return $this
427
     *
428
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-post-filter.html
429
     */
430
    public function setPostFilter(AbstractQuery $filter)
431
    {
432
        return $this->setParam('post_filter', $filter);
433
    }
434
435
    /**
436
     * @param Collapse $collapse
437
     *
438
     * @return $this
439
     */
440
    public function setCollapse(Collapse $collapse): self
441
    {
442
        return $this->setParam('collapse', $collapse);
443
    }
444
445
    /**
446
     * Adds a track_total_hits argument.
447
     *
448
     * @param bool|int $trackTotalHits OPTIONAL Track total hits parameter (default = true)
449
     *
450
     * @return $this
451
     *
452
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-track-total-hits
453
     */
454
    public function setTrackTotalHits($trackTotalHits = true)
455
    {
456
        return $this->setParam('track_total_hits', $trackTotalHits);
457
    }
458
}
459