-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathSearchAPISearch.php
More file actions
366 lines (307 loc) · 10.4 KB
/
SearchAPISearch.php
File metadata and controls
366 lines (307 loc) · 10.4 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
<?php
namespace Drupal\graphql_search_api\Plugin\GraphQL\Fields;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\graphql\GraphQL\Cache\CacheableValue;
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
use Drupal\graphql\GraphQL\Execution\ResolveContext;
use GraphQL\Type\Definition\ResolveInfo;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* A query field that wraps a Search API query.
*
* @GraphQLField(
* secure = true,
* id = "search_api_search",
* type = "SearchAPIResult",
* name = "searchAPISearch",
* nullable = true,
* multi = false,
* arguments = {
* "index_id" = "String!",
* "fulltext" = "FulltextInput",
* "language" = "[String]",
* "condition_group" = "ConditionGroupInput",
* "conditions" = "[ConditionInput]",
* "range" = "RangeInput",
* "sort" = "[SortInput]",
* "facets" = "[FacetInput]",
* "more_like_this" = "MLTInput",
* "solr_params" = "[SolrParameterInput]",
* },
* )
*/
class SearchAPISearch extends FieldPluginBase implements ContainerFactoryPluginInterface {
/**
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $logger;
private $query;
private $index;
/**
* {@inheritDoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, LoggerChannelFactoryInterface $logger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('logger.factory')
);
}
/**
* {@inheritdoc}
*/
public function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
// Load up the index passed in argument.
$this->index = $this->entityTypeManager->getStorage('search_api_index')->load($args['index_id']);
// Prepare the query with our arguments.
$this->prepareSearchQuery($args);
// Execute search.
try {
$results = $this->query->execute();
}
// Handle error, check exception type -> SearchApiException ?
catch (\Exception $exception) {
$this->logger->get('graphql_search_api')->error($exception->getMessage());
}
// Get search response from results.
$search_response = $this->getSearchResponse($results);
// Add the result count to the response.
$search_response['result_count'] = $results->getResultCount();
// Set response type.
$search_response['type'] = 'SearchAPIResult';
yield $search_response;
}
/**
* {@inheritdoc}
*/
protected function getCacheDependencies(array $result, $value, array $args, ResolveContext $context, ResolveInfo $info) {
$metadata = new CacheableMetadata();
$metadata->addCacheTags(['search_api_list:' . $this->index->id()]);
return [$metadata];
}
/**
* Adds conditions to the Search API query.
*
* @conditions
* The conditions to be added.
*/
private function addConditions($conditions) {
// Loop through conditions to add them into the query.
foreach ($conditions as $condition) {
if (empty($condition['operator'])) {
$condition['operator'] = '=';
}
if ($condition['value'] == 'NULL') {
$condition['value'] = NULL;
}
// Set the condition in the query.
$this->query->addCondition($condition['name'], $condition['value'], $condition['operator']);
}
}
/**
* Adds a condition group to the Search API query.
*
* @condition_group
* The conditions to be added.
*/
private function addConditionGroup($condition_group_arg) {
if(empty($condition_group_arg['groups'])) {
return;
}
// Loop through the groups in the args.
foreach ($condition_group_arg['groups'] as $group) {
// Set default conjunction and tags.
$group_conjunction = 'AND';
$group_tags = array();
// Set conjunction from args.
if (isset($group['conjunction'])) {
$group_conjunction = $group['conjunction'];
}
if (isset($group['tags'])) {
$group_tags = $group['tags'];
}
// Create a single condition group.
$condition_group = $this->query->createConditionGroup($group_conjunction, $group_tags);
// Loop through all conditions and add them to the Group.
foreach ($group['conditions'] as $condition) {
$condition_group->addCondition($condition['name'], $condition['value'], $condition['operator']);
}
// Merge the single groups to the condition group.
$this->query->addConditionGroup($condition_group);
}
}
/**
* Adds direct Solr parameters to the Search API query.
*
* @params
* The conditions to be added.
*/
private function addSolrParams($params) {
// Loop through conditions to add them into the query.
foreach ($params as $param) {
// Set the condition in the query.
$this->query->setOption('solr_param_' . $param['parameter'], $param['value']);
}
}
/**
* Sets fulltext fields in the Search API query.
*
* @full_text_params
* Parameters containing fulltext keywords to be used as well as optional
* fields.
*/
private function setFulltextFields($full_text_params) {
// Check if keys is an array and if so set a conjunction.
if (is_array($full_text_params['keys'])) {
// If no conjunction was specified use OR as default.
if (!empty($full_text_params['conjunction'])) {
$full_text_params['keys']['#conjunction'] = $full_text_params['conjunction'];
}
else {
$full_text_params['keys']['#conjunction'] = 'OR';
}
}
// Set the keys in the query.
$this->query->keys($full_text_params['keys']);
// Set the optional fulltext fields if specified.
if (!empty($full_text_params['fields'])) {
$this->query->setFulltextFields($full_text_params['fields']);
}
}
/**
* Sets facets in the Search API query.
*
* @facets
* The facets to be added to the query.
*/
private function setFacets($facets) {
// Retrieve this index server details.
$server = $this->index->getServerInstance();
// Check if the index server supports facets (e.g solr).
if ($server->supportsFeature('search_api_facets')) {
$facets_array = [];
// Loop through all the provided facets.
foreach ($facets as $facet) {
$facets_array[$facet['field']] = [
'field' => $facet['field'],
'limit' => $facet['limit'],
'operator' => $facet['operator'],
'min_count' => $facet['min_count'],
'missing' => $facet['missing'],
];
}
// Set the facets in the query.
$this->query->setOption('search_api_facets', $facets_array);
}
}
/**
* Sets MLT in the Search API query.
*
* @facets
* The MLT params to be added to the query.
*/
private function setMLT($mlt_params) {
// Retrieve this index server details.
$server = $this->index->getServerInstance();
// Check if the index server supports More Like This (e.g solr).
if ($server->supportsFeature('search_api_mlt')) {
// Set the more like this parameters in the query.
$this->query->setOption('search_api_mlt', $mlt_params);
}
}
/**
* Prepares the Search API query by adding all possible options.
*
* Options include conditions, language, fulltext, range, sort and facets.
*
* @args
* The arguments containing all the parameters to be loaded to the query.
*/
private function prepareSearchQuery($args) {
// Prepare a query for the respective Search API index.
$this->query = $this->index->query();
// Adding query conditions if they exist.
if ($args['conditions']) {
$this->addConditions($args['conditions']);
}
// Adding query group conditions if they exist.
if ($args['condition_group']) {
$this->addConditionGroup($args['condition_group']);
}
// Adding Solr specific parameters if they exist.
if ($args['solr_params']) {
$this->addSolrParams($args['solr_params']);
}
// Restrict the search to specific languages.
if ($args['language']) {
$this->query->setLanguages($args['language']);
}
// Set fulltext search parameters in the query.
if ($args['fulltext']) {
$this->setFulltextFields($args['fulltext']);
}
// Adding range parameters to the query (e.g for pagination).
if ($args['range']) {
$this->query->range($args['range']['offset'], $args['range']['limit']);
}
// Adding sort parameters to the query.
if ($args['sort']) {
foreach ($args['sort'] as $sort) {
$this->query->sort($sort['field'], $sort['value']);
}
}
// Adding facets to the query.
if ($args['facets']) {
$this->setFacets($args['facets']);
}
// Adding more like this parameters to the query.
if ($args['more_like_this']) {
$this->setMLT($args['more_like_this']);
}
}
/**
* Obtain a Search Response from the results returned by Search API.
*
* @results
* The Search API results to be parsed.
*/
private function getSearchResponse($results) {
// Obtain result items.
$result_items = $results->getResultItems();
// Initialise response array.
$search_response = [];
// Loop through each item in the result set.
foreach ($result_items as $id => &$item) {
// Load the response document into the search response array.
$document['item'] = $item;
$document['index_id'] = $this->index->id();
$document['type'] = str_replace("_", "", ucwords($this->index->id() . "Doc", '_'));
// Set the relevance score.
$document['relevance'] = $item->getScore();
$search_response['SearchAPIDocument'][] = $document;
}
// Extract facets from the result set.
$facets = $results->getExtraData('search_api_facets');
if ($facets) {
$search_response['facets'] = $facets;
}
return $search_response;
}
}