forked from DSpace/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolrServiceImpl.java
More file actions
1643 lines (1479 loc) · 72.8 KB
/
SolrServiceImpl.java
File metadata and controls
1643 lines (1479 loc) · 72.8 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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.discovery;
import static java.util.stream.Collectors.joining;
import static org.dspace.discovery.indexobject.ItemIndexFactoryImpl.STATUS_FIELD;
import static org.dspace.discovery.indexobject.ItemIndexFactoryImpl.STATUS_FIELD_PREDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.TimeZone;
import java.util.UUID;
import javax.mail.MessagingException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.MoreLikeThisParams;
import org.apache.solr.common.params.SpellingParams;
import org.apache.solr.common.util.NamedList;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogHelper;
import org.dspace.discovery.configuration.DiscoveryConfiguration;
import org.dspace.discovery.configuration.DiscoveryConfigurationParameters;
import org.dspace.discovery.configuration.DiscoveryMoreLikeThisConfiguration;
import org.dspace.discovery.configuration.DiscoverySearchFilterFacet;
import org.dspace.discovery.configuration.DiscoverySortConfiguration;
import org.dspace.discovery.indexobject.IndexableCollection;
import org.dspace.discovery.indexobject.IndexableCommunity;
import org.dspace.discovery.indexobject.IndexableItem;
import org.dspace.discovery.indexobject.factory.IndexFactory;
import org.dspace.discovery.indexobject.factory.IndexObjectFactoryFactory;
import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.GroupService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* SolrIndexer contains the methods that index Items and their metadata,
* collections, communities, etc. It is meant to either be invoked from the
* command line (see dspace/bin/index-all) or via the indexContent() methods
* within DSpace.
* <p>
* The Administrator can choose to run SolrIndexer in a cron that repeats
* regularly, a failed attempt to index from the UI will be "caught" up on in
* that cron.
*
* The SolrServiceImpl is registered as a Service in the ServiceManager via
* a Spring configuration file located under
* classpath://spring/spring-dspace-applicationContext.xml
*
* Its configuration is Autowired by the ApplicationContext
*
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
*/
@Service
public class SolrServiceImpl implements SearchService, IndexingService {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(SolrServiceImpl.class);
// Suffix of the solr field used to index the facet/filter so that the facet search can search all word in a
// facet by indexing "each word to end of value' partial value
public static final String SOLR_FIELD_SUFFIX_FACET_PREFIXES = "_prefix";
// Suffix of the solr field used to index the facet/filter so that the facet search can search all word in a
// facet.
private static final String SOLR_FACET_FIELD_ALL_VALUES_SUFFIX = "_filter";
// List of all facets which will return facet value with splitter.
private ArrayList<String> allValuesFacetList = new ArrayList<>();
@Autowired
protected ContentServiceFactory contentServiceFactory;
@Autowired
protected GroupService groupService;
@Autowired
protected IndexObjectFactoryFactory indexObjectServiceFactory;
@Autowired
protected SolrSearchCore solrSearchCore;
@Autowired
protected ConfigurationService configurationService;
protected SolrServiceImpl() {
}
/**
* If the handle for the "dso" already exists in the index, and the "dso"
* has a lastModified timestamp that is newer than the document in the index
* then it is updated, otherwise a new document is added.
*
* @param context Users Context
* @param dso DSpace Object (Item, Collection or Community
* @throws SQLException if error
*/
@Override
public void indexContent(Context context, IndexableObject dso)
throws SQLException {
indexContent(context, dso, false);
}
/**
* If the handle for the "dso" already exists in the index, and the "dso"
* has a lastModified timestamp that is newer than the document in the index
* then it is updated, otherwise a new document is added.
*
* @param context Users Context
* @param indexableObject The object we want to index
* @param force Force update even if not stale.
*/
@Override
public void indexContent(Context context, IndexableObject indexableObject,
boolean force) {
try {
final IndexFactory indexableObjectFactory = indexObjectServiceFactory.
getIndexableObjectFactory(indexableObject);
if (force || requiresIndexing(indexableObject.getUniqueIndexID(), indexableObject.getLastModified())) {
update(context, indexableObjectFactory, indexableObject);
log.info(LogHelper.getHeader(context, "indexed_object", indexableObject.getUniqueIndexID()));
}
} catch (IOException | SQLException | SolrServerException | SearchServiceException e) {
log.error(e.getMessage(), e);
}
}
protected void update(Context context, IndexFactory indexableObjectService,
IndexableObject indexableObject) throws IOException, SQLException, SolrServerException {
final SolrInputDocument solrInputDocument = indexableObjectService.buildDocument(context, indexableObject);
indexableObjectService.writeDocument(context, indexableObject, solrInputDocument);
}
/**
* Update the given indexable object using a given service
* @param context The DSpace Context
* @param indexableObjectService The service to index the object with
* @param indexableObject The object to index
* @param preDB Add a "preDB" status to the document
*/
protected void update(Context context, IndexFactory indexableObjectService, IndexableObject indexableObject,
boolean preDB) throws IOException, SQLException, SolrServerException {
if (preDB) {
final SolrInputDocument solrInputDocument =
indexableObjectService.buildNewDocument(context, indexableObject);
indexableObjectService.writeDocument(context, indexableObject, solrInputDocument);
} else {
update(context, indexableObjectService, indexableObject);
}
}
/**
* unIndex removes an Item, Collection, or Community
*
* @param context The relevant DSpace Context.
* @param dso DSpace Object, can be Community, Item, or Collection
* @throws SQLException if database error
* @throws IOException if IO error
*/
@Override
public void unIndexContent(Context context, IndexableObject dso)
throws SQLException, IOException {
unIndexContent(context, dso, false);
}
/**
* unIndex removes an Item, Collection, or Community
*
* @param context The relevant DSpace Context.
* @param indexableObject The object to be indexed
* @param commit if <code>true</code> force an immediate commit on SOLR
* @throws SQLException if database error
* @throws IOException if IO error
*/
@Override
public void unIndexContent(Context context, IndexableObject indexableObject, boolean commit)
throws SQLException, IOException {
try {
if (indexableObject == null) {
return;
}
String uniqueID = indexableObject.getUniqueIndexID();
log.info("Try to delete uniqueID:" + uniqueID);
indexObjectServiceFactory.getIndexableObjectFactory(indexableObject).delete(indexableObject);
if (commit) {
solrSearchCore.getSolr().commit();
}
} catch (IOException | SolrServerException exception) {
log.error(exception.getMessage(), exception);
emailException(exception);
}
}
/**
* Unindex a Document in the Lucene index.
*
* @param context the dspace context
* @param searchUniqueID the search uniqueID of the document to be deleted
* @throws IOException if IO error
*/
@Override
public void unIndexContent(Context context, String searchUniqueID) throws IOException {
unIndexContent(context, searchUniqueID, false);
}
/**
* Unindex a Document in the Lucene Index.
*
* @param context the dspace context
* @param searchUniqueID the search uniqueID of the document to be deleted
* @param commit commit the update immediately.
* @throws IOException if IO error
*/
@Override
public void unIndexContent(Context context, String searchUniqueID, boolean commit)
throws IOException {
try {
if (solrSearchCore.getSolr() != null) {
IndexFactory index = indexObjectServiceFactory.getIndexableObjectFactory(searchUniqueID);
if (index != null) {
index.delete(searchUniqueID);
} else {
log.warn("Object not found in Solr index: " + searchUniqueID);
}
if (commit) {
solrSearchCore.getSolr().commit();
}
}
} catch (SolrServerException e) {
log.error(e.getMessage(), e);
}
}
/**
* reIndexContent removes something from the index, then re-indexes it
*
* @param context context object
* @param dso object to re-index
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
*/
@Override
public void reIndexContent(Context context, IndexableObject dso)
throws SQLException, IOException {
try {
indexContent(context, dso);
} catch (SQLException exception) {
log.error(exception.getMessage(), exception);
emailException(exception);
}
}
/**
* create full index - wiping old index
*
* @param c context to use
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
*/
@Override
public void createIndex(Context c) throws SQLException, IOException {
/* Reindex all content preemptively. */
updateIndex(c, true);
}
/**
* Iterates over all Items, Collections and Communities. And updates them in
* the index. Uses decaching to control memory footprint. Uses indexContent
* and isStale to check state of item in index.
*
* @param context the dspace context
*/
@Override
public void updateIndex(Context context) {
updateIndex(context, false);
}
/**
* Iterates over all Items, Collections and Communities. And updates them in
* the index. Uses decaching to control memory footprint. Uses indexContent
* and isStale to check state of item in index.
* <p>
* At first it may appear counterintuitive to have an IndexWriter/Reader
* opened and closed on each DSO. But this allows the UI processes to step
* in and attain a lock and write to the index even if other processes/jvms
* are running a reindex.
*
* @param context the dspace context
* @param force whether or not to force the reindexing
*/
@Override
public void updateIndex(Context context, boolean force) {
updateIndex(context, force, null);
}
@Override
public void updateIndex(Context context, boolean force, String type) {
try {
final List<IndexFactory> indexableObjectServices = indexObjectServiceFactory.
getIndexFactories();
for (IndexFactory indexableObjectService : indexableObjectServices) {
if (type == null || StringUtils.equals(indexableObjectService.getType(), type)) {
final Iterator<IndexableObject> indexableObjects = indexableObjectService.findAll(context);
while (indexableObjects.hasNext()) {
final IndexableObject indexableObject = indexableObjects.next();
indexContent(context, indexableObject, force);
context.uncacheEntity(indexableObject.getIndexedObject());
}
}
}
if (solrSearchCore.getSolr() != null) {
solrSearchCore.getSolr().commit();
}
} catch (IOException | SQLException | SolrServerException e) {
log.error(e.getMessage(), e);
}
}
/**
* Removes all documents from the Lucene index
*/
public void deleteIndex() {
try {
final List<IndexFactory> indexableObjectServices = indexObjectServiceFactory.
getIndexFactories();
for (IndexFactory indexableObjectService : indexableObjectServices) {
indexableObjectService.deleteAll();
}
} catch (IOException | SolrServerException e) {
log.error("Error cleaning discovery index: " + e.getMessage(), e);
}
}
/**
* Iterates over all documents in the Lucene index and verifies they are in
* database, if not, they are removed.
*
* @throws IOException IO exception
* @throws SQLException sql exception
* @throws SearchServiceException occurs when something went wrong with querying the solr server
*/
@Override
public void cleanIndex() throws IOException, SQLException, SearchServiceException {
Context context = new Context();
context.turnOffAuthorisationSystem();
try {
if (solrSearchCore.getSolr() == null) {
return;
}
// First, we'll just get a count of the total results
SolrQuery countQuery = new SolrQuery("*:*");
countQuery.setRows(0); // don't actually request any data
// Get the total amount of results
QueryResponse totalResponse = solrSearchCore.getSolr().query(countQuery,
solrSearchCore.REQUEST_METHOD);
long total = totalResponse.getResults().getNumFound();
int start = 0;
int batch = 100;
// Now get actual Solr Documents in batches
SolrQuery query = new SolrQuery();
query.setFields(SearchUtils.RESOURCE_UNIQUE_ID, SearchUtils.RESOURCE_ID_FIELD,
SearchUtils.RESOURCE_TYPE_FIELD);
query.addSort(SearchUtils.RESOURCE_UNIQUE_ID, SolrQuery.ORDER.asc);
query.setQuery("*:*");
query.setRows(batch);
// Keep looping until we hit the total number of Solr docs
while (start < total) {
query.setStart(start);
QueryResponse rsp = solrSearchCore.getSolr().query(query, solrSearchCore.REQUEST_METHOD);
SolrDocumentList docs = rsp.getResults();
for (SolrDocument doc : docs) {
String uniqueID = (String) doc.getFieldValue(SearchUtils.RESOURCE_UNIQUE_ID);
IndexableObject o = findIndexableObject(context, doc);
if (o == null) {
log.info("Deleting: " + uniqueID);
/*
* Use IndexWriter to delete, its easier to manage
* write.lock
*/
unIndexContent(context, uniqueID);
} else {
log.debug("Keeping: " + o.getUniqueIndexID());
}
}
start += batch;
}
} catch (IOException | SQLException | SolrServerException e) {
log.error("Error cleaning discovery index: " + e.getMessage(), e);
} finally {
context.abort();
}
}
/**
* Maintenance to keep a SOLR index efficient.
* Note: This might take a long time.
*/
@Override
public void optimize() {
try {
if (solrSearchCore.getSolr() == null) {
return;
}
long start = System.currentTimeMillis();
System.out.println("SOLR Search Optimize -- Process Started:" + start);
solrSearchCore.getSolr().optimize();
long finish = System.currentTimeMillis();
System.out.println("SOLR Search Optimize -- Process Finished:" + finish);
System.out.println("SOLR Search Optimize -- Total time taken:" + (finish - start) + " (ms).");
} catch (SolrServerException | IOException e) {
System.err.println(e.getMessage());
}
}
@Override
public void buildSpellCheck()
throws SearchServiceException, IOException {
try {
if (solrSearchCore.getSolr() == null) {
return;
}
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("spellcheck", true);
solrQuery.set(SpellingParams.SPELLCHECK_BUILD, true);
solrSearchCore.getSolr().query(solrQuery, solrSearchCore.REQUEST_METHOD);
} catch (SolrServerException e) {
//Make sure to also log the exception since this command is usually run from a crontab.
log.error(e, e);
throw new SearchServiceException(e);
}
}
@Override
public void atomicUpdate(Context context, String uniqueIndexId, String field, Map<String, Object> fieldModifier)
throws SolrServerException, IOException {
SolrInputDocument solrInputDocument = new SolrInputDocument();
solrInputDocument.addField(SearchUtils.RESOURCE_UNIQUE_ID, uniqueIndexId);
solrInputDocument.addField(field, fieldModifier);
solrSearchCore.getSolr().add(solrInputDocument);
}
// //////////////////////////////////
// Private
// //////////////////////////////////
protected void emailException(Exception exception) {
// Also email an alert, system admin may need to check for stale lock
try {
String recipient = configurationService.getProperty("alert.recipient");
if (StringUtils.isNotBlank(recipient)) {
Email email = Email
.getEmail(I18nUtil.getEmailFilename(
Locale.getDefault(), "internal_error"));
email.addRecipient(recipient);
email.addArgument(configurationService.getProperty("dspace.ui.url"));
email.addArgument(new Date());
String stackTrace;
if (exception != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
pw.flush();
stackTrace = sw.toString();
} else {
stackTrace = "No exception";
}
email.addArgument(stackTrace);
email.send();
}
} catch (IOException | MessagingException e) {
// Not much we can do here!
log.warn("Unable to send email alert", e);
}
}
/**
* Is stale checks the lastModified time stamp in the database and the index
* to determine if the index is stale.
*
* @param uniqueId the unique identifier of the object that we want to index
* @param lastModified the last modified date of the DSpace object
* @return a boolean indicating if the dso should be re indexed again
* @throws SQLException sql exception
* @throws IOException io exception
* @throws SearchServiceException if something went wrong with querying the solr server
*/
protected boolean requiresIndexing(String uniqueId, Date lastModified)
throws SQLException, IOException, SearchServiceException {
// Check if we even have a last modified date
if (lastModified == null) {
return true;
}
boolean reindexItem = false;
boolean inIndex = false;
SolrQuery query = new SolrQuery();
query.setQuery(SearchUtils.RESOURCE_UNIQUE_ID + ":" + uniqueId);
// Specify that we ONLY want the LAST_INDEXED_FIELD returned in the field list (fl)
query.setFields(SearchUtils.LAST_INDEXED_FIELD);
QueryResponse rsp;
try {
if (solrSearchCore.getSolr() == null) {
return false;
}
rsp = solrSearchCore.getSolr().query(query, solrSearchCore.REQUEST_METHOD);
} catch (SolrServerException e) {
throw new SearchServiceException(e.getMessage(), e);
}
for (SolrDocument doc : rsp.getResults()) {
inIndex = true;
Object value = doc.getFieldValue(SearchUtils.LAST_INDEXED_FIELD);
if (value instanceof Date) {
Date lastIndexed = (Date) value;
if (lastIndexed.before(lastModified)) {
reindexItem = true;
}
}
}
return reindexItem || !inIndex;
}
@Override
public String createLocationQueryForAdministrableItems(Context context)
throws SQLException {
StringBuilder locationQuery = new StringBuilder();
if (context.getCurrentUser() != null) {
List<Group> groupList = EPersonServiceFactory.getInstance().getGroupService()
.allMemberGroups(context, context.getCurrentUser());
List<ResourcePolicy> communitiesPolicies = AuthorizeServiceFactory.getInstance().getResourcePolicyService()
.find(context, context.getCurrentUser(),
groupList, Constants.ADMIN,
Constants.COMMUNITY);
List<ResourcePolicy> collectionsPolicies = AuthorizeServiceFactory.getInstance().getResourcePolicyService()
.find(context, context.getCurrentUser(),
groupList, Constants.ADMIN,
Constants.COLLECTION);
List<Collection> allCollections = new ArrayList<>();
for (ResourcePolicy rp : collectionsPolicies) {
Collection collection = ContentServiceFactory.getInstance().getCollectionService()
.find(context, rp.getdSpaceObject().getID());
allCollections.add(collection);
}
if (CollectionUtils.isNotEmpty(communitiesPolicies) || CollectionUtils.isNotEmpty(allCollections)) {
locationQuery.append("location:( ");
for (int i = 0; i < communitiesPolicies.size(); i++) {
ResourcePolicy rp = communitiesPolicies.get(i);
Community community = ContentServiceFactory.getInstance().getCommunityService()
.find(context, rp.getdSpaceObject().getID());
locationQuery.append("m").append(community.getID());
if (i != (communitiesPolicies.size() - 1)) {
locationQuery.append(" OR ");
}
allCollections.addAll(ContentServiceFactory.getInstance().getCommunityService()
.getAllCollections(context, community));
}
Iterator<Collection> collIter = allCollections.iterator();
if (communitiesPolicies.size() > 0 && allCollections.size() > 0) {
locationQuery.append(" OR ");
}
while (collIter.hasNext()) {
locationQuery.append("l").append(collIter.next().getID());
if (collIter.hasNext()) {
locationQuery.append(" OR ");
}
}
locationQuery.append(")");
} else {
log.warn("We have a collection or community admin with ID: " + context.getCurrentUser().getID()
+ " without any administrable collection or community!");
}
}
return locationQuery.toString();
}
/**
* Helper function to retrieve a date using a best guess of the potential
* date encodings on a field
*
* @param t the string to be transformed to a date
* @return a date if the formatting was successful, null if not able to transform to a date
*/
public Date toDate(String t) {
SimpleDateFormat[] dfArr;
// Choose the likely date formats based on string length
switch (t.length()) {
// case from 1 to 3 go through adding anyone a single 0. Case 4 define
// for all the SimpleDateFormat
case 1:
t = "0" + t;
// fall through
case 2:
t = "0" + t;
// fall through
case 3:
t = "0" + t;
// fall through
case 4:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyy")};
break;
case 6:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyyMM")};
break;
case 7:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyy-MM")};
break;
case 8:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyyMMdd"),
new SimpleDateFormat("yyyy MMM")};
break;
case 10:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyy-MM-dd")};
break;
case 11:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat("yyyy MMM dd")};
break;
case 20:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'")};
break;
default:
dfArr = new SimpleDateFormat[] {new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")};
break;
}
for (SimpleDateFormat df : dfArr) {
try {
// Parse the date
df.setCalendar(Calendar
.getInstance(TimeZone.getTimeZone("UTC")));
df.setLenient(false);
return df.parse(t);
} catch (ParseException pe) {
log.error("Unable to parse date format", pe);
}
}
return null;
}
public String locationToName(Context context, String field, String value) throws SQLException {
if ("location.comm".equals(field) || "location.coll".equals(field)) {
int type = ("location.comm").equals(field) ? Constants.COMMUNITY : Constants.COLLECTION;
DSpaceObject commColl = null;
if (StringUtils.isNotBlank(value)) {
commColl = contentServiceFactory.getDSpaceObjectService(type).find(context, UUID.fromString(value));
}
if (commColl != null) {
return commColl.getName();
}
}
return value;
}
//========== SearchService implementation
@Override
public DiscoverResult search(Context context, IndexableObject dso, DiscoverQuery discoveryQuery)
throws SearchServiceException {
if (dso != null) {
if (dso instanceof IndexableCommunity) {
discoveryQuery.addFilterQueries("location:m" + dso.getID());
} else if (dso instanceof IndexableCollection) {
discoveryQuery.addFilterQueries("location:l" + dso.getID());
} else if (dso instanceof IndexableItem) {
discoveryQuery.addFilterQueries(SearchUtils.RESOURCE_UNIQUE_ID + ":" + dso.
getUniqueIndexID());
}
}
return search(context, discoveryQuery);
}
@Override
public Iterator<Item> iteratorSearch(Context context, IndexableObject dso, DiscoverQuery query)
throws SearchServiceException {
return new SearchIterator(context, dso, query);
}
@Override
public DiscoverResult search(Context context, DiscoverQuery discoveryQuery)
throws SearchServiceException {
try {
if (solrSearchCore.getSolr() == null) {
return new DiscoverResult();
}
return retrieveResult(context, discoveryQuery);
} catch (Exception e) {
throw new org.dspace.discovery.SearchServiceException(e.getMessage(), e);
}
}
/**
* This class implements an iterator over items that is specifically used to iterate over search results
*/
private class SearchIterator implements Iterator<Item> {
private Context context;
private DiscoverQuery discoverQuery;
private DiscoverResult discoverResult;
private IndexableObject dso;
private int absoluteCursor;
private int relativeCursor;
private int pagesize;
SearchIterator(Context context, DiscoverQuery discoverQuery) throws SearchServiceException {
this.context = context;
this.discoverQuery = discoverQuery;
this.absoluteCursor = discoverQuery.getStart();
initialise();
}
SearchIterator(Context context, IndexableObject dso, DiscoverQuery discoverQuery)
throws SearchServiceException {
this.context = context;
this.dso = dso;
this.discoverQuery = discoverQuery;
initialise();
}
private void initialise() throws SearchServiceException {
this.relativeCursor = 0;
if (discoverQuery.getMaxResults() != -1) {
pagesize = discoverQuery.getMaxResults();
} else {
pagesize = 10;
}
discoverQuery.setMaxResults(pagesize);
this.discoverResult = search(context, dso, discoverQuery);
}
@Override
public boolean hasNext() {
return absoluteCursor < discoverResult.getTotalSearchResults();
}
@Override
public Item next() {
//paginate getting results from the discoverquery.
if (relativeCursor == pagesize) {
// get a new page of results when the last element of the previous page has been read
int offset = absoluteCursor;
// reset the position counter for getting element relativecursor on a page
relativeCursor = 0;
discoverQuery.setStart(offset);
try {
discoverResult = search(context, dso, discoverQuery);
} catch (SearchServiceException e) {
log.error("error while getting search results", e);
}
}
// get the element at position relativecursor on a page
IndexableObject res = discoverResult.getIndexableObjects().get(relativeCursor);
relativeCursor++;
absoluteCursor++;
return (Item) res.getIndexedObject();
}
}
protected SolrQuery resolveToSolrQuery(Context context, DiscoverQuery discoveryQuery)
throws SearchServiceException {
SolrQuery solrQuery = new SolrQuery();
String query = "*:*";
if (discoveryQuery.getQuery() != null) {
query = discoveryQuery.getQuery();
}
solrQuery.setQuery(query);
// Add any search fields to our query. This is the limited list
// of fields that will be returned in the solr result
for (String fieldName : discoveryQuery.getSearchFields()) {
solrQuery.addField(fieldName);
}
// Also ensure a few key obj identifier fields are returned with every query
solrQuery.addField(SearchUtils.RESOURCE_TYPE_FIELD);
solrQuery.addField(SearchUtils.RESOURCE_ID_FIELD);
solrQuery.addField(SearchUtils.RESOURCE_UNIQUE_ID);
solrQuery.addField(STATUS_FIELD);
if (discoveryQuery.isSpellCheck()) {
solrQuery.setParam(SpellingParams.SPELLCHECK_Q, query);
solrQuery.setParam(SpellingParams.SPELLCHECK_COLLATE, Boolean.TRUE);
solrQuery.setParam("spellcheck", Boolean.TRUE);
}
for (int i = 0; i < discoveryQuery.getFilterQueries().size(); i++) {
String filterQuery = discoveryQuery.getFilterQueries().get(i);
solrQuery.addFilterQuery(filterQuery);
}
if (discoveryQuery.getDSpaceObjectFilters() != null) {
solrQuery.addFilterQuery(
discoveryQuery.getDSpaceObjectFilters()
.stream()
.map(filter -> SearchUtils.RESOURCE_TYPE_FIELD + ":" + filter)
.collect(joining(" OR "))
);
}
for (int i = 0; i < discoveryQuery.getFieldPresentQueries().size(); i++) {
String filterQuery = discoveryQuery.getFieldPresentQueries().get(i);
solrQuery.addFilterQuery(filterQuery + ":[* TO *]");
}
if (discoveryQuery.getStart() != -1) {
solrQuery.setStart(discoveryQuery.getStart());
}
if (discoveryQuery.getMaxResults() != -1) {
solrQuery.setRows(discoveryQuery.getMaxResults());
}
if (discoveryQuery.getSortField() != null) {
SolrQuery.ORDER order = SolrQuery.ORDER.asc;
if (discoveryQuery.getSortOrder().equals(DiscoverQuery.SORT_ORDER.desc)) {
order = SolrQuery.ORDER.desc;
}
solrQuery.addSort(discoveryQuery.getSortField(), order);
}
for (String property : discoveryQuery.getProperties().keySet()) {
List<String> values = discoveryQuery.getProperties().get(property);
solrQuery.add(property, values.toArray(new String[values.size()]));
}
List<DiscoverFacetField> facetFields = discoveryQuery.getFacetFields();
if (0 < facetFields.size()) {
//Only add facet information if there are any facets
for (DiscoverFacetField facetFieldConfig : facetFields) {
String field = transformFacetField(facetFieldConfig, facetFieldConfig.getField(), false);
if (facetFieldConfig.getPrefix() != null) {
field = transformPrefixFacetField(facetFieldConfig, facetFieldConfig.getField(), false);
}
solrQuery.addFacetField(field);
// Setting the facet limit in this fashion ensures that each facet can have its own max
solrQuery
.add("f." + field + "." + FacetParams.FACET_LIMIT, String.valueOf(facetFieldConfig.getLimit()));
String facetSort;
if (DiscoveryConfigurationParameters.SORT.COUNT.equals(facetFieldConfig.getSortOrder())) {
facetSort = FacetParams.FACET_SORT_COUNT;
} else {
facetSort = FacetParams.FACET_SORT_INDEX;
}
solrQuery.add("f." + field + "." + FacetParams.FACET_SORT, facetSort);
if (facetFieldConfig.getOffset() != -1) {
solrQuery.setParam("f." + field + "."
+ FacetParams.FACET_OFFSET,
String.valueOf(facetFieldConfig.getOffset()));
}
if (facetFieldConfig.getPrefix() != null) {
solrQuery.setFacetPrefix(field, facetFieldConfig.getPrefix());
}
}
}
List<String> facetQueries = discoveryQuery.getFacetQueries();
for (String facetQuery : facetQueries) {
solrQuery.addFacetQuery(facetQuery);
}
if (discoveryQuery.getFacetMinCount() != -1) {
solrQuery.setFacetMinCount(discoveryQuery.getFacetMinCount());
}
if (CollectionUtils.isNotEmpty(facetFields) || CollectionUtils.isNotEmpty(facetQueries)) {
solrQuery.setParam(FacetParams.FACET_OFFSET, String.valueOf(discoveryQuery.getFacetOffset()));
}
if (0 < discoveryQuery.getHitHighlightingFields().size()) {
solrQuery.setHighlight(true);
solrQuery.add(HighlightParams.USE_PHRASE_HIGHLIGHTER, Boolean.TRUE.toString());
for (DiscoverHitHighlightingField highlightingField : discoveryQuery.getHitHighlightingFields()) {
solrQuery.addHighlightField(highlightingField.getField() + "_hl");
solrQuery.add("f." + highlightingField.getField() + "_hl." + HighlightParams.FRAGSIZE,
String.valueOf(highlightingField.getMaxChars()));
solrQuery.add("f." + highlightingField.getField() + "_hl." + HighlightParams.SNIPPETS,
String.valueOf(highlightingField.getMaxSnippets()));
}
}
//Add any configured search plugins !
List<SolrServiceSearchPlugin> solrServiceSearchPlugins = DSpaceServicesFactory.getInstance()
.getServiceManager().getServicesByType(SolrServiceSearchPlugin.class);
for (SolrServiceSearchPlugin searchPlugin : solrServiceSearchPlugins) {
searchPlugin.additionalSearchParameters(context, discoveryQuery, solrQuery);
}
return solrQuery;
}
protected DiscoverResult retrieveResult(Context context, DiscoverQuery query)
throws SQLException, SolrServerException, IOException, SearchServiceException {
// we use valid and executeLimit to decide if the solr query need to be re-run if we found some stale objects
boolean valid = false;
int executionCount = 0;
DiscoverResult result = null;
SolrQuery solrQuery = resolveToSolrQuery(context, query);
// how many re-run of the query are allowed other than the first run
int maxAttempts = configurationService.getIntProperty("discovery.removestale.attempts", 3);
do {
executionCount++;
result = new DiscoverResult();
// if we found stale objects we can decide to skip execution of the remaining code to improve performance
boolean skipLoadingResponse = false;
// use zombieDocs to collect stale found objects