-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathFullTextSearchModule.cs
More file actions
1739 lines (1454 loc) · 46.4 KB
/
FullTextSearchModule.cs
File metadata and controls
1739 lines (1454 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Waher.Events;
using Waher.Persistence.Attributes;
using Waher.Persistence.Filters;
using Waher.Persistence.FullTextSearch.Files;
using Waher.Persistence.FullTextSearch.Keywords;
using Waher.Persistence.FullTextSearch.Orders;
using Waher.Persistence.FullTextSearch.Tokenizers;
using Waher.Persistence.LifeCycle;
using Waher.Persistence.Serialization;
using Waher.Runtime.Cache;
using Waher.Runtime.Collections;
using Waher.Runtime.Inventory;
using Waher.Runtime.Threading;
using Waher.Script.Model;
namespace Waher.Persistence.FullTextSearch
{
/// <summary>
/// Full-text search module, controlling the life-cycle of the full-text-search engine.
/// </summary>
[ModuleDependency(typeof(DatabaseModule))]
public class FullTextSearchModule : IModule
{
private static readonly MultiReadSingleWriteObject synchObj = new MultiReadSingleWriteObject(typeof(FullTextSearchModule), false);
private static Cache<string, QueryRecord> queryCache;
private static Dictionary<string, bool> stopWords = new Dictionary<string, bool>();
private static IPersistentDictionary collectionInformation;
private static Dictionary<string, CollectionInformation> collections;
private static Dictionary<string, IPersistentDictionary> indices;
private static Dictionary<Type, TypeInformation> types;
private static FullTextSearchModule instance = null;
/// <summary>
/// Full-text search module, controlling the life-cycle of the full-text-search engine.
/// </summary>
public FullTextSearchModule()
{
}
/// <summary>
/// Starts the module.
/// </summary>
public async Task Start()
{
collectionInformation = await Database.GetDictionary("FullTextSearchCollections");
collections = new Dictionary<string, CollectionInformation>();
indices = new Dictionary<string, IPersistentDictionary>();
types = new Dictionary<Type, TypeInformation>();
queryCache = new Cache<string, QueryRecord>(int.MaxValue, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
instance = this;
Database.ObjectInserted += this.Database_ObjectInserted;
Database.ObjectUpdated += this.Database_ObjectUpdated;
Database.ObjectDeleted += this.Database_ObjectDeleted;
Database.CollectionCleared += this.Database_CollectionCleared;
Types.OnInvalidated += this.Types_OnInvalidated;
}
/// <summary>
/// Stops the module.
/// </summary>
public async Task Stop()
{
Database.ObjectInserted -= this.Database_ObjectInserted;
Database.ObjectUpdated -= this.Database_ObjectUpdated;
Database.ObjectDeleted -= this.Database_ObjectDeleted;
Database.CollectionCleared -= this.Database_CollectionCleared;
Types.OnInvalidated -= this.Types_OnInvalidated;
// TODO: Wait for current objects to be finished.
await synchObj.BeginWrite();
try
{
queryCache?.Dispose();
queryCache = null;
if (!(indices is null))
{
foreach (IPersistentDictionary Index in indices.Values)
Index.Dispose();
indices.Clear();
indices = null;
}
collectionInformation?.Dispose();
collectionInformation = null;
collections?.Clear();
collections = null;
types?.Clear();
types = null;
}
finally
{
await synchObj.EndWrite();
instance = null;
}
}
private void Database_ObjectInserted(object Sender, ObjectEventArgs e)
{
Task.Run(() => this.ObjectInserted(e));
}
private async Task ObjectInserted(ObjectEventArgs e)
{
try
{
Tuple<CollectionInformation, TypeInformation, GenericObject> P = await Prepare(e.Object);
if (P is null)
return;
object ObjectId = await Database.TryGetObjectId(e.Object);
if (ObjectId is null)
return;
CollectionInformation CollectionInfo = P.Item1;
TypeInformation TypeInfo = P.Item2;
GenericObject GenObj = P.Item3;
TokenCount[] Tokens;
string IndexName;
if (GenObj is null)
{
IndexName = TypeInfo.GetIndexCollection(e.Object);
Tokens = await TypeInfo.Tokenize(e.Object, CollectionInfo.Properties);
}
else
{
IndexName = CollectionInfo.IndexCollectionName;
Tokens = await Tokenize(GenObj, CollectionInfo.Properties);
}
if (Tokens is null || Tokens.Length == 0)
return;
ObjectReference Ref;
await synchObj.BeginWrite();
try
{
ulong Index = await GetNextIndexNrLocked(IndexName);
Ref = new ObjectReference()
{
IndexCollection = IndexName,
Collection = CollectionInfo.CollectionName,
ObjectInstanceId = ObjectId,
Index = Index,
Tokens = Tokens,
Indexed = DateTime.UtcNow
};
await AddTokensToIndexLocked(Ref);
await Database.Insert(Ref);
}
finally
{
await synchObj.EndWrite();
}
queryCache?.Clear();
await Search.RaiseObjectAddedToIndex(this, new ObjectReferenceEventArgs(Ref));
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
private static async Task<IPersistentDictionary> GetIndexLocked(string IndexCollection, bool CreateIfNotFound)
{
if (indices.TryGetValue(IndexCollection, out IPersistentDictionary Result))
return Result;
if (CreateIfNotFound)
{
Result = await Database.GetDictionary(IndexCollection);
indices[IndexCollection] = Result;
}
return Result;
}
private static async Task AddTokensToIndexLocked(ObjectReference Ref)
{
DateTime TP = DateTime.UtcNow;
IPersistentDictionary Index = await GetIndexLocked(Ref.IndexCollection, true);
foreach (TokenCount Token in Ref.Tokens)
{
KeyValuePair<bool, object> P = await Index.TryGetValueAsync(Token.Token);
int c;
if (!P.Key || !(P.Value is TokenReferences References))
{
References = new TokenReferences()
{
LastBlock = 0,
ObjectReferences = new ulong[] { Ref.Index },
Counts = new uint[] { (uint)Token.DocIndex.Length },
Timestamps = new DateTime[] { TP }
};
await Index.AddAsync(Token.Token, References, true);
}
else if ((c = References.ObjectReferences.Length) < TokenReferences.MaxReferences)
{
ulong[] NewReferences = new ulong[c + 1];
uint[] NewCounts = new uint[c + 1];
DateTime[] NewTimestamps = new DateTime[c + 1];
Array.Copy(References.ObjectReferences, 0, NewReferences, 0, c);
Array.Copy(References.Counts, 0, NewCounts, 0, c);
Array.Copy(References.Timestamps, 0, NewTimestamps, 0, c);
NewReferences[c] = Ref.Index;
NewCounts[c] = (uint)Token.DocIndex.Length;
NewTimestamps[c] = TP;
References.ObjectReferences = NewReferences;
References.Counts = NewCounts;
References.Timestamps = NewTimestamps;
await Index.AddAsync(Token.Token, References, true);
}
else
{
References.LastBlock++;
TokenReferences NewBlock = new TokenReferences()
{
LastBlock = 0,
Counts = References.Counts,
ObjectReferences = References.ObjectReferences,
Timestamps = References.Timestamps
};
await Index.AddAsync(Token.Token + " " + References.LastBlock.ToString(), NewBlock, true);
References.ObjectReferences = new ulong[] { Ref.Index };
References.Counts = new uint[] { (uint)Token.DocIndex.Length };
References.Timestamps = new DateTime[] { TP };
await Index.AddAsync(Token.Token, References, true);
}
Token.Block = References.LastBlock + 1;
}
}
private static async Task<ulong> GetNextIndexNrLocked(string IndexedCollection)
{
if (collectionInformation is null)
throw new ObjectDisposedException(nameof(FullTextSearchModule));
string Key = " C(" + IndexedCollection + ")";
KeyValuePair<bool, object> P = await collectionInformation.TryGetValueAsync(Key);
if (!P.Key || !(P.Value is ulong Nr))
Nr = 0;
Nr++;
await collectionInformation.AddAsync(Key, Nr, true);
return Nr;
}
private static Task<CollectionInformation> GetCollectionInfoLocked(string CollectionName, bool CreateIfNotExists)
{
return GetCollectionInfoLocked(CollectionName, CollectionName, CreateIfNotExists);
}
private static async Task<CollectionInformation> GetCollectionInfoLocked(
string IndexCollectionName, string CollectionName, bool CreateIfNotExists)
{
if (collections is null)
{
if (CreateIfNotExists)
throw new NotSupportedException("Service not initialized or shut down.");
else
return null;
}
if (collections.TryGetValue(CollectionName, out CollectionInformation Result))
return Result;
KeyValuePair<bool, object> P = await collectionInformation.TryGetValueAsync(CollectionName);
if (P.Key && P.Value is CollectionInformation Result2)
{
collections[CollectionName] = Result2;
return Result2;
}
if (!CreateIfNotExists)
return null;
Result = new CollectionInformation(IndexCollectionName, CollectionName, false);
collections[CollectionName] = Result;
await collectionInformation.AddAsync(CollectionName, Result, true);
return Result;
}
/// <summary>
/// Gets the database collections that get indexed into a given index colltion.
/// </summary>
/// <returns>Collection Names indexed in the full-text-search index.</returns>
public static async Task<Dictionary<string, string[]>> GetCollectionNames()
{
Dictionary<string, ChunkedList<string>> ByIndex = new Dictionary<string, ChunkedList<string>>();
await synchObj.BeginRead();
try
{
object[] Values = await collectionInformation.GetValuesAsync();
foreach (object Obj in Values)
{
if (Obj is CollectionInformation Info &&
Info.IndexForFullTextSearch &&
!string.IsNullOrEmpty(Info.IndexCollectionName))
{
if (!ByIndex.TryGetValue(Info.IndexCollectionName, out ChunkedList<string> Collections))
{
Collections = new ChunkedList<string>();
ByIndex[Info.IndexCollectionName] = Collections;
}
Collections.Add(Info.CollectionName);
}
}
}
finally
{
await synchObj.EndRead();
}
Dictionary<string, string[]> Result = new Dictionary<string, string[]>();
foreach (KeyValuePair<string, ChunkedList<string>> Rec in ByIndex)
Result[Rec.Key] = Rec.Value.ToArray();
return Result;
}
/// <summary>
/// Gets the database collections that get indexed into a given index colltion.
/// </summary>
/// <param name="IndexCollectionName">Index Collection Name</param>
/// <returns>Collection Names indexed in the full-text-search index
/// defined by <paramref name="IndexCollectionName"/>.</returns>
public static async Task<string[]> GetCollectionNames(string IndexCollectionName)
{
await synchObj.BeginRead();
try
{
return await GetCollectionNamesLocked(IndexCollectionName);
}
finally
{
await synchObj.EndRead();
}
}
/// <summary>
/// Gets the database collections that get indexed into a given index colltion.
/// </summary>
/// <param name="IndexCollectionName">Index Collection Name</param>
/// <returns>Collection Names indexed in the full-text-search index
/// defined by <paramref name="IndexCollectionName"/>.</returns>
private static async Task<string[]> GetCollectionNamesLocked(string IndexCollectionName)
{
ChunkedList<string> Result = new ChunkedList<string>();
foreach (object Obj in await collectionInformation.GetValuesAsync())
{
if (Obj is CollectionInformation Info && Info.IndexForFullTextSearch)
{
if (Info.IndexCollectionName == IndexCollectionName)
Result.Add(Info.CollectionName);
}
}
return Result.ToArray();
}
/// <summary>
/// Defines the Full-text-search index collection name, for objects in a given collection.
/// </summary>
/// <param name="IndexCollection">Collection name for full-text-search index of objects in the given collection.</param>
/// <param name="CollectionName">Collection of objects to index.</param>
/// <returns>If the configuration was changed.</returns>
internal static async Task<bool> SetFullTextSearchIndexCollection(string IndexCollection, string CollectionName)
{
await synchObj.BeginWrite();
try
{
CollectionInformation Info = await GetCollectionInfoLocked(IndexCollection, CollectionName, false);
bool Created;
if (Info is null)
{
Created = true;
Info = await GetCollectionInfoLocked(IndexCollection, CollectionName, true);
}
else
Created = false;
if (Info.IndexCollectionName != IndexCollection)
{
Info.IndexCollectionName = IndexCollection;
await collectionInformation.AddAsync(Info.CollectionName, Info, true);
return true;
}
else
return Created;
}
finally
{
await synchObj.EndWrite();
}
}
/// <summary>
/// Adds properties for full-text-search indexation.
/// </summary>
/// <param name="CollectionName">Collection name.</param>
/// <param name="Properties">Properties to index.</param>
/// <returns>If new property names were found and added.</returns>
internal static async Task<bool> AddFullTextSearch(string CollectionName, params PropertyDefinition[] Properties)
{
await synchObj.BeginWrite();
try
{
CollectionInformation Info = await GetCollectionInfoLocked(CollectionName, true);
if (Info.AddIndexableProperties(Properties))
{
await collectionInformation.AddAsync(Info.CollectionName, Info, true);
return true;
}
else
return false;
}
finally
{
await synchObj.EndWrite();
}
}
/// <summary>
/// Removes properties from full-text-search indexation.
/// </summary>
/// <param name="CollectionName">Collection name.</param>
/// <param name="Properties">Properties to remove from indexation.</param>
/// <returns>If property names were found and removed.</returns>
internal static async Task<bool> RemoveFullTextSearch(string CollectionName, params PropertyDefinition[] Properties)
{
await synchObj.BeginWrite();
try
{
CollectionInformation Info = await GetCollectionInfoLocked(CollectionName, true);
if (Info.RemoveIndexableProperties(Properties))
{
await collectionInformation.AddAsync(Info.CollectionName, Info, true);
return true;
}
else
return false;
}
finally
{
await synchObj.EndWrite();
}
}
/// <summary>
/// Gets indexed properties for full-text-search indexation.
/// </summary>
/// <returns>Dictionary of indexed properties, per collection.</returns>
internal static async Task<Dictionary<string, PropertyDefinition[]>> GetFullTextSearchIndexedProperties()
{
Dictionary<string, PropertyDefinition[]> Result = new Dictionary<string, PropertyDefinition[]>();
await synchObj.BeginRead();
try
{
foreach (object Obj in await collectionInformation.GetValuesAsync())
{
if (Obj is CollectionInformation Info && Info.IndexForFullTextSearch)
Result[Info.CollectionName] = Info.Properties;
}
}
finally
{
await synchObj.EndRead();
}
return Result;
}
/// <summary>
/// Gets indexed properties for full-text-search indexation.
/// </summary>
/// <param name="CollectionName">Collection name.</param>
/// <returns>Array of indexed properties.</returns>
internal static async Task<PropertyDefinition[]> GetFullTextSearchIndexedProperties(string CollectionName)
{
await synchObj.BeginRead();
try
{
CollectionInformation Info = await GetCollectionInfoLocked(CollectionName, false);
if (Info is null || !Info.IndexForFullTextSearch)
return Array.Empty<PropertyDefinition>();
else
return (PropertyDefinition[])Info.Properties.Clone();
}
finally
{
await synchObj.EndRead();
}
}
private static async Task<Tuple<CollectionInformation, TypeInformation, GenericObject>> Prepare(object Object)
{
Object = await ScriptNode.WaitPossibleTask(Object);
await synchObj.BeginWrite();
try
{
if (Object is GenericObject GenObj)
return await PrepareLocked(GenObj);
else
return await PrepareLocked(Object.GetType(), Object);
}
finally
{
await synchObj.EndWrite();
}
}
private static async Task<Tuple<CollectionInformation, TypeInformation, GenericObject>> PrepareLocked(GenericObject GenObj)
{
CollectionInformation CollectionInfo = await GetCollectionInfoLocked(GenObj.CollectionName, true);
if (CollectionInfo.IndexForFullTextSearch)
return new Tuple<CollectionInformation, TypeInformation, GenericObject>(CollectionInfo, null, GenObj);
else
return null;
}
private static async Task<TypeInformation> GetTypeInfoLocked(Type T, object Instance)
{
if (types is null)
throw new Exception("Full text search module not started, or in the process of being stopped.");
if (types.TryGetValue(T, out TypeInformation Result))
return Result;
TypeInfo TI = T.GetTypeInfo();
IEnumerable<FullTextSearchAttribute> SearchAttrs = TI.GetCustomAttributes<FullTextSearchAttribute>(true);
CollectionNameAttribute CollectionAttr = TI.GetCustomAttribute<CollectionNameAttribute>(true);
ITokenizer CustomTokenizer = Types.FindBest<ITokenizer, Type>(T);
if (CollectionAttr is null)
Result = new TypeInformation(T, TI, null, null, CustomTokenizer, null);
else
{
string CollectionName = CollectionAttr.Name;
bool DynamicIndex = false;
string IndexName;
if (!(SearchAttrs is null))
{
foreach (FullTextSearchAttribute Attribute in SearchAttrs)
{
if (Attribute.DynamicIndexCollection)
{
DynamicIndex = true;
break;
}
}
}
if (DynamicIndex)
IndexName = null;
else
{
IndexName = CollectionName;
foreach (FullTextSearchAttribute Attribute in SearchAttrs)
{
IndexName = Attribute.GetIndexCollection(Instance);
break;
}
}
CollectionInformation Info = await GetCollectionInfoLocked(IndexName, CollectionName, true);
Result = new TypeInformation(T, TI, CollectionName, Info, CustomTokenizer, SearchAttrs);
if (Result.HasPropertyDefinitions && Info.AddIndexableProperties(Result.Properties))
await collectionInformation.AddAsync(CollectionName, Info, true);
else if (!(CustomTokenizer is null) && !Info.IndexForFullTextSearch)
{
Info.IndexForFullTextSearch = true;
await collectionInformation.AddAsync(CollectionName, Info, true);
}
}
types[T] = Result;
return Result;
}
private static async Task<Tuple<CollectionInformation, TypeInformation, GenericObject>> PrepareLocked(Type T, object Instance)
{
TypeInformation TypeInfo = await GetTypeInfoLocked(T, Instance);
if (!TypeInfo.HasCollection)
return null;
if (!TypeInfo.CollectionInformation?.IndexForFullTextSearch ?? false)
return null;
return new Tuple<CollectionInformation, TypeInformation, GenericObject>(TypeInfo.CollectionInformation, TypeInfo, null);
}
/// <summary>
/// Parses a search string into keyworkds.
/// </summary>
/// <param name="Search">Search string.</param>
/// <param name="TreatKeywordsAsPrefixes">If keywords should be treated as
/// prefixes. Example: "test" would match "test", "tests" and "testing" if
/// treated as a prefix, but also "tester", "testosterone", etc.</param>
/// <returns>Keywords</returns>
internal static Keyword[] ParseKeywords(string Search, bool TreatKeywordsAsPrefixes)
{
return ParseKeywords(Search, TreatKeywordsAsPrefixes, true);
}
/// <summary>
/// Parses a search string into keyworkds.
/// </summary>
/// <param name="Search">Search string.</param>
/// <param name="TreatKeywordsAsPrefixes">If keywords should be treated as
/// prefixes. Example: "test" would match "test", "tests" and "testing" if
/// treated as a prefix, but also "tester", "testosterone", etc.</param>
/// <param name="ParseQuotes">If quotes are to be processed.</param>
/// <returns>Keywords</returns>
private static Keyword[] ParseKeywords(string Search, bool TreatKeywordsAsPrefixes,
bool ParseQuotes)
{
ChunkedList<Keyword> Result = new ChunkedList<Keyword>();
StringBuilder sb = new StringBuilder();
bool First = true;
bool Required = false;
bool Prohibited = false;
string Wildcard = null;
int Type = 0;
Keyword Keyword;
string Token;
foreach (char ch in Search.ToLower().Normalize(NormalizationForm.FormD))
{
UnicodeCategory Category = CharUnicodeInfo.GetUnicodeCategory(ch);
if (Category == UnicodeCategory.NonSpacingMark)
continue;
if (char.IsLetterOrDigit(ch))
{
sb.Append(ch);
First = false;
}
else if (Type == 2)
{
if (ch == '/')
{
Token = sb.ToString();
sb.Clear();
First = true;
Type = 0;
Add(new RegexKeyword(Token), Result, ref Required, ref Prohibited);
}
else
{
sb.Append(ch);
First = false;
}
}
else if (Type == 3)
{
if (ch == '"')
{
Token = sb.ToString();
sb.Clear();
First = true;
Type = 0;
Add(new SequenceOfKeywords(ParseKeywords(Token, false)),
Result, ref Required, ref Prohibited);
}
else
sb.Append(ch);
}
else if (Type == 4)
{
if (ch == '\'')
{
Token = sb.ToString();
sb.Clear();
First = true;
Type = 0;
Add(new SequenceOfKeywords(ParseKeywords(Token, false)),
Result, ref Required, ref Prohibited);
}
else
sb.Append(ch);
}
else if (Type == 0 && (ch == '*' || ch == '%' || ch == '¤' || ch == '#'))
{
sb.Append(ch);
Type = 1;
Wildcard = new string(ch, 1);
}
else
{
if (!First)
{
Token = sb.ToString();
sb.Clear();
First = true;
if (Type == 1)
{
Keyword = new WildcardKeyword(Token, Wildcard);
Wildcard = null;
}
else if (TreatKeywordsAsPrefixes)
Keyword = new WildcardKeyword(Token);
else
Keyword = new PlainKeyword(Token);
Add(Keyword, Result, ref Required, ref Prohibited);
Type = 0;
}
if (ch == '+')
{
Required = true;
Prohibited = false;
}
else if (ch == '-')
{
Prohibited = true;
Required = false;
}
else if (ch == '/')
Type = 2;
else if (ch == '"' && ParseQuotes)
Type = 3;
else if (ch == '\'' && ParseQuotes)
Type = 4;
}
}
if (!First)
{
Token = sb.ToString();
sb.Clear();
switch (Type)
{
case 0:
default:
if (TreatKeywordsAsPrefixes)
Keyword = new WildcardKeyword(Token);
else
Keyword = new PlainKeyword(Token);
break;
case 1:
Keyword = new WildcardKeyword(Token, Wildcard);
break;
case 2:
Keyword = new RegexKeyword(Token);
break;
}
Add(Keyword, Result, ref Required, ref Prohibited);
}
return Result.ToArray();
}
private static void Add(Keyword Keyword, ChunkedList<Keyword> Result, ref bool Required, ref bool Prohibited)
{
if (Required)
{
Keyword = new RequiredKeyword(Keyword);
Required = false;
}
if (Prohibited)
{
Keyword = new ProhibitedKeyword(Keyword);
Prohibited = false;
}
Result.Add(Keyword);
}
/// <summary>
/// Performs a Full-Text-Search
/// </summary>
/// <param name="IndexCollection">Index collection name.</param>
/// <param name="Offset">Index of first object matching the keywords.</param>
/// <param name="MaxCount">Maximum number of objects to return.</param>
/// <param name="Order">The order of objects to return.</param>
/// <param name="PaginationStrategy">How to handle pagination.</param>
/// <param name="Keywords">Keywords to search for.</param>
/// <returns>Array of objects. Depending on choice of
/// <paramref name="PaginationStrategy"/>, null items may be returned
/// if underlying object is not compatible with <typeparamref name="T"/>.</returns>
internal static async Task<T[]> FullTextSearch<T>(string IndexCollection,
int Offset, int MaxCount, FullTextSearchOrder Order,
PaginationStrategy PaginationStrategy, params Keyword[] Keywords)
where T : class
{
if (MaxCount <= 0 || Keywords is null)
return Array.Empty<T>();
int NrKeywords = Keywords.Length;
if (NrKeywords == 0)
return Array.Empty<T>();
Keywords = (Keyword[])Keywords.Clone();
Array.Sort(Keywords, orderOfProcessing);
StringBuilder sb = new StringBuilder();
sb.Append(IndexCollection);
sb.Append(' ');
sb.Append(Order.ToString());
foreach (Keyword Keyword in Keywords)
{
if (!Keyword.Ignore)
{
sb.Append(' ');
sb.Append(Keyword.ToString());
}
}
string Key = sb.ToString();
MatchInformation[] FoundReferences;
SearchProcess Process = null;
if (queryCache.TryGetValue(Key, out QueryRecord QueryRecord))
{
FoundReferences = QueryRecord.FoundReferences;
Process = QueryRecord.Process;
}
else
{
IPersistentDictionary Index;
await synchObj.BeginRead();
try
{
Index = await GetIndexLocked(IndexCollection, false);
if (!(Index is null))
{
Process = new SearchProcess(Index, IndexCollection);
foreach (Keyword Keyword in Keywords)
{
if (Keyword.Ignore)
continue;
if (!await Keyword.Process(Process))
return Array.Empty<T>();
}
}
}
finally
{
await synchObj.EndRead();
}
if (Index is null)
{
await synchObj.BeginWrite();
try
{
Index = await GetIndexLocked(IndexCollection, true);
Process = new SearchProcess(Index, IndexCollection);
foreach (Keyword Keyword in Keywords)
{
if (Keyword.Ignore)
continue;
if (!await Keyword.Process(Process))
return Array.Empty<T>();
}
}
finally
{
await synchObj.EndWrite();
}
}
int c = Process.ReferencesByObject.Count;
FoundReferences = new MatchInformation[c];
Process.ReferencesByObject.Values.CopyTo(FoundReferences, 0);
switch (Order)
{
case FullTextSearchOrder.Relevance:
default:
Array.Sort(FoundReferences, relevanceOrder);
break;
case FullTextSearchOrder.Occurrences:
Array.Sort(FoundReferences, occurrencesOrder);
break;
case FullTextSearchOrder.Newest:
Array.Sort(FoundReferences, newestOrder);
break;
case FullTextSearchOrder.Oldest:
Array.Sort(FoundReferences, oldestOrder);
break;
}
queryCache[Key] = new QueryRecord()
{
FoundReferences = FoundReferences,
Process = Process
};
}
ChunkedList<T> Result = new ChunkedList<T>();
switch (PaginationStrategy)
{
case PaginationStrategy.PaginateOverObjectsNullIfIncompatible:
default:
foreach (MatchInformation ObjectReference in FoundReferences)
{
if (Offset > 0)
{
Offset--;
continue;
}
ulong RefIndex = ObjectReference.ObjectReference;
ObjectReference Ref = await Process.TryGetObjectReference(RefIndex, true);
if (Ref is null)
Result.Add(null);
else
{
T Object = await Database.TryLoadObject<T>(Ref.Collection, Ref.ObjectInstanceId);
if (Object is null)
Result.Add(null);
else
Result.Add(Object);
}
MaxCount--;
if (MaxCount <= 0)
break;
}