This repository has been archived by the owner on Jul 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ElasticActiveDataProvider.php
221 lines (203 loc) · 6.92 KB
/
ElasticActiveDataProvider.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
<?php
/**
* Class ElasticActiveDataProvider
*/
class ElasticActiveDataProvider extends CActiveDataProvider
{
/** @var mixed|CActiveRecord */
public $model;
public $scores = [];
protected $criteria;
protected $countCriteria;
protected $objectHash;
public function __construct($modelClass, $config = [])
{
parent::__construct($modelClass, $config);
$this->objectHash = spl_object_hash($this);
}
/**
* @param mixed $className Really a string, defined as mixed only for the IDE not to display errors
* @return CActiveRecord
*/
protected function getModel($className)
{
return $className::model();
}
/**
* @return CActiveRecord[]
*/
protected function fetchData()
{
$pkAlias = "{$this->model->tableAlias}.{$this->model->tableSchema->primaryKey}";
$keys = $this->fetchKeys();
$implodedKeys = implode(',', $keys);
$criteria = new CDbCriteria([
'condition' => "{$pkAlias} in ($implodedKeys)",
'order' => "field({$pkAlias}, {$implodedKeys})",
'limit' => 5000,
]);
!empty($this->model->elastic_findcriteria) && $criteria->mergeWith($this->model->elastic_findcriteria);
return empty($keys) ? [] : $this->model->findAll($criteria);
}
/**
* @return array
*/
protected function fetchKeys()
{
return $this->memoize('fetchKeys', function () {
$keys = [];
foreach ($this->getResultSet(false)->getResults() as $result) {
$keys[] = $result->getData()['id'];
$this->scores[$result->getData()['id']] = $result->getScore();
}
return $keys;
});
}
public function memoize(string $id, callable $callable)
{
static $cache = [];
if (!isset($cache[$this->objectHash])) {
$cache[$this->objectHash] = [];
}
return $cache[$this->objectHash][$id] ?? $cache[$this->objectHash][$id] = $callable();
}
/**
* @param bool $count whether the count or results \Elastica\ResultSet should be returned
* @return \Elastica\ResultSet
*/
public function getResultSet($count = false)
{
return $this->memoize("getResultSet-{$count}", function () use ($count) {
$search = new Elastica\Search($this->model->getElasticDbConnection());
return $search
->addIndex($this->model->getElasticIndex())
->addType($this->model->getElasticType())
->setQuery($this->getQuery($count))->search();
});
}
/**
* @param bool $count whether the count or results criteria should be returned
* @return \Elastica\Query
*/
public function getQuery($count = false)
{
return $this->memoize("getResultSet-{$count}", function () use ($count) {
$criteria = $count ? $this->getCountCriteria() : $this->getCriteria();
empty($criteria['query']) && $criteria['query'] = null;
$sort = $this->getSortCriteria();
if (!empty($criteria['order'])) {
$sort = $criteria['order'];
unset($criteria['order']);
}
if (!$count) {
$opts['sort'] = $sort;
if (($pagination = $this->getPagination()) !== false) {
$pagination->setItemCount($this->getTotalItemCount());
$pagination->getOffset() && $opts['from'] = $pagination->getOffset();
$pagination->getLimit() && $opts['size'] = $pagination->getLimit();
}
$criteria = $opts + $criteria;
}
return new Elastica\Query($criteria);
});
}
/**
* @return array
*/
public function getCountCriteria()
{
return $this->countCriteria ?: $this->criteria;
}
/**
* @param array $value
*/
public function setCountCriteria($value)
{
$this->countCriteria = $value;
}
/**
* @return array
*/
public function getCriteria()
{
return $this->criteria;
}
/**
* @param array $value
*/
public function setCriteria($value)
{
$this->criteria = $value;
}
/**
* @return array
*/
public function getSortCriteria()
{
return $this->memoize('getSortCriteria', function () {
$ret = [];
if (($sort = $this->getSort()) !== false) {
$directions = $sort->getDirections();
if (empty($directions)) {
if (is_string($sort->defaultOrder)) {
$ret[] = $this->parseOrderBy($sort->defaultOrder);
}
} else {
foreach ($directions as $attribute => $descending) {
$definition = $sort->resolveAttribute($attribute);
if (is_array($definition)) {
if ($descending) {
$ret[] = isset($definition['desc'])
? (is_array($definition['desc'])
? $definition['desc']
: $this->parseOrderBy($definition['desc'])
)
: [$attribute => 'desc'];
} else {
$ret[] = isset($definition['asc'])
? (is_array($definition['asc'])
? $definition['asc']
: $this->parseOrderBy($definition['asc'])
)
: [$attribute => 'asc'];
}
} else if ($definition !== false) {
$attribute = $definition;
$ret[] = [$attribute => $descending ? 'desc' : 'asc'];
}
}
}
}
$sort = [];
foreach ($ret as $r) {
!empty($r) && $sort[] = $r;
}
return CMap::mergeArray($sort, ['_score']);
});
}
/**
* @param $str
* @return array
*/
public function parseOrderBy($str)
{
$matches = [];
preg_match('/^\s*(\w+)[\s.]+(\w+)/', $str, $matches);
$order = [];
if (!empty($matches)) {
$order = !empty($matches[1]) ? [$matches[1] => (!empty($matches[2]) ? $matches[2] : 'asc')] : [];
} else if (is_string($str)) {
$order = [$str => 'asc'];
}
return $order;
}
/**
* @return int
*/
protected function calculateTotalItemCount()
{
return $this->memoize('calculateTotalItemCount', function () {
return $this->getResultSet(true)->getTotalHits();
});
}
}