/
SearchResponderV2.scala
1052 lines (903 loc) · 49.4 KB
/
SearchResponderV2.scala
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 © 2015-2019 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi.responders.v2
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import org.knora.webapi._
import org.knora.webapi.exceptions.{
AssertionException,
BadRequestException,
GravsearchException,
InconsistentRepositoryDataException
}
import org.knora.webapi.feature.FeatureFactoryConfig
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.util.ConstructResponseUtilV2.MappingAndXSLTransformation
import org.knora.webapi.messages.util.rdf.{SparqlSelectResult, SparqlSelectResultBody, VariableResultsRow}
import org.knora.webapi.messages.util.search._
import org.knora.webapi.messages.util.search.gravsearch.GravsearchQueryChecker
import org.knora.webapi.messages.util.search.gravsearch.prequery.{
AbstractPrequeryGenerator,
NonTriplestoreSpecificGravsearchToCountPrequeryTransformer,
NonTriplestoreSpecificGravsearchToPrequeryTransformer
}
import org.knora.webapi.messages.util.search.gravsearch.types._
import org.knora.webapi.messages.util.standoff.StandoffTagUtilV2
import org.knora.webapi.messages.util.{ConstructResponseUtilV2, ErrorHandlingMap, ResponderData}
import org.knora.webapi.messages.v2.responder.KnoraJsonLDResponseV2
import org.knora.webapi.messages.v2.responder.ontologymessages.{
EntityInfoGetRequestV2,
EntityInfoGetResponseV2,
ReadClassInfoV2,
ReadPropertyInfoV2
}
import org.knora.webapi.messages.v2.responder.resourcemessages._
import org.knora.webapi.messages.v2.responder.searchmessages._
import org.knora.webapi.messages.{OntologyConstants, SmartIri, StringFormatter}
import org.knora.webapi.responders.Responder.handleUnexpectedMessage
import org.knora.webapi.util.ApacheLuceneSupport._
import scala.concurrent.Future
class SearchResponderV2(responderData: ResponderData) extends ResponderWithStandoffV2(responderData) {
// A Gravsearch type inspection runner.
private val gravsearchTypeInspectionRunner = new GravsearchTypeInspectionRunner(responderData)
/**
* Receives a message of type [[SearchResponderRequestV2]], and returns an appropriate response message.
*/
def receive(msg: SearchResponderRequestV2): Future[KnoraJsonLDResponseV2] = msg match {
case FullTextSearchCountRequestV2(searchValue,
limitToProject,
limitToResourceClass,
limitToStandoffClass,
featureFactoryConfig,
requestingUser) =>
fulltextSearchCountV2(searchValue,
limitToProject,
limitToResourceClass,
limitToStandoffClass,
featureFactoryConfig,
requestingUser)
case FulltextSearchRequestV2(searchValue,
offset,
limitToProject,
limitToResourceClass,
limitToStandoffClass,
returnFiles,
targetSchema,
schemaOptions,
featureFactoryConfig,
requestingUser) =>
fulltextSearchV2(
searchValue,
offset,
limitToProject,
limitToResourceClass,
limitToStandoffClass,
returnFiles,
targetSchema,
schemaOptions,
featureFactoryConfig,
requestingUser
)
case GravsearchCountRequestV2(query, featureFactoryConfig, requestingUser) =>
gravsearchCountV2(inputQuery = query,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser)
case GravsearchRequestV2(query, targetSchema, schemaOptions, featureFactoryConfig, requestingUser) =>
gravsearchV2(inputQuery = query,
targetSchema = targetSchema,
schemaOptions = schemaOptions,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser)
case SearchResourceByLabelCountRequestV2(searchValue,
limitToProject,
limitToResourceClass,
featureFactoryConfig,
requestingUser) =>
searchResourcesByLabelCountV2(searchValue,
limitToProject,
limitToResourceClass,
featureFactoryConfig,
requestingUser)
case SearchResourceByLabelRequestV2(searchValue,
offset,
limitToProject,
limitToResourceClass,
targetSchema,
featureFactoryConfig,
requestingUser) =>
searchResourcesByLabelV2(searchValue,
offset,
limitToProject,
limitToResourceClass,
targetSchema,
featureFactoryConfig,
requestingUser)
case resourcesInProjectGetRequestV2: SearchResourcesByProjectAndClassRequestV2 =>
searchResourcesByProjectAndClassV2(resourcesInProjectGetRequestV2)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/**
* Performs a fulltext search and returns the resources count (how many resources match the search criteria),
* without taking into consideration permission checking.
*
* This method does not return the resources themselves.
*
* @param searchValue the values to search for.
* @param limitToProject limit search to given project.
* @param limitToResourceClass limit search to given resource class.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ResourceCountV2]] representing the number of resources that have been found.
*/
private def fulltextSearchCountV2(searchValue: String,
limitToProject: Option[IRI],
limitToResourceClass: Option[SmartIri],
limitToStandoffClass: Option[SmartIri],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ResourceCountV2] = {
val searchTerms: LuceneQueryString = LuceneQueryString(searchValue)
for {
countSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.searchFulltext(
triplestore = settings.triplestoreType,
searchTerms = searchTerms,
limitToProject = limitToProject,
limitToResourceClass = limitToResourceClass.map(_.toString),
limitToStandoffClass = limitToStandoffClass.map(_.toString),
returnFiles = false, // not relevant for a count query
separator = None, // no separator needed for count query
limit = 1,
offset = 0,
countQuery = true // do not get the resources themselves, but the sum of results
)
.toString())
// _ = println(countSparql)
countResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(countSparql)).mapTo[SparqlSelectResult]
// query response should contain one result with one row with the name "count"
_ = if (countResponse.results.bindings.length != 1) {
throw GravsearchException(
s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given")
}
count = countResponse.results.bindings.head.rowMap("count")
} yield ResourceCountV2(numberOfResources = count.toInt)
}
/**
* Performs a fulltext search (simple search).
*
* @param searchValue the values to search for.
* @param offset the offset to be used for paging.
* @param limitToProject limit search to given project.
* @param limitToResourceClass limit search to given resource class.
* @param returnFiles if true, return any file value attached to each matching resource.
* @param targetSchema the target API schema.
* @param schemaOptions the schema options submitted with the request.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ReadResourcesSequenceV2]] representing the resources that have been found.
*/
private def fulltextSearchV2(searchValue: String,
offset: Int,
limitToProject: Option[IRI],
limitToResourceClass: Option[SmartIri],
limitToStandoffClass: Option[SmartIri],
returnFiles: Boolean,
targetSchema: ApiV2Schema,
schemaOptions: Set[SchemaOption],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ReadResourcesSequenceV2] = {
import org.knora.webapi.messages.util.search.FullTextMainQueryGenerator.FullTextSearchConstants
val groupConcatSeparator = StringFormatter.INFORMATION_SEPARATOR_ONE
val searchTerms: LuceneQueryString = LuceneQueryString(searchValue)
for {
searchSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.searchFulltext(
triplestore = settings.triplestoreType,
searchTerms = searchTerms,
limitToProject = limitToProject,
limitToResourceClass = limitToResourceClass.map(_.toString),
limitToStandoffClass = limitToStandoffClass.map(_.toString),
returnFiles = returnFiles,
separator = Some(groupConcatSeparator),
limit = settings.v2ResultsPerPage,
offset = offset * settings.v2ResultsPerPage, // determine the actual offset
countQuery = false
)
.toString())
// _ = println(searchSparql)
prequeryResponseNotMerged: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(searchSparql))
.mapTo[SparqlSelectResult]
// _ = println(prequeryResponseNotMerged)
mainResourceVar = QueryVariable("resource")
// Merge rows with the same resource IRI.
prequeryResponse = mergePrequeryResults(prequeryResponseNotMerged, mainResourceVar)
// a sequence of resource IRIs that match the search criteria
// attention: no permission checking has been done so far
resourceIris: Seq[IRI] = prequeryResponse.results.bindings.map { resultRow: VariableResultsRow =>
resultRow.rowMap(FullTextSearchConstants.resourceVar.variableName)
}
// If the prequery returned some results, prepare a main query.
mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- if (resourceIris.nonEmpty) {
// for each resource, create a Set of value object IRIs
val valueObjectIrisPerResource: Map[IRI, Set[IRI]] =
prequeryResponse.results.bindings.foldLeft(Map.empty[IRI, Set[IRI]]) {
(acc: Map[IRI, Set[IRI]], resultRow: VariableResultsRow) =>
val mainResIri: IRI = resultRow.rowMap(FullTextSearchConstants.resourceVar.variableName)
resultRow.rowMap.get(FullTextSearchConstants.valueObjectConcatVar.variableName) match {
case Some(valObjIris) =>
// Filter out empty IRIs (which we could get if a variable used in GROUP_CONCAT is unbound)
acc + (mainResIri -> valObjIris.split(groupConcatSeparator).toSet.filterNot(_.isEmpty))
case None => acc
}
}
// println(valueObjectIrisPerResource)
// collect all value object IRIs
val allValueObjectIris = valueObjectIrisPerResource.values.flatten.toSet
// create a CONSTRUCT query to query resources and their values
val mainQuery = FullTextMainQueryGenerator.createMainQuery(
resourceIris = resourceIris.toSet,
valueObjectIris = allValueObjectIris,
targetSchema = targetSchema,
schemaOptions = schemaOptions,
settings = settings
)
val triplestoreSpecificQueryPatternTransformerConstruct: ConstructToConstructTransformer = {
if (settings.triplestoreType.startsWith("graphdb")) {
// GraphDB
new SparqlTransformer.GraphDBConstructToConstructTransformer
} else {
// Other
new SparqlTransformer.NoInferenceConstructToConstructTransformer
}
}
val triplestoreSpecificQuery = QueryTraverser.transformConstructToConstruct(
inputQuery = mainQuery,
transformer = triplestoreSpecificQueryPatternTransformerConstruct
)
// println(triplestoreSpecificQuery.toSparql)
for {
searchResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = triplestoreSpecificQuery.toSparql,
featureFactoryConfig = featureFactoryConfig
)).mapTo[SparqlExtendedConstructResponse]
// separate resources and value objects
queryResultsSep: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2
.splitMainResourcesAndValueRdfData(constructQueryResults = searchResponse, requestingUser = requestingUser)
} yield queryResultsSep
} else {
// the prequery returned no results, no further query is necessary
Future(
ConstructResponseUtilV2.MainResourcesAndValueRdfData(resources = Map.empty)
)
}
// Find out whether to query standoff along with text values. This boolean value will be passed to
// ConstructResponseUtilV2.makeTextValueContentV2.
queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues(targetSchema = targetSchema,
schemaOptions = schemaOptions)
// If we're querying standoff, get XML-to standoff mappings.
mappingsAsMap: Map[IRI, MappingAndXSLTransformation] <- if (queryStandoff) {
getMappingsFromQueryResultsSeparated(
queryResultsSeparated = mainResourcesAndValueRdfData.resources,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
} else {
FastFuture.successful(Map.empty[IRI, MappingAndXSLTransformation])
}
// _ = println(mappingsAsMap)
apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse(
mainResourcesAndValueRdfData = mainResourcesAndValueRdfData,
orderByResourceIri = resourceIris,
pageSizeBeforeFiltering = resourceIris.size,
mappings = mappingsAsMap,
queryStandoff = queryStandoff,
calculateMayHaveMoreResults = true,
versionDate = None,
responderManager = responderManager,
settings = settings,
targetSchema = targetSchema,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
} yield apiResponse
}
/**
* Performs a count query for a Gravsearch query provided by the user.
*
* @param inputQuery a Gravsearch query provided by the client.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ResourceCountV2]] representing the number of resources that have been found.
*/
private def gravsearchCountV2(inputQuery: ConstructQuery,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ResourceCountV2] = {
// make sure that OFFSET is 0
if (inputQuery.offset != 0)
throw GravsearchException(s"OFFSET must be 0 for a count query, but ${inputQuery.offset} given")
for {
// Do type inspection and remove type annotations from the WHERE clause.
typeInspectionResult: GravsearchTypeInspectionResult <- gravsearchTypeInspectionRunner.inspectTypes(
inputQuery.whereClause,
requestingUser)
whereClauseWithoutAnnotations: WhereClause = GravsearchTypeInspectionUtil.removeTypeAnnotations(
inputQuery.whereClause)
// Validate schemas and predicates in the CONSTRUCT clause.
_ = GravsearchQueryChecker.checkConstructClause(
constructClause = inputQuery.constructClause,
typeInspectionResult = typeInspectionResult
)
// Create a Select prequery
nonTriplestoreSpecificConstructToSelectTransformer: NonTriplestoreSpecificGravsearchToCountPrequeryTransformer = new NonTriplestoreSpecificGravsearchToCountPrequeryTransformer(
constructClause = inputQuery.constructClause,
typeInspectionResult = typeInspectionResult,
querySchema = inputQuery.querySchema.getOrElse(throw AssertionException(s"WhereClause has no querySchema"))
)
nonTriplestoreSpecficPrequery: SelectQuery = QueryTraverser.transformConstructToSelect(
inputQuery = inputQuery.copy(
whereClause = whereClauseWithoutAnnotations,
orderBy = Seq.empty[OrderCriterion] // count queries do not need any sorting criteria
),
transformer = nonTriplestoreSpecificConstructToSelectTransformer
)
// Convert the non-triplestore-specific query to a triplestore-specific one.
triplestoreSpecificQueryPatternTransformerSelect: SelectToSelectTransformer = {
if (settings.triplestoreType.startsWith("graphdb")) {
// GraphDB
new SparqlTransformer.GraphDBSelectToSelectTransformer(
useInference = nonTriplestoreSpecificConstructToSelectTransformer.useInference
)
} else {
// Other
new SparqlTransformer.NoInferenceSelectToSelectTransformer(
simulateInference = nonTriplestoreSpecificConstructToSelectTransformer.useInference
)
}
}
triplestoreSpecificCountQuery = QueryTraverser.transformSelectToSelect(
inputQuery = nonTriplestoreSpecficPrequery,
transformer = triplestoreSpecificQueryPatternTransformerSelect
)
// _ = println(triplestoreSpecificCountQuery.toSparql)
countResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(triplestoreSpecificCountQuery.toSparql))
.mapTo[SparqlSelectResult]
// query response should contain one result with one row with the name "count"
_ = if (countResponse.results.bindings.length != 1) {
throw GravsearchException(
s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given")
}
count: String = countResponse.results.bindings.head.rowMap("count")
} yield ResourceCountV2(numberOfResources = count.toInt)
}
/**
* Performs a search using a Gravsearch query provided by the client.
*
* @param inputQuery a Gravsearch query provided by the client.
* @param targetSchema the target API schema.
* @param schemaOptions the schema options submitted with the request.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ReadResourcesSequenceV2]] representing the resources that have been found.
*/
private def gravsearchV2(inputQuery: ConstructQuery,
targetSchema: ApiV2Schema,
schemaOptions: Set[SchemaOption],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ReadResourcesSequenceV2] = {
import org.knora.webapi.messages.util.search.gravsearch.mainquery.GravsearchMainQueryGenerator
for {
// Do type inspection and remove type annotations from the WHERE clause.
typeInspectionResult: GravsearchTypeInspectionResult <- gravsearchTypeInspectionRunner.inspectTypes(
inputQuery.whereClause,
requestingUser)
whereClauseWithoutAnnotations: WhereClause = GravsearchTypeInspectionUtil.removeTypeAnnotations(
inputQuery.whereClause)
// Validate schemas and predicates in the CONSTRUCT clause.
_ = GravsearchQueryChecker.checkConstructClause(
constructClause = inputQuery.constructClause,
typeInspectionResult = typeInspectionResult
)
// Create a Select prequery
nonTriplestoreSpecificConstructToSelectTransformer: NonTriplestoreSpecificGravsearchToPrequeryTransformer = new NonTriplestoreSpecificGravsearchToPrequeryTransformer(
constructClause = inputQuery.constructClause,
typeInspectionResult = typeInspectionResult,
querySchema = inputQuery.querySchema.getOrElse(throw AssertionException(s"WhereClause has no querySchema")),
settings = settings
)
// TODO: if the ORDER BY criterion is a property whose occurrence is not 1, then the logic does not work correctly
// TODO: the ORDER BY criterion has to be included in a GROUP BY statement, returning more than one row if property occurs more than once
nonTriplestoreSpecificPrequery: SelectQuery = QueryTraverser.transformConstructToSelect(
inputQuery = inputQuery.copy(whereClause = whereClauseWithoutAnnotations),
transformer = nonTriplestoreSpecificConstructToSelectTransformer
)
// variable representing the main resources
mainResourceVar: QueryVariable = nonTriplestoreSpecificConstructToSelectTransformer.mainResourceVariable
// Convert the non-triplestore-specific query to a triplestore-specific one.
triplestoreSpecificQueryPatternTransformerSelect: SelectToSelectTransformer = {
if (settings.triplestoreType.startsWith("graphdb")) {
// GraphDB
new SparqlTransformer.GraphDBSelectToSelectTransformer(
useInference = nonTriplestoreSpecificConstructToSelectTransformer.useInference
)
} else {
// Other
new SparqlTransformer.NoInferenceSelectToSelectTransformer(
simulateInference = nonTriplestoreSpecificConstructToSelectTransformer.useInference
)
}
}
// Convert the preprocessed query to a non-triplestore-specific query.
triplestoreSpecificPrequery = QueryTraverser.transformSelectToSelect(
inputQuery = nonTriplestoreSpecificPrequery,
transformer = triplestoreSpecificQueryPatternTransformerSelect
)
triplestoreSpecificPrequerySparql = triplestoreSpecificPrequery.toSparql
_ = log.debug(triplestoreSpecificPrequerySparql)
prequeryResponseNotMerged: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(
triplestoreSpecificPrequerySparql)).mapTo[SparqlSelectResult]
pageSizeBeforeFiltering: Int = prequeryResponseNotMerged.results.bindings.size
// Merge rows with the same main resource IRI. This could happen if there are unbound variables in a UNION.
prequeryResponse = mergePrequeryResults(prequeryResponseNotMerged = prequeryResponseNotMerged,
mainResourceVar = mainResourceVar)
// a sequence of resource IRIs that match the search criteria
// attention: no permission checking has been done so far
mainResourceIris: Seq[IRI] = prequeryResponse.results.bindings.map { resultRow: VariableResultsRow =>
resultRow.rowMap(mainResourceVar.variableName)
}
mainQueryResults: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- if (mainResourceIris.nonEmpty) {
// at least one resource matched the prequery
// get all the IRIs for variables representing dependent resources per main resource
val dependentResourceIrisPerMainResource: GravsearchMainQueryGenerator.DependentResourcesPerMainResource =
GravsearchMainQueryGenerator.getDependentResourceIrisPerMainResource(
prequeryResponse = prequeryResponse,
transformer = nonTriplestoreSpecificConstructToSelectTransformer,
mainResourceVar = mainResourceVar
)
// collect all variables representing resources
val allResourceVariablesFromTypeInspection: Set[QueryVariable] = typeInspectionResult.entities.collect {
case (queryVar: TypeableVariable, nonPropTypeInfo: NonPropertyTypeInfo) if nonPropTypeInfo.isResourceType =>
QueryVariable(queryVar.variableName)
}.toSet
// the user may have defined IRIs of dependent resources in the input query (type annotations)
// only add them if they are mentioned in a positive context (not negated like in a FILTER NOT EXISTS or MINUS)
val dependentResourceIrisFromTypeInspection: Set[IRI] = typeInspectionResult.entities.collect {
case (iri: TypeableIri, _: NonPropertyTypeInfo)
if whereClauseWithoutAnnotations.positiveEntities.contains(IriRef(iri.iri)) =>
iri.iri.toString
}.toSet
// the IRIs of all dependent resources for all main resources
val allDependentResourceIris
: Set[IRI] = dependentResourceIrisPerMainResource.dependentResourcesPerMainResource.values.flatten.toSet ++ dependentResourceIrisFromTypeInspection
// for each main resource, create a Map of value object variables and their Iris
val valueObjectVarsAndIrisPerMainResource: GravsearchMainQueryGenerator.ValueObjectVariablesAndValueObjectIris =
GravsearchMainQueryGenerator.getValueObjectVarsAndIrisPerMainResource(
prequeryResponse = prequeryResponse,
transformer = nonTriplestoreSpecificConstructToSelectTransformer,
mainResourceVar = mainResourceVar
)
// collect all value objects IRIs (for all main resources and for all value object variables)
val allValueObjectIris: Set[IRI] =
valueObjectVarsAndIrisPerMainResource.valueObjectVariablesAndValueObjectIris.values.foldLeft(Set.empty[IRI]) {
case (acc: Set[IRI], valObjIrisForQueryVar: Map[QueryVariable, Set[IRI]]) =>
acc ++ valObjIrisForQueryVar.values.flatten.toSet
}
// create the main query
// it is a Union of two sets: the main resources and the dependent resources
val mainQuery: ConstructQuery = GravsearchMainQueryGenerator.createMainQuery(
mainResourceIris = mainResourceIris.map(iri => IriRef(iri.toSmartIri)).toSet,
dependentResourceIris = allDependentResourceIris.map(iri => IriRef(iri.toSmartIri)),
valueObjectIris = allValueObjectIris,
targetSchema = targetSchema,
schemaOptions = schemaOptions,
settings = settings
)
val triplestoreSpecificQueryPatternTransformerConstruct: ConstructToConstructTransformer = {
if (settings.triplestoreType.startsWith("graphdb")) {
// GraphDB
new SparqlTransformer.GraphDBConstructToConstructTransformer
} else {
// Other
new SparqlTransformer.NoInferenceConstructToConstructTransformer
}
}
val triplestoreSpecificMainQuery = QueryTraverser.transformConstructToConstruct(
inputQuery = mainQuery,
transformer = triplestoreSpecificQueryPatternTransformerConstruct
)
// Convert the result to a SPARQL string and send it to the triplestore.
val triplestoreSpecificMainQuerySparql: String = triplestoreSpecificMainQuery.toSparql
log.debug(triplestoreSpecificMainQuerySparql)
for {
mainQueryResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = triplestoreSpecificMainQuerySparql,
featureFactoryConfig = featureFactoryConfig,
)).mapTo[SparqlExtendedConstructResponse]
// Filter out values that the user doesn't have permission to see.
queryResultsFilteredForPermissions: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2
.splitMainResourcesAndValueRdfData(
constructQueryResults = mainQueryResponse,
requestingUser = requestingUser
)
// filter out those value objects that the user does not want to be returned by the query (not present in the input query's CONSTRUCT clause)
queryResWithFullGraphPatternOnlyRequestedValues: Map[IRI, ConstructResponseUtilV2.ResourceWithValueRdfData] = MainQueryResultProcessor
.getRequestedValuesFromResultsWithFullGraphPattern(
queryResultsFilteredForPermissions.resources,
valueObjectVarsAndIrisPerMainResource,
allResourceVariablesFromTypeInspection,
dependentResourceIrisFromTypeInspection,
nonTriplestoreSpecificConstructToSelectTransformer,
typeInspectionResult,
inputQuery
)
} yield
queryResultsFilteredForPermissions.copy(
resources = queryResWithFullGraphPatternOnlyRequestedValues
)
} else {
// the prequery returned no results, no further query is necessary
Future(ConstructResponseUtilV2.MainResourcesAndValueRdfData(resources = Map.empty))
}
// Find out whether to query standoff along with text values. This boolean value will be passed to
// ConstructResponseUtilV2.makeTextValueContentV2.
queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues(targetSchema = targetSchema,
schemaOptions = schemaOptions)
// If we're querying standoff, get XML-to standoff mappings.
mappingsAsMap: Map[IRI, MappingAndXSLTransformation] <- if (queryStandoff) {
getMappingsFromQueryResultsSeparated(
queryResultsSeparated = mainQueryResults.resources,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
} else {
FastFuture.successful(Map.empty[IRI, MappingAndXSLTransformation])
}
apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse(
mainResourcesAndValueRdfData = mainQueryResults,
orderByResourceIri = mainResourceIris,
pageSizeBeforeFiltering = pageSizeBeforeFiltering,
mappings = mappingsAsMap,
queryStandoff = queryStandoff,
versionDate = None,
calculateMayHaveMoreResults = true,
responderManager = responderManager,
settings = settings,
targetSchema = targetSchema,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
} yield apiResponse
}
/**
* Gets resources from a project.
*
* @param resourcesInProjectGetRequestV2 the request message.
* @return a [[ReadResourcesSequenceV2]].
*/
private def searchResourcesByProjectAndClassV2(
resourcesInProjectGetRequestV2: SearchResourcesByProjectAndClassRequestV2): Future[ReadResourcesSequenceV2] = {
val internalClassIri = resourcesInProjectGetRequestV2.resourceClass.toOntologySchema(InternalSchema)
val maybeInternalOrderByPropertyIri: Option[SmartIri] =
resourcesInProjectGetRequestV2.orderByProperty.map(_.toOntologySchema(InternalSchema))
for {
// Get information about the resource class, and about the ORDER BY property if specified.
entityInfoResponse: EntityInfoGetResponseV2 <- {
responderManager ? EntityInfoGetRequestV2(
classIris = Set(internalClassIri),
propertyIris = maybeInternalOrderByPropertyIri.toSet,
requestingUser = resourcesInProjectGetRequestV2.requestingUser
)
}.mapTo[EntityInfoGetResponseV2]
classDef: ReadClassInfoV2 = entityInfoResponse.classInfoMap(internalClassIri)
// If an ORDER BY property was specified, determine which subproperty of knora-base:valueHas to use to get the
// literal value to sort by.
maybeOrderByValuePredicate: Option[SmartIri] = maybeInternalOrderByPropertyIri match {
case Some(internalOrderByPropertyIri) =>
val internalOrderByPropertyDef: ReadPropertyInfoV2 =
entityInfoResponse.propertyInfoMap(internalOrderByPropertyIri)
// Ensure that the ORDER BY property is one that we can sort by.
if (!internalOrderByPropertyDef.isResourceProp || internalOrderByPropertyDef.isLinkProp || internalOrderByPropertyDef.isLinkValueProp || internalOrderByPropertyDef.isFileValueProp) {
throw BadRequestException(s"Cannot sort by property <${resourcesInProjectGetRequestV2.orderByProperty}>")
}
// Ensure that the resource class has a cardinality on the ORDER BY property.
if (!classDef.knoraResourceProperties.contains(internalOrderByPropertyIri)) {
throw BadRequestException(
s"Class <${resourcesInProjectGetRequestV2.resourceClass}> has no cardinality on property <${resourcesInProjectGetRequestV2.orderByProperty}>")
}
// Get the value class that's the object of the knora-base:objectClassConstraint of the ORDER BY property.
val orderByValueType: SmartIri = internalOrderByPropertyDef.entityInfoContent.requireIriObject(
OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri,
throw InconsistentRepositoryDataException(
s"Property <$internalOrderByPropertyIri> has no knora-base:objectClassConstraint")
)
// Determine which subproperty of knora-base:valueHas corresponds to that value class.
val orderByValuePredicate = orderByValueType.toString match {
case OntologyConstants.KnoraBase.IntValue => OntologyConstants.KnoraBase.ValueHasInteger
case OntologyConstants.KnoraBase.DecimalValue => OntologyConstants.KnoraBase.ValueHasDecimal
case OntologyConstants.KnoraBase.BooleanValue => OntologyConstants.KnoraBase.ValueHasBoolean
case OntologyConstants.KnoraBase.DateValue => OntologyConstants.KnoraBase.ValueHasStartJDN
case OntologyConstants.KnoraBase.ColorValue => OntologyConstants.KnoraBase.ValueHasColor
case OntologyConstants.KnoraBase.GeonameValue => OntologyConstants.KnoraBase.ValueHasGeonameCode
case OntologyConstants.KnoraBase.IntervalValue => OntologyConstants.KnoraBase.ValueHasIntervalStart
case OntologyConstants.KnoraBase.UriValue => OntologyConstants.KnoraBase.ValueHasUri
case _ => OntologyConstants.KnoraBase.ValueHasString
}
Some(orderByValuePredicate.toSmartIri)
case None => None
}
// Do a SELECT prequery to get the IRIs of the requested page of resources.
prequery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.getResourcesInProjectPrequery(
triplestore = settings.triplestoreType,
projectIri = resourcesInProjectGetRequestV2.projectIri.toString,
resourceClassIri = internalClassIri,
maybeOrderByProperty = maybeInternalOrderByPropertyIri,
maybeOrderByValuePredicate = maybeOrderByValuePredicate,
limit = settings.v2ResultsPerPage,
offset = resourcesInProjectGetRequestV2.page * settings.v2ResultsPerPage
)
.toString
sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(prequery)).mapTo[SparqlSelectResult]
mainResourceIris: Seq[IRI] = sparqlSelectResponse.results.bindings.map(_.rowMap("resource"))
// Find out whether to query standoff along with text values. This boolean value will be passed to
// ConstructResponseUtilV2.makeTextValueContentV2.
queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues(targetSchema = ApiV2Complex,
schemaOptions =
resourcesInProjectGetRequestV2.schemaOptions)
// If we're supposed to query standoff, get the indexes delimiting the first page of standoff. (Subsequent
// pages, if any, will be queried separately.)
(maybeStandoffMinStartIndex: Option[Int], maybeStandoffMaxStartIndex: Option[Int]) = StandoffTagUtilV2
.getStandoffMinAndMaxStartIndexesForTextValueQuery(
queryStandoff = queryStandoff,
settings = settings
)
// Are there any matching resources?
apiResponse: ReadResourcesSequenceV2 <- if (mainResourceIris.nonEmpty) {
for {
// Yes. Do a CONSTRUCT query to get the contents of those resources. If we're querying standoff, get
// at most one page of standoff per text value.
resourceRequestSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.getResourcePropertiesAndValues(
triplestore = settings.triplestoreType,
resourceIris = mainResourceIris,
preview = false,
queryAllNonStandoff = true,
maybePropertyIri = None,
maybeVersionDate = None,
maybeStandoffMinStartIndex = maybeStandoffMinStartIndex,
maybeStandoffMaxStartIndex = maybeStandoffMaxStartIndex,
stringFormatter = stringFormatter
)
.toString())
// _ = println(resourceRequestSparql)
resourceRequestResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = resourceRequestSparql,
featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig
)).mapTo[SparqlExtendedConstructResponse]
// separate resources and values
mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2
.splitMainResourcesAndValueRdfData(constructQueryResults = resourceRequestResponse,
requestingUser = resourcesInProjectGetRequestV2.requestingUser)
// If we're querying standoff, get XML-to standoff mappings.
mappings: Map[IRI, MappingAndXSLTransformation] <- if (queryStandoff) {
getMappingsFromQueryResultsSeparated(
mainResourcesAndValueRdfData.resources,
featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig,
resourcesInProjectGetRequestV2.requestingUser
)
} else {
FastFuture.successful(Map.empty[IRI, MappingAndXSLTransformation])
}
// Construct a ReadResourceV2 for each resource that the user has permission to see.
readResourcesSequence: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse(
mainResourcesAndValueRdfData = mainResourcesAndValueRdfData,
orderByResourceIri = mainResourceIris,
pageSizeBeforeFiltering = mainResourceIris.size,
mappings = mappings,
queryStandoff = maybeStandoffMinStartIndex.nonEmpty,
versionDate = None,
calculateMayHaveMoreResults = true,
responderManager = responderManager,
targetSchema = resourcesInProjectGetRequestV2.targetSchema,
settings = settings,
featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig,
requestingUser = resourcesInProjectGetRequestV2.requestingUser
)
} yield readResourcesSequence
} else {
FastFuture.successful(ReadResourcesSequenceV2(Vector.empty[ReadResourceV2]))
}
} yield apiResponse
}
/**
* Performs a count query for a search for resources by their rdfs:label.
*
* @param searchValue the values to search for.
* @param limitToProject limit search to given project.
* @param limitToResourceClass limit search to given resource class.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ReadResourcesSequenceV2]] representing the resources that have been found.
*/
private def searchResourcesByLabelCountV2(searchValue: String,
limitToProject: Option[IRI],
limitToResourceClass: Option[SmartIri],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ResourceCountV2] = {
val searchPhrase: MatchStringWhileTyping = MatchStringWhileTyping(searchValue)
for {
countSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.searchResourceByLabel(
triplestore = settings.triplestoreType,
searchTerm = searchPhrase,
limitToProject = limitToProject,
limitToResourceClass = limitToResourceClass.map(_.toString),
limit = 1,
offset = 0,
countQuery = true
)
.toString())
// _ = println(countSparql)
countResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(countSparql)).mapTo[SparqlSelectResult]
// query response should contain one result with one row with the name "count"
_ = if (countResponse.results.bindings.length != 1) {
throw GravsearchException(
s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given")
}
count = countResponse.results.bindings.head.rowMap("count")
} yield
ResourceCountV2(
numberOfResources = count.toInt
)
}
/**
* Performs a search for resources by their rdfs:label.
*
* @param searchValue the values to search for.
* @param offset the offset to be used for paging.
* @param limitToProject limit search to given project.
* @param limitToResourceClass limit search to given resource class.
* @param targetSchema the schema of the response.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the the client making the request.
* @return a [[ReadResourcesSequenceV2]] representing the resources that have been found.
*/
private def searchResourcesByLabelV2(searchValue: String,
offset: Int,
limitToProject: Option[IRI],
limitToResourceClass: Option[SmartIri],
targetSchema: ApiV2Schema,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ReadResourcesSequenceV2] = {
val searchPhrase: MatchStringWhileTyping = MatchStringWhileTyping(searchValue)
for {
searchResourceByLabelSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.searchResourceByLabel(
triplestore = settings.triplestoreType,
searchTerm = searchPhrase,
limitToProject = limitToProject,
limitToResourceClass = limitToResourceClass.map(_.toString),
limit = settings.v2ResultsPerPage,
offset = offset * settings.v2ResultsPerPage,
countQuery = false
)
.toString())
// _ = println(searchResourceByLabelSparql)
searchResourceByLabelResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = searchResourceByLabelSparql,
featureFactoryConfig = featureFactoryConfig
)).mapTo[SparqlExtendedConstructResponse]
// collect the IRIs of main resources returned
mainResourceIris: Set[IRI] = searchResourceByLabelResponse.statements.foldLeft(Set.empty[IRI]) {
case (acc: Set[IRI], (subject: SubjectV2, assertions: Map[SmartIri, Seq[LiteralV2]])) =>
// check if the assertions represent a main resource and include its IRI if so
val subjectIsMainResource: Boolean =
assertions.getOrElse(OntologyConstants.KnoraBase.IsMainResource.toSmartIri, Seq.empty).headOption match {
case Some(BooleanLiteralV2(booleanVal)) => booleanVal
case _ => false
}
if (subjectIsMainResource) {
val subjIri: IRI = subject match {
case IriSubjectV2(value) => value
case other => throw InconsistentRepositoryDataException(s"Unexpected subject of resource: $other")
}
acc + subjIri
} else {
acc
}
}
// _ = println(mainResourceIris.size)
// separate resources and value objects
mainResourcesAndValueRdfData = ConstructResponseUtilV2.splitMainResourcesAndValueRdfData(
constructQueryResults = searchResourceByLabelResponse,
requestingUser = requestingUser)
//_ = println(queryResultsSeparated)
apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse(
mainResourcesAndValueRdfData = mainResourcesAndValueRdfData,
orderByResourceIri = mainResourceIris.toSeq.sorted,
pageSizeBeforeFiltering = mainResourceIris.size,
queryStandoff = false,
versionDate = None,
calculateMayHaveMoreResults = true,
responderManager = responderManager,
targetSchema = targetSchema,
settings = settings,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
} yield apiResponse
}
/**
* Given a prequery result, merges rows with the same main resource IRI. This could happen if there are unbound
* variables in `GROUP_CONCAT` expressions.
*
* @param prequeryResponseNotMerged the prequery response before merging.
* @param mainResourceVar the name of the column representing the main resource.
* @return the merged results.
*/