Query   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 5
dl 0
loc 55
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B multiSearch() 0 31 6
1
<?php
2
/**
3
 *
4
 * @author Mihkel Viilveer <[email protected]>
5
 * @date 2.09.2014
6
 */
7
8
namespace opus\elastic\components;
9
10
use yii\base\InvalidParamException;
11
use yii\elasticsearch\Exception;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Json;
14
15
/**
16
 * Class Query
17
 *
18
 * @author Mihkel Viilveer <[email protected]>
19
 * @package opus\elastic\components
20
 * @property \opus\elastic\elastica\filter\BoolQuery $filter
21
 */
22
class Query extends \yii\elasticsearch\Query
23
{
24
    /**
25
     * @var array|string|\opus\elastic\elastica\filter\BoolQuery The filter part of this search query. This is an array or json string that follows the format of
26
     * the elasticsearch [Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html).
27
     */
28
    public $filter;
29
30
    /**
31
     * @var array|string|\Elastica\Query\Bool The query part of this search query. This is an array or json string that follows the format of
32
     * the elasticsearch [Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html).
33
     */
34
    public $query;
35
36
    /**
37
     * Creates multi search request to elasticsearch
38
     *
39
     * @param array $requests
40
     * @param null $searchType
41
     * @param array $options
42
     * @throws Exception
43
     * @return mixed
44
     */
45
    public static function multiSearch(
46
        array $requests,
47
        $searchType = null,
48
        $options = []
49
    ) {
50
        if (empty($requests)) {
51
            throw new InvalidParamException('Cannot create empty request');
52
        }
53
        $requestParts = [];
54
        foreach ($requests as $request) {
55
            $requestParts[] = Json::encode(
56
                [
57
                    'index' => $request['index'],
58
                    'type' => $request['type'],
59
                    'search_type' => $searchType ?: 'query_then_fetch'
60
                ]
61
            );
62
            $requestParts[] = Json::encode($request['query']);
63
        }
64
        $query = implode("\n", $requestParts) . "\n";
65
66
        $result = \Yii::$app->elasticsearch->get('_msearch', $options, $query);
67
68
        foreach ($result['responses'] as $set) {
69
            if (($error = ArrayHelper::getValue($set, 'error')) !== null) {
70
                throw new Exception($error);
71
            }
72
        }
73
74
        return $result;
75
    }
76
}