-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathIndexer.php
430 lines (356 loc) · 11.2 KB
/
Indexer.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
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
<?php
namespace Simgroep\ConcurrentSpiderBundle;
use PhpAmqpLib\Message\AMQPMessage;
use Solarium\Client;
use Solarium\QueryType\Update\Query\Query;
use Solarium\Exception\HttpException;
use DateTime;
use VDB\Uri\Uri;
/**
* This class provides a gateway to the datastore for spidered webpages.
*/
class Indexer
{
const maxSolrQueryParams = 100;
/**
* @var \Solarium\Client
*/
private $client;
/**
* Holds the documents before submitting them to Solr
*
* @var array
*/
private $documents = [];
/**
* @var array
*/
private $mapping;
/**
* Amount of documents that should be kept in memory before they are saved to solr.
*
* @var integer
*/
private $minimalDocumentSaveAmount;
/**
* Constructor.
*
* @param \Solarium\Client $client
* @param array $mapping
* @param integer $minimalDocumentSaveAmount
*/
public function __construct(Client $client, array $mapping, $minimalDocumentSaveAmount)
{
$this->client = $client;
$this->mapping = $mapping;
$this->minimalDocumentSaveAmount = $minimalDocumentSaveAmount;
}
/**
* Indicates whether an URL already has been indexed or not.
*
* @param string $uri
* @param array $metadata
*
* @return boolean
*/
public function isUrlIndexedandNotExpired($uri, array $metadata = [])
{
$this->setCoreNameFromMetadata($metadata);
$currentDate = new DateTime();
$queryPhrase = sprintf(
"id:%s AND revisit_expiration:[%s TO *]",
sha1(strtolower($uri)),
$currentDate->format('Y-m-d\TH:i:s\Z')
);
$query = $this->client->createSelect();
$query->setQuery($queryPhrase);
$result = $this->client->select($query);
return ($result->getNumFound() > 0);
}
/**
* Returns unique hashes for uris from one page.
*
* @param Uri[] $uris
*
* @return array
*/
public function getUniqueHashIds($uris)
{
$hashes = [];
foreach ($uris as $uri) {
$uri = UrlCheck::normalizeUri($uri);
$hashId = $this->getHashSolarId($uri);
$hashes[$hashId] = $uri;
}
return array_keys($hashes);
}
/**
* Filters all URL from one page and return not indexed or expired.
*
* @param $uris
* @param array $metadata
*
* @return array
*/
public function filterIndexedAndNotExpired($uris, array $metadata = [])
{
if (!count($uris)) {
return $uris;
}
$this->setCoreNameFromMetadata($metadata);
$currentDate = new DateTime();
$docIds = $this->getUniqueHashIds($uris);
$urisAll = [];
$docIdsParts = array_chunk($docIds, self::maxSolrQueryParams);
foreach ($docIdsParts as $docIdsSet) {
$queryPhrase = sprintf(
'id:(%s) AND revisit_expiration:[%s TO *]',
implode(' OR ', $docIdsSet),
$currentDate->format('Y-m-d\TH:i:s\Z')
);
$query = $this->client->createSelect();
$query->setQuery($queryPhrase);
$result = $this->client->select($query);
if ($result->getNumFound() > 0) {
$storedIds = array_map(function ($doc) {
return $doc->id;
}, $result->getDocuments());
$uris = $this->getUnstoredOrExpiredUris($uris, $storedIds);
$urisAll = array_merge($urisAll, $uris);
}
}
return count($urisAll) ? $urisAll : $uris;
}
/**
* Returns unique urls to be crawl from one page.
*
* @param Uri[] $uris
* @param $storedIds
*
* @return array
*/
public function getUnstoredOrExpiredUris($uris, $storedIds)
{
$toCrawlUris = [];
foreach ($uris as $uri) {
$uri = UrlCheck::normalizeUri($uri);
$hashId = $this->getHashSolarId($uri);
if (!in_array($hashId, $storedIds)) {
$toCrawlUris[$hashId] = $uri;
}
}
return $toCrawlUris;
}
/**
* Removes all documents of a complete core.
*
* @param string $core
*/
public function emptyCore($core)
{
$this->setCoreNameFromMetadata(['core' => $core]);
$update = $this->client->createUpdate();
$update->addDeleteQuery('*:*');
$update->addCommit();
$this->client->update($update);
}
/**
* Get document urls and id from solr.
* @param array $metadata
* @return null|\Solarium\Core\Plugin\PluginInterface
*/
public function getDocumentUrlsInCore($metadata)
{
$this->setCoreNameFromMetadata($metadata);
$query = $this->client->createSelect();
$query->setQuery('*:*');
$query->setFields(['url', 'id']);
$prefetch = $this->client->getPlugin('prefetchiterator');
$prefetch->setPrefetch(100); //fetch 2 rows per query (for real world use this can be way higher)
$prefetch->setQuery($query);
return $prefetch;
}
/**
* Returns the amount of documents in a core.
*
* @param string $core
*
* @return integer
*
* @throws Solarium\Exception\HttpException
*/
public function getAmountDocumentsInCore($core)
{
$this->setCoreNameFromMetadata(['core' => $core]);
$query = $this->client->createSelect();
$query->setQuery('*:*');
$result = $this->client->select($query);
return $result->getNumFound();
}
/**
* Returns a SOLR document based on the given URL.
*
* @param string $url
* @param array $metadata
*
* @return array
*/
public function findDocumentByUrl($url, array $metadata = [])
{
$this->setCoreNameFromMetadata($metadata);
$query = $this->client->createSelect();
$query->setQuery(sprintf('id:%s', sha1(strtolower($url))));
$result = $this->client->select($query);
return ($result->getNumFound() == 0) ? null : $result->getDocuments()[0];
}
/**
* Returns url's that are expired.
*
* @param string $core
*
* @return \Solarium\QueryType\Select\Result\Result
*/
public function findExpiredUrls($core)
{
$this->setCoreNameFromMetadata(['core' => $core]);
$now = new DateTime();
$queryPhrase = sprintf("revisit_expiration:[* TO %s]", $now->format('Y-m-d\TH:i:s\Z'));
$query = $this->client->createSelect()
->setQuery($queryPhrase)
->setRows(1000);
return $this->client->select($query);
}
/**
* Returns url's that are not indexed or indexed but expired.
*
* @param string $uri
* @param array $metadata
*
* @return boolean
*/
public function isUrlNotIndexedOrIndexedAndExpired($uri, array $metadata = [])
{
$this->setCoreNameFromMetadata($metadata);
$uriHash = sha1(strtolower($uri));
$queryPhrase = sprintf(
"id:%s",
$uriHash
);
$query = $this->client->createSelect();
$query->setQuery($queryPhrase);
$result = $this->client->select($query);
if ($result->getNumFound() < 1) {
return true;
}
$now = new DateTime();
$queryPhrase = sprintf(
"id:%s AND revisit_expiration:[* TO %s]",
$uriHash,
$now->format('Y-m-d\TH:i:s\Z')
);
$query->setQuery($queryPhrase);
$result = $this->client->select($query);
return ($result->getNumFound() > 0);
}
/**
* Make a document ready to be indexed.
*
* @param \PhpAmqpLib\Message\AMQPMessage $message
*/
public function prepareDocument(AMQPMessage $message)
{
$data = json_decode($message->body, true);
$core = '';
if (array_key_exists('core', $data['metadata'])) {
$core = $data['metadata']['core'];
}
$updateQuery = $this->client->createUpdate();
$document = $updateQuery->createDocument();
foreach ($this->mapping as $field => $solrField) {
if ($field === 'groups') {
foreach ($solrField as $groupFieldName => $solrGroupFields) {
foreach ($solrGroupFields as $fieldName => $solrGroupFieldName) {
$composedFieldName = $groupFieldName . '.' . $fieldName;
$composedSolrFieldName = $groupFieldName . '.' . $solrGroupFieldName;
if (array_key_exists($composedFieldName, $data['document'])) {
$document->addField($composedSolrFieldName, $data['document'][$composedFieldName]);
}
}
}
continue;
}
if (array_key_exists($field, $data['document'])) {
$document->addField($solrField, $data['document'][$field]);
}
}
$this->documents[$core][] = $document;
if (count($this->documents, true) >= $this->minimalDocumentSaveAmount) {
foreach (array_keys($this->documents) as $core) {
$this->setCoreNameFromMetadata(['core' => $core]);
$updateQuery = $this->client->createUpdate();
$this->addDocuments($updateQuery, $this->documents[$core]);
}
$this->documents = [];
}
}
/**
* Remove document from solr by AMQPMessage.
*
* @param \PhpAmqpLib\Message\AMQPMessage $message
*/
public function deleteDocument(AMQPMessage $message)
{
$data = json_decode($message->body, true);
$this->deleteDocumentById($data['metadata'], sha1(strtolower($data['url'])));
}
/**
* Remove document from solr by ID
* @param array $metadata
* @param string $document_id
*/
public function deleteDocumentById($metadata, $document_id)
{
$this->setCoreNameFromMetadata($metadata);
$updateQuery = $this->client->createUpdate();
$updateQuery->addDeleteById($document_id);
$this->client->update($updateQuery);
}
/**
* Set Core Name to write/read data
*
* @param array $metadata
*/
protected function setCoreNameFromMetadata(array $metadata)
{
if (array_key_exists('core', $metadata)) {
foreach ($this->client->getEndPoints() as $endpoint) {
$endpoint->setCore($metadata['core']);
}
}
}
/**
* Add multiple documents to the data store.
*
* @param \Solarium\QueryType\Update\Query\Query $updateQuery
* @param array $documents
*/
protected function addDocuments(Query $updateQuery, array $documents)
{
$updateQuery->addDocuments($documents);
$this->client->update($updateQuery);
}
/**
* Get unique solar index document id
*
* @param Uri|string $uri
*
* @return string
*/
public function getHashSolarId($uri)
{
if ($uri instanceof Uri) {
$uri = $uri->toString();
}
return sha1(strtolower(UrlCheck::fixUrl($uri)));
}
}