-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathElasticSearchService.groovy
2297 lines (2002 loc) · 88.6 KB
/
ElasticSearchService.groovy
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
/*
* Copyright (C) 2013 Atlas of Living Australia
* All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
package au.org.ala.ecodata
import com.mongodb.client.model.Filters
import grails.async.Promise
import grails.async.Promises
import grails.converters.JSON
import grails.core.GrailsApplication
import grails.util.Environment
import groovy.json.JsonSlurper
import groovy.util.logging.Slf4j
import org.apache.http.HttpHost
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
import org.elasticsearch.ElasticsearchException
import org.elasticsearch.action.bulk.BulkProcessor
import org.elasticsearch.action.bulk.BulkRequest
import org.elasticsearch.action.bulk.BulkResponse
import org.elasticsearch.action.delete.DeleteRequest
import org.elasticsearch.action.delete.DeleteResponse
import org.elasticsearch.action.get.GetRequest
import org.elasticsearch.action.get.GetResponse
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.action.search.SearchRequest
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.RestClientBuilder
import org.elasticsearch.client.RestHighLevelClient
import org.elasticsearch.core.TimeValue
import org.elasticsearch.geometry.Circle
import org.elasticsearch.geometry.Geometry
import org.elasticsearch.geometry.LinearRing
import org.elasticsearch.geometry.Polygon
import org.elasticsearch.index.query.*
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders
import org.elasticsearch.search.aggregations.AggregationBuilder
import org.elasticsearch.search.aggregations.AggregationBuilders
import org.elasticsearch.search.aggregations.BucketOrder
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder
import org.elasticsearch.search.builder.SearchSourceBuilder
import org.elasticsearch.search.sort.SortOrder
import org.elasticsearch.xcontent.XContentType
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEvent
import org.grails.datastore.mapping.engine.event.EventType
import org.grails.datastore.mapping.query.api.BuildableCriteria
import java.text.SimpleDateFormat
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.function.BiConsumer
import java.util.regex.Matcher
import static au.org.ala.ecodata.ElasticIndex.*
import static au.org.ala.ecodata.Status.DELETED
import static grails.async.Promises.task
import static org.elasticsearch.index.query.QueryBuilders.*
/**
* ElasticSearch service. This service is responsible for indexing documents as well as handling searches (queries).
*
* Note:
* DEFAULT_INDEX used by MERIT
* HOMEPAGE_INDEX shared by both Biocollect and MERIT (MERIT embeds activities to the project. Bicollect doesn't include embedded activities)
* PROJECT_ACTIVITY_INDEX used by Biocollect and its applicable to survey based projects (ie; non NRM one's)
*
* Code gist taken from
* https://github.com/mstein/elasticsearch-grails-plugin/blob/master/grails-app/services/org/grails/plugins/elasticsearch/ElasticSearchService.groovy
*
* @author "Nick dos Remedios <nick.dosremedios@csiro.au>"
*/
class ElasticSearchService {
static transactional = false
GrailsApplication grailsApplication
ProjectService projectService
ActivityService activityService
SiteService siteService
PermissionService permissionService
UserService userService
DocumentService documentService
ProjectActivityService projectActivityService
RecordService recordService
MetadataService metadataService
OrganisationService organisationService
OutputService outputService
EmailService emailService
HubService hubService
CacheService cacheService
ProgramService programService
ManagementUnitService managementUnitService
RestHighLevelClient client
ElasticSearchIndexManager indexManager
def indexingTempInactive = false // can be set to true for loading of dump files, etc
def ALLOWED_DOC_TYPES = [Project.class.name, Site.class.name, Document.class.name, Activity.class.name, Record.class.name, Organisation.class.name, UserPermission.class.name, Program.class.name, Output.class.name]
def DEFAULT_FACETS = 10
private static Queue<IndexDocMsg> _messageQueue = new ConcurrentLinkedQueue<IndexDocMsg>()
/**
* List of indexed fields we apply a compatibility layer to so we accept "T" and "F" as terms when filtering on these fields.
* This is required due to a change in the way elasticsearch handled boolean fields.
*/
private static List BOOLEAN_PROEJCT_FIELDS = ['isExternal', 'isMERIT', 'isCitizenScience', 'isSciStarter', 'alaHarvest']
private static List DOCUMENT_TYPES_TO_EXCLUDE_REINDEXING = ['link']
/**
* Init method to be called on service creation
*/
def initialize() {
log.info "Setting-up elasticsearch client and indexes"
client = buildElasticSearchClient()
String indexPrefix = grailsApplication.config.getProperty('app.elasticsearch.indexPrefix', String, Environment.current.name.toLowerCase())
Map mappings = getMapping()
indexManager = new ElasticSearchIndexManager(client, indexPrefix, mappings.settings, mapping.mappings)
// TODO - this needs to be in a retry loop in case ES is down when ecodata is started
indexManager.initialiseIndexAliases()
// MapService.buildGeoServerDependencies can throw Runtime exception. This causes bean initialization failure.
// Therefore, calling the below function in a thread.
task {
// Most of the time GeoServer starts before Ecodata. ES data connectors in GeoServer cannot connect to ES.
// The below code recreates the connectors.
if(getMapService().enabled) {
log.info("Starting to build GeoServer dependencies")
getMapService()?.buildGeoServerDependencies()
log.info("Completed building GeoServer dependencies")
}
}
}
private RestHighLevelClient buildElasticSearchClient() {
String host = grailsApplication.config.getProperty('elasticsearch.host', String, 'localhost')
int port = grailsApplication.config.getProperty('elasticsearch.port', Integer, 9200)
String username = grailsApplication.config.getProperty('elasticsearch.username')
String password = grailsApplication.config.getProperty('elasticsearch.password')
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password))
RestClientBuilder builder = RestClient.builder(
new HttpHost(host, port, "http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
})
new RestHighLevelClient(builder)
}
// Used to avoid a circular dependency during initialisation
def getMapService() {
return grailsApplication.mainContext.mapService
}
/**
* Index a single document (toMap representation not domain class)
* Does a check to see if doc has been marked as deleted.
*
* @param doc
* @return IndexResponse
*/
def indexDoc(doc, String index, BulkProcessor bulkProcessor = null) {
String docId = getEntityId(doc)
if (!canIndex(doc)) {
deleteIfRequired(docId, index)
return
}
// The purpose of the as JSON call below is to convert Date objects into the format we use
// throughout the app - otherwise the elasticsearch XContentBuilder will transform them into
// ISO dates with milliseconds which causes BioCollect problems as it uses the _source field of the
// search result directly.
Map docMap = doc
index = index ?: DEFAULT_INDEX
// Delete index if it exists and doc.status == 'deleted'
checkForDelete(docMap, docId, index)
// Prevent deleted document from been indexed regardless of whether it has a previous index entry
if(docMap.status?.toLowerCase() == DELETED) {
return null;
}
try {
addCustomFields(docMap)
String docContent = new JSON(docMap).toString(false)
IndexRequest indexRequest = new IndexRequest(index).id(docId)
indexRequest.source(docContent, XContentType.JSON)
// If we are indexing in bulk, use the supplied request, otherwise index the doc directly.
if (bulkProcessor) {
bulkProcessor.add(indexRequest)
}
else {
client.index(indexRequest, RequestOptions.DEFAULT)
}
} catch (Exception e) {
String documentString = (docMap as JSON).toString(true)
String message = e instanceof ElasticsearchException ? e.getDetailedMessage() : e.getMessage()
log.error "Error: ${message}\nDocument:Error indexing document: ${docId}, type:${docMap['className']}"
if (Environment.current == Environment.PRODUCTION) {
String subject = "Indexing failed on server ${grailsApplication.config.getProperty('grails.serverURL')}"
String body = "Type: "+getDocType(doc)+"\n"
body += "Index: "+index+"\n"
body += "Error: "+e.getMessage()+"\n"
body += "Document: "+documentString
emailService.emailSupport(subject, body)
}
}
}
/**
* Get the doc identifier, which differs for each domain class.
*
* @param doc
* @return docId (String)
*/
def getEntityId(doc) {
IdentifierHelper.getEntityIdentifier(doc)
}
def getDocType(doc) {
String className = doc.className ?: "au.org.ala.ecodata.doc"
className.tokenize(".")[-1].toLowerCase()
}
/**
* Check if a doc has been marked as deleted.
* Returns false if the doc to be indexed exists in the search index
* and has {status: "deleted"}. Doc is deleted from search index.
*
* @param doc
* @param docId
* @return isDeleted (Boolean)
*/
def checkForDelete(doc, docId, String index = DEFAULT_INDEX) {
def isDeleted = false
if (doc.status?.toLowerCase() == DELETED) {
isDeleted = deleteIfRequired(docId, index)
}
return isDeleted
}
/** Deletes the document with the supplied id from elasticsearch if it is indexed */
boolean deleteIfRequired(String docId, String index) {
def isDeleted = false
GetResponse resp
try {
GetRequest request = new GetRequest(index, docId)
resp = client.get(request, RequestOptions.DEFAULT)
if (resp.exists) {
try {
deleteDocById(docId, index)
isDeleted = true
} catch (Exception e) {
log.error "Error deleting doc with ID ${docId}: ${e.message}"
}
}
} catch (Exception e) {
log.error "ES prepareGet error: ${e}", e
}
return isDeleted
}
/**
* Add extra (custom) fields to doc in search index.
*
* @param doc
*/
def addCustomFields(Map doc) {
// Remove the mongo id if it exists.
doc.remove("_id")
doc.remove("id")
// hand-coded copy fields with different analysers
doc.docType = getDocType(doc)
if (!doc.name && doc.type) {
// activities have no name so we'll use the type
doc.name = doc.type
}
// Add some processed lat/lon data to doc
doc.geo = []
def lat, lon
if (doc.extent?.geometry?.decimalLatitude && doc.extent?.geometry?.decimalLatitude) {
lat = doc.extent.geometry.decimalLatitude as String
lon = doc.extent.geometry.decimalLongitude as String
} else if (doc.extent?.geometry?.centre?.size() == 2) {
lat = doc.extent.geometry.centre[1] as String
lon = doc.extent.geometry.centre[0] as String
}
if (lat && lon) {
def geoObj = [:]
geoObj.siteName = doc.name
geoObj.siteId = doc.siteId
def loc = [:]
loc.lat = lat.toFloat()
loc.lon = lon.toFloat()
geoObj.loc = loc
doc.geo.add(geoObj)
}
// Homepage index is nested TODO: remove duplicate code from above
if (doc.sites?.size() > 0) {
// one or more sites to a project (deep copy)
doc.sites.each { site ->
if (site.extent?.geometry?.decimalLatitude && site.extent?.geometry?.decimalLatitude) {
lat = site.extent.geometry.decimalLatitude as String
lon = site.extent.geometry.decimalLongitude as String
} else if (site.extent?.geometry?.centre?.size() == 2) {
lat = site.extent.geometry.centre[1] as String
lon = site.extent.geometry.centre[0] as String
}
if (lat && lon) {
def geoObj = [:]
geoObj.siteName = site.name
geoObj.siteId = site.siteId
def loc = [:]
loc.lat = lat.toFloat()
loc.lon = lon.toFloat()
geoObj.loc = loc
doc.geo.add(geoObj)
}
}
}
}
/**
* Get the complete mapping that will be used by Elastic Search i.e. default mapping + custom mapping
* @return
*/
Map getMapping() {
Map parsedJson = getDefaultMapping()
parsedJson = addCustomIndicesToMapping(parsedJson)
parsedJson
}
/**
* Get default mapping from file.
* @return
*/
Map getDefaultMapping() {
cacheService.get('default-mapping-json', {
Map parsedJson = new JsonSlurper().parseText(getClass().getResourceAsStream("/data/mapping.json").getText())
def facetMappings = buildFacetMapping()
// Geometries can appear at two different locations inside a doc depending on the type (site, activity or project)
parsedJson.mappings["properties"].extent["properties"].geometry["properties"].putAll(facetMappings.properties)
parsedJson.mappings["properties"].sites["properties"].extent["properties"].geometry["properties"].putAll(facetMappings.properties)
parsedJson.mappings["properties"].putAll(facetMappings.facets)
parsedJson
})
}
/**
* Find custom mapping from data models and add them to passed mapping object.
* @param mapping
* @return
*/
Map addCustomIndicesToMapping(Map mapping){
Map indices = metadataService.getIndicesForDataModels()
indices?.each { index, fields ->
if(metadataService.isIndexValid(fields)){
if(!doesIndexExist(index, mapping)){
addCustomIndex(fields, mapping)
} else {
log.warn("Index already exists: ${index}. Ignoring it.")
}
} else {
log.warn("Index is not valid: ${index}. Ignoring it.")
}
}
mapping
}
/**
* Add an index specific properties to mapping object based on index's data type.
* @param fields
* @param mapping
* @return
*/
Map addCustomIndex(List fields, Map mapping){
Map field = fields?.get(0)
switch (field.dataType){
case 'set':
case 'text':
case 'boolean':
case 'image':
case 'Image':
case 'document':
case 'stringList':
mapping?.mappings["properties"].put(field.indexName, [
"type" : "keyword"
])
break
case 'number':
mapping?.mappings["properties"].put(field.indexName, [
"type" : "double"
])
break
case 'date':
mapping?.mappings["properties"].put(field.indexName, [
"type" : "date"
])
break
}
mapping
}
boolean doesIndexExist(String index, Map mapping){
if(mapping?.mappings["properties"].hasProperty(index)){
return true
}
false
}
def buildFacetMapping() {
def facetList = []
Map facetConfig = metadataService.getGeographicConfig()
// These groupings of facets determine the way the layers are used with a site, but can be treated the
// same for the purposes of indexing the results.
['contextual', 'grouped', 'special'].each {
facetList.addAll(facetConfig[it].collect { k, v -> k })
}
Map properties = [:]
Map facets = [:]
facetList.each { facetName ->
properties << [(facetName): [type: 'text', copy_to:facetName+"Facet"]]
facets << [(facetName + "Facet"): [type: "keyword"]]
}
[properties:properties, facets:facets]
}
/**
* Log GORM event to msg queue
*
* @param event
*/
def queueGormEvent(AbstractPersistenceEvent event) {
def doc = event.entityObject
def docType = doc.getClass().name
if (!ALLOWED_DOC_TYPES.contains(docType)) {
return
}
def docId = getEntityId(doc)
def projectIdsToUpdate = []
def message = new IndexDocMsg(docType: docType, docId: docId, indexType: event.eventType, docIds: projectIdsToUpdate)
queueIndexingEvent(message)
}
void queueIndexingEvent(IndexDocMsg msg) {
try {
_messageQueue.offer(msg)
} catch (Exception ex) {
log.error ex.localizedMessage, ex
}
}
/**
* Called by Quartz job - grabs all message on the queue and indexes
* documents with ElasticSearch. Code gist taken from AuditService.
*
* @param maxMessagesToFlush
* @return
*/
public int flushIndexMessageQueue(int maxMessagesToFlush = 1000) {
int messageCount = 0
try {
IndexDocMsg message = null;
while (messageCount < maxMessagesToFlush && (message = _messageQueue.poll()) != null) {
log.debug "Processing IndexDocMsg: ${message}"
try {
switch (message.indexType) {
case EventType.PostUpdate:
case EventType.PostInsert:
indexDocType(message.docId, message.docType)
break
case EventType.PreDelete:
case EventType.PostDelete:
deleteDocByIdAndType(message.docId, message.docType)
break
case EventType.PreUpdate:
checkDeleteForProjects(message.docIds)
break
default:
log.warn "Unexpected GORM event type: ${message.indexType}"
}
}
catch (Exception e) {
log.error "Error indexing message from message queue: ${message}", e
}
messageCount++
}
} catch (Exception ex) {
log.error "Error indexing docs from message queue: ${ex}", ex
}
return messageCount
}
/**
* Index any document type using the toMap representation of it.
* Called by {@link GormEventListener GormEventListener}.
*
* @param doc (domain object)
*/
def indexDocType(Object docId, String docType) {
// skip indexing
if (indexingTempInactive
|| !grailsApplication.config.getProperty('app.elasticsearch.indexOnGormEvents')
|| !ALLOWED_DOC_TYPES.contains(docType)) {
return null
}
switch (docType) {
case Project.class.name:
Project project = Project.findByProjectId(docId)
indexHomePage(project, docType)
break
case Site.class.name:
def doc = Site.findBySiteId(docId)
def siteMap = siteService.toMap(doc, SiteService.FLAT)
siteMap["className"] = docType
siteMap = prepareSiteForIndexing(siteMap, true)
if (siteMap) {
indexDoc(siteMap, DEFAULT_INDEX)
}
doc?.projects?.each { projectId ->
Project proj = Project.findByProjectId(projectId)
indexHomePage(proj, Project.class.name)
}
break
case Record.class.name:
Record record = Record.findByOccurrenceID(docId)
if(record) {
Activity activity = Activity.findByActivityId(record.activityId)
if (activity) {
def doc = activityService.toMap(activity, ActivityService.FLAT)
doc = prepareActivityForIndexing(doc)
indexDoc(doc, (doc?.projectActivityId || doc?.isWorks) ? PROJECT_ACTIVITY_INDEX : DEFAULT_INDEX)
}
else {
log.warn("No activity found with id ${record.activityId} when indexing record for project ${record.projectId} and survey ${record.projectActivityId}")
}
}
break
case Output.class.name:
Output output = Output.findByOutputId(docId)
if (output) {
indexDocType(output.activityId, Activity.class.name)
}
break
case Activity.class.name:
Activity activity = Activity.findByActivityId(docId)
def doc = activityService.toMap(activity, ActivityService.FLAT)
doc = prepareActivityForIndexing(doc)
// Works project activities are created before a survey is filled in
indexDoc(doc, (doc?.projectActivityId || doc?.isWorks) ? PROJECT_ACTIVITY_INDEX : DEFAULT_INDEX)
// update linked project -- index for homepage
def pDoc = Project.findByProjectId(doc.projectId)
if (pDoc) {
indexHomePage(pDoc, Project.class.name)
}
if(activity.siteId){
indexDocType(activity.siteId, Site.class.name)
}
break
case Document.class.name:
Map document = documentService.getByStatus(docId)
document = prepareDocumentForIndexing(document)
document ? indexDoc(document, DEFAULT_INDEX) : null
break
case Organisation.class.name:
Map organisation = organisationService.get(docId)
prepareOrganisationForIndexing(organisation)
indexDoc(organisation, DEFAULT_INDEX)
break
case UserPermission.class.name:
String projectId = UserPermission.findByIdAndEntityType(docId, Project.class.name)?.getEntityId()
if (projectId) {
Project doc = Project.findByProjectId(projectId)
indexHomePage(doc, Project.class.name)
}
break
}
}
private boolean canIndex(Map doc) {
return doc?.visibility != 'private'
}
/**
* Add additional data to site for indexing purposes. eg. project, photo point, survey name etc.
* @param siteMap
* @param indexNestedDocuments
* @return
*/
private Map prepareSiteForIndexing(Map siteMap, Boolean indexNestedDocuments) {
List projects = [], surveys = []
if(siteMap.projects){
List allProjects = Project.createCriteria().list {
'in'('projectId', siteMap.projects)
ne('isMERIT', true)
}
projects.addAll(allProjects.collect { project ->
if(indexNestedDocuments){
indexHomePage(project, "au.org.ala.ecodata.Project")
}
[
projectName: project.name,
projectId : project.projectId,
projectType: project?.projectType
]
})
List surveysForProject = ProjectActivity.findAllByProjectIdInList(siteMap.projects);
surveys.addAll(surveysForProject.collect {
[
surveyName : it.name,
projectActivityId: it.projectActivityId
]
})
}
siteMap.projectList = projects;
siteMap.surveyList = surveys
addYearAndMonthToEntity(siteMap, siteMap)
Document doc = Document.findByRoleAndSiteIdAndType('photoPoint', siteMap.siteId, 'image')
if (doc) {
siteMap.photoType = 'photoPoint'
}
// Don't include orphan sites or MERIT sites.
siteMap.projectList ? siteMap : null
}
/**
* Update index for home page (projects with sites)
*
* @param doc
* @param docType
*/
def indexHomePage(doc, docType) {
// homepage index - turned off due to triggering recursive POST INSERT events for some reason
try {
def docId = getEntityId(doc)
// Prevent deleted document from been indexed regardless of whether it has a previous index entry
if(doc.status?.toLowerCase() == DELETED) {
// Delete index if it exists and doc.status == 'deleted'
checkForDelete(doc, docId, HOMEPAGE_INDEX)
return null;
}
def projectMapDeep = prepareProjectForHomePageIndex(doc)
projectMapDeep["className"] = docType
indexDoc(projectMapDeep, HOMEPAGE_INDEX)
} catch (StackOverflowError e) {
log.error "SO error - indexDocType for ${doc.projectId}: ${e.message}", e
} catch (Exception e) {
log.error "Exception - indexDocType for ${doc?.projectId}: ${e.message}", e
}
}
/**
* Delete doc from search main index.
*
* @param doc (domain object)
*/
def deleteDocType(doc) {
def docId = getEntityId(doc)
// skip indexing
if (indexingTempInactive
|| !grailsApplication.config.getProperty('app.elasticsearch.indexOnGormEvents')
|| !ALLOWED_DOC_TYPES.contains(doc.getClass().name)) {
return null
}
// delete from index
def resp = checkForDelete(doc, docId)
log.info "Delete from index for ${doc}: ${resp} "
}
/**
* Delete doc from search index - by doc id and type
*
* @param docId
* @param docType
* @return
*/
def deleteDocByIdAndType(docId, docType) {
def doc
try{
switch (docType) {
case Activity.class.name:
deleteDocById(docId, PROJECT_ACTIVITY_INDEX)
deleteDocById(docId)
break
case Project.class.name:
deleteDocById(docId, HOMEPAGE_INDEX)
case Site.class.name:
case Organisation.class.name:
deleteDocById(docId)
}
} catch (Exception e){
log.warn "Attempting to delete an unknown doc type: ${docType}. Doc not deleted from search index"
log.error(e.message)
e.stackTrace()
}
}
/**
* If an activity or site is deleted we need to keep track of the owning project (id)
* and then re-index those projects.
*
* @param docIds
* @return
*/
def checkDeleteForProjects(docIds) {
// docIds is assumed to be a list of ProjectIds
docIds.each { id ->
//log.debug "Updating project id: ${id}"
indexDocType(id, Project.class.name)
}
}
def indexDependenciesOfProjects(List projectIds) {
log.info("Started indexing of projects: ${projectIds}")
projectIds?.each { projectId ->
log.debug("Started indexing assets of project: ${projectId}")
indexDependenciesOfProject(projectId)
log.debug("Indexed assets of project: ${projectId}")
}
log.info("Completed indexing of projects: ${projectIds}")
}
def indexDependenciesOfProject (String projectId) {
int batchSize = 50
log.debug "Indexing project"
Project.withNewSession { session ->
Project project = Project.findByProjectIdAndStatusNotEqual(projectId, DELETED)
try {
Map projectMap = prepareProjectForHomePageIndex(project)
indexDoc(projectMap, HOMEPAGE_INDEX)
}
catch (Exception e) {
log.error("Unable to index project: " + project?.projectId, e)
}
log.debug "Indexing sites"
int count = 0
siteService.doWithAllSites({ siteMap ->
siteMap["className"] = Site.class.name
try {
siteMap = prepareSiteForIndexing(siteMap, false)
if (siteMap) {
indexDoc(siteMap, DEFAULT_INDEX)
}
}
catch (Exception e) {
log.error("Unable index site: " + siteMap?.siteId, e)
}
count++
if (count % 1000 == 0) {
session.clear()
log.info("Processed " + count + " sites")
}
}, [Filters.eq('projectId', projectId)], batchSize)
if (project.organisationId) {
log.debug "Indexing organisations of project"
organisationService.doWithAllOrganisations ({ Map org ->
try {
prepareOrganisationForIndexing(org)
indexDoc(org, DEFAULT_INDEX)
}
catch (Exception e) {
log.error("Unable to index organisation: " + org?.organisationId, e)
}
}, [Filters.eq('organisationId', project.organisationId)], batchSize)
}
log.debug "Indexing activities"
count = 0
activityService.doWithAllActivities({ Map activity ->
try {
activity = prepareActivityForIndexing(activity)
indexDoc(activity, activity?.projectActivityId || activity?.isWorks ? PROJECT_ACTIVITY_INDEX : DEFAULT_INDEX)
}
catch (Exception e) {
log.error("Unable to index activity: " + activity?.activityId, e)
}
count++
if (count % 1000 == 0) {
session.clear()
log.info("Processed " + count + " activities")
}
}, [Filters.eq('projectId', projectId)], batchSize)
log.debug "Indexing documents"
count = 0
Document.findAllByProjectIdAndStatusNotEqual(projectId, DELETED, [batchSize: batchSize]).each { Document document ->
try {
Map doc = documentService.toMap(document)
doc = prepareDocumentForIndexing(doc)
if (doc) {
indexDoc(doc, DEFAULT_INDEX)
}
}
catch (Exception e) {
log.error("Unable to index document: " + doc?.documentId, e)
}
count++
if (count % 100 == 0) {
session.clear()
log.info("Processed " + count + " documents")
}
}
}
}
Promise reindexProjectsWithCriteriaAsync(Map searchCriteriaParams) {
Promises.task {
indexProjectsWithCriteria(searchCriteriaParams)
}
}
/**
* This method will re-index (in the current live search index) a set of Projects identified by
* the supplied criteria. It should not be used for large re-indexing tasks.
* @param searchCriteriaParams
* @return the number projects indexed.
*/
int indexProjectsWithCriteria(Map searchCriteriaParams) {
BulkProcessor.Listener listener = new LoggingBulkIndexingListener()
BulkProcessor bulkProcessor = BulkProcessor.builder(
{ request, bulkListener ->
client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener) } as BiConsumer, listener, "ecodata-project-indexing"
).build()
int count = 0
Closure query = { Map batchOptions ->
BuildableCriteria searchCriteria = Project.createCriteria()
searchCriteria.list(batchOptions) {
ne("status", DELETED)
searchCriteriaParams.each { prop, value ->
if (value instanceof List) {
inList(prop, value)
} else {
eq(prop, value)
}
}
}
}
Project.withNewSession {
def batchParams = [offset: 0, max: 50, sort: 'projectId']
List projects = query(batchParams)
while (projects) {
projects.each { project ->
try {
Map projectMap = prepareProjectForHomePageIndex(project)
indexDoc(projectMap,HOMEPAGE_INDEX, bulkProcessor)
count++
}
catch (Exception e) {
log.error("Unable to index project: " + project?.projectId, e)
}
}
batchParams.offset = batchParams.offset + batchParams.max
projects = query(batchParams)
log.info("Processed " + batchParams.offset + " projects")
}
}
bulkProcessor.close()
count
}
@Slf4j
static class LoggingBulkIndexingListener implements BulkProcessor.Listener {
int bulkIndexCount = 0
int lastReportedIndexCount = 0
int progressLogThreshold = 1000
@Override
void beforeBulk(long executionId, BulkRequest request) {}
@Override
void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
bulkIndexCount += request.numberOfActions()
if (bulkIndexCount - lastReportedIndexCount > progressLogThreshold) {
log.info("Bulk indexed "+bulkIndexCount+" documents")
lastReportedIndexCount = bulkIndexCount
}
if (response.hasFailures()) {
log.warn(response.buildFailureMessage())
}
}
@Override
void afterBulk(long executionId, BulkRequest request, Throwable failure) {
log.error("Error executing bulk indexing", failure)
}
}
/**
* Index all documents. Index is cleared first.
*/
def indexAll() {
log.debug "Clearing the unused index first"
indexManager.setMapping(mapping.mappings)
Map newIndexes = indexManager.recreateUnusedIndexes()
// homepage index (doing some manual batching due to memory constraints)
log.info "Indexing all MERIT and NON-MERIT projects in generic HOMEPAGE index"
BulkProcessor.Listener listener = new LoggingBulkIndexingListener()
BulkProcessor bulkProcessor = BulkProcessor.builder(
{ request, bulkListener ->
client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener) } as BiConsumer, listener, "ecodata-indexing"
).build()
Project.withNewSession {
def batchParams = [offset: 0, max: 50, sort: 'projectId']
def projects = Project.findAllByStatusNotEqual(DELETED, batchParams)
while (projects) {