forked from phildow/SPSearchStore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPSearchStore.m
1239 lines (884 loc) · 35.3 KB
/
SPSearchStore.m
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
//
// SPSearchStore.m
// SPSearchStore
//
// v0.9
//
// Created by Philip Dow on 6/6/11.
// Copyright 2011 Philip Dow /Sprouted. All rights reserved.
//
/*
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
* Neither the name of the author nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
For non-attribution licensing options refer to http://phildow.net/licensing/
*/
#import "SPSearchStore.h"
NSString const * kSPSearchStoreIndexName = @"Search Index";
NSInteger const kSPSearchStoreMemorySize = 2^16;
static NSTimeInterval kSPSearchStoreDefaultFetchTime = 0.5;
static NSInteger kSPSearchStoreDefaultFetchCount = 100;
static NSDictionary * SPSearchStoreStopWords() {
// Stop words dictionary. Currently only supports english but it hould be easy
// to add other language specific stop words. Simply expand the stopWords
// dictionary by adding a string of words separated by single space for the
// value, followed by the two character language specifier for the key.
// Other possible English stop words:
// about against under with away also across ago been before after above below
// around vs up down while
static NSDictionary *stopWords = nil;
if ( stopWords == nil ) {
stopWords = [[NSDictionary alloc] initWithObjectsAndKeys:
@"a all am an and any are as at be but by can could did do does etc for from goes got had has have he her hers him his how if in is it its let me more much must my no nor not now of off on or our own see set shall she should so some than that the them then there these they this those though to too us was way we what when where which who why will would yes yet you your yours",
@"en",
nil];
}
return stopWords;
}
static NSMutableDictionary * SPSearchStoreTextAnalysisOptions() {
// This dictionary stores a default set of text analysis options which are
// specified during search index creation. They cover preferences such as
// stop words, term length, proximity indexing and so on.
static NSMutableDictionary *textAnalysis = nil;
if ( textAnalysis == nil ) {
textAnalysis = [[NSMutableDictionary alloc] init];
[textAnalysis setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kSKProximityIndexing];
[textAnalysis setObject:[NSNumber numberWithInteger:0] forKey:(NSString *)kSKMaximumTerms];
[textAnalysis setObject:[NSNumber numberWithInteger:1] forKey:(NSString *)kSKMinTermLength];
}
return textAnalysis;
}
#pragma mark -
@interface SPSearchStore()
@property (readwrite,retain) NSMutableData *storeData;
@property (readwrite,retain) NSURL *storeURL;
@property (readwrite,copy) NSDictionary *analysisOptions;
@property (readwrite,copy) NSSet *stopWords;
@property (readwrite) BOOL didCreateStore;
#pragma mark -
- (BOOL) _addDocument:(NSURL*)inDocumentURI withText:(NSString*)inContents;
- (BOOL) _addDocument:(NSURL*)inFileURL typeHint:(NSString*)inMimeHint;
- (BOOL) _removeDocument:(NSURL*)inDocumentURI;
- (NSArray*) _allDocumentsForDocumentRef:(SKDocumentRef)document ignoreEmptyDocuments:(BOOL)ignoresEmpty;
- (BOOL) _fetchResults:(NSArray**)outDocuments ranks:(float*)outRanks
maxTime:(CFTimeInterval)maxTime maxCount:(CFIndex)maxCount;
- (void) _incrementChangeCount;
- (BOOL) _flushIndexIfNecessary;
- (BOOL) _compactIndex;
@end
#pragma mark -
@implementation SPSearchStore
@synthesize searchIndex;
@synthesize storeURL;
@synthesize writeLock;
@synthesize readLock;
@synthesize didCreateStore;
@synthesize analysisOptions;
@synthesize stopWords;
@synthesize ignoresNumericTerms;
@synthesize fetchCount;
@synthesize fetchTime;
#pragma mark -
- (id) initStoreWithMemory:(NSMutableData*)inData type:(SKIndexType)inType {
NSAssert( inType!=kSKIndexUnknown, @"inType must not be kSKIndexUnknown (0)" );
if ( self = [super init] ) {
if ( inData == nil ) {
// create a new in memory store
inData = [NSMutableData dataWithCapacity: kSPSearchStoreMemorySize];
searchIndex = SKIndexCreateWithMutableData( (CFMutableDataRef)inData, (CFStringRef)NULL,
(SKIndexType)inType, (CFDictionaryRef)SPSearchStoreTextAnalysisOptions() );
}
else {
// open a store from memory
searchIndex = SKIndexOpenWithMutableData ( (CFMutableDataRef)inData, (CFStringRef)NULL );
}
if ( searchIndex == NULL ) {
[self release];
return nil;
}
writeLock = [[NSLock alloc] init];
readLock = [[NSLock alloc] init];
self.stopWords = [SPSearchStoreTextAnalysisOptions() objectForKey:(NSString*)kSKStopWords];
self.analysisOptions = SPSearchStoreTextAnalysisOptions();
self.didCreateStore = (inData==nil);
self.storeData = inData;
self.storeURL = nil;
self.fetchCount = kSPSearchStoreDefaultFetchCount;
self.fetchTime = kSPSearchStoreDefaultFetchTime;
indexType = inType;
changeCount = 0;
}
return self;
}
- (id) initStoreWithFilename:(NSString*)inPath type:(SKIndexType)inType {
NSAssert( inPath!=nil, @"inPath must not be nil");
NSAssert( inType!=kSKIndexUnknown, @"inType must not be kSKIndexUnknown (0)" );
return [self initStoreWithURL:[NSURL fileURLWithPath:inPath] type:inType];
}
- (id) initStoreWithURL:(NSURL*)inFileURL type:(SKIndexType)inType {
NSAssert( inFileURL!=nil, @"inFileURL must not be nil");
NSAssert( [inFileURL isFileURL], @"inFileURL must be a file url");
NSAssert( inType!=kSKIndexUnknown, @"inType must not be kSKIndexUnknown (0)" );
if ( self = [super init] ) {
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
BOOL fileExists = [fm fileExistsAtPath:[inFileURL path]];
if ( fileExists ) {
// store already exists, we want to open it
searchIndex = SKIndexOpenWithURL((CFURLRef)inFileURL, (CFStringRef)NULL, true);
}
else {
// store does not exist, we want to create it
searchIndex = SKIndexCreateWithURL((CFURLRef)inFileURL, (CFStringRef)NULL,
(SKIndexType)inType, (CFDictionaryRef)SPSearchStoreTextAnalysisOptions() );
}
if ( searchIndex == NULL ) {
[self release];
return nil;
}
writeLock = [[NSLock alloc] init];
readLock = [[NSLock alloc] init];
self.stopWords = [SPSearchStoreTextAnalysisOptions() objectForKey:(NSString*)kSKStopWords];
self.analysisOptions = SPSearchStoreTextAnalysisOptions();
self.didCreateStore = !fileExists;
self.storeURL = inFileURL;
self.storeData = nil;
self.fetchCount = kSPSearchStoreDefaultFetchCount;
self.fetchTime = kSPSearchStoreDefaultFetchTime;
indexType = inType;
changeCount = 0;
}
return self;
}
- (void) dealloc {
self.analysisOptions = nil;
self.storeData = nil;
self.storeURL = nil;
SKIndexClose(searchIndex);
searchIndex = NULL;
[writeLock release], writeLock = nil;
[readLock release], readLock = nil;
[indexQue release], indexQue = nil;
[super dealloc];
}
#pragma mark -
- (void) setUsesSpotlightImporters:(BOOL)useSpotlight {
@synchronized(self) {
usesSpotlightImporters = useSpotlight;
if ( useSpotlight ) SKLoadDefaultExtractorPlugIns();
}
}
- (BOOL) usesSpotlightImporters {
BOOL uses;
@synchronized(self) {
uses = usesSpotlightImporters;
}
return uses;
}
- (void) setUsesConcurrentIndexing:(BOOL)useConcurrent {
@synchronized(self) {
usesConcurrentIndexing = useConcurrent;
if ( useConcurrent && indexQue == nil ) {
indexQue = [[NSOperationQueue alloc] init];
[indexQue setMaxConcurrentOperationCount:1];
// we lock around calls to the index, so there is no point
// in supporting more than one operation simultaneously
}
else if ( !useConcurrent && indexQue != nil ) {
[indexQue cancelAllOperations];
[indexQue release], indexQue = nil;
}
}
}
- (BOOL) usesConcurrentIndexing {
BOOL uses;
@synchronized(self) {
uses = usesConcurrentIndexing;
}
return uses;
}
- (void) setStoreData:(NSMutableData *)inData {
@synchronized(self) {
[inData retain];
[storeData release];
storeData = inData;
}
}
- (NSMutableData *) storeData {
NSMutableData *data = nil;
@synchronized(self) {
[self _flushIndexIfNecessary];
data = [[storeData retain] autorelease];
}
return data;
}
#pragma mark -
+ (void) setDefaultTextAnalysisOption:(id)inObject forKey:(NSString*)inKey {
[SPSearchStoreTextAnalysisOptions() setObject:inObject forKey:inKey];
}
+ (id) defaultTextAnalysisOptionForKey:(NSString*)inKey {
return [SPSearchStoreTextAnalysisOptions() objectForKey:inKey];
}
+ (NSSet*) stopWordsForLanguage:(NSString*)inLanguage {
NSString *words = [SPSearchStoreStopWords() objectForKey:inLanguage];
return ( words ? [NSSet setWithArray:[words componentsSeparatedByString:@" "]] : nil );
}
#pragma mark -
#pragma mark Document / Store Management
- (BOOL) addDocument:(NSURL*)inDocumentURI withText:(NSString*)inContents {
NSAssert( inDocumentURI!=nil, @"inDocumentURI must not be nil");
NSAssert( inContents!=nil, @"inContents must not be nil");
// Pass the call to a private method in order to support concurrent processing. Could
// be made 10.5 compatible using invocation operations or detachNewThreadSelector:
if ( self.usesConcurrentIndexing ) {
if ( indexQue == nil ) return NO;
[indexQue addOperationWithBlock:^(void) {
[self _addDocument:inDocumentURI withText:inContents];
}];
return YES;
}
else {
return [self _addDocument:inDocumentURI withText:inContents];
}
}
- (BOOL) addDocument:(NSURL*)inFileURL typeHint:(NSString*)inMimeHint {
NSAssert( inFileURL!=nil, @"inFileURL must not be nil");
// Pass the call to a private method in order to support concurrent processing. Could
// be made 10.5 compatible using invocation operations or detachNewThreadSelector:
if ( self.usesConcurrentIndexing ) {
if ( indexQue == nil ) return NO;
[indexQue addOperationWithBlock:^(void) {
[self _addDocument:inFileURL typeHint:inMimeHint];
}];
return YES;
}
else {
return [self _addDocument:inFileURL typeHint:inMimeHint];
}
}
- (BOOL) _addDocument:(NSURL*)inFileURL typeHint:(NSString*)inMimeHint {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[writeLock lock];
BOOL success = NO;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inFileURL);
if ( document == NULL ) goto bail; // not always harmful!
success = SKIndexAddDocument(searchIndex, document, (CFStringRef)inMimeHint, true);
if ( success ) [self _incrementChangeCount];
//
// CFStringRef name = SKDocumentGetName(document);
// NSLog(@"name is %@", (NSString*)name);
//
bail:
if ( document ) CFRelease(document);
[writeLock unlock];
[pool release];
return success;
}
- (BOOL) _addDocument:(NSURL*)inDocumentURI withText:(NSString*)inContents {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[writeLock lock];
BOOL success = NO;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
success = SKIndexAddDocumentWithText(searchIndex, document, (CFStringRef)inContents, true);
if ( success ) [self _incrementChangeCount];
bail:
if ( document ) CFRelease(document);
[writeLock unlock];
[pool release];
return success;
}
#pragma mark -
- (BOOL) removeDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inFileURL must not be nil");
if ( self.usesConcurrentIndexing ) {
if ( indexQue == nil ) return NO;
[indexQue addOperationWithBlock:^(void) {
[self _removeDocument:inDocumentURI];
}];
return YES;
}
else {
return [self _removeDocument:inDocumentURI];
}
}
- (BOOL) _removeDocument:(NSURL*)inDocumentURI {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[writeLock lock];
BOOL success = NO;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
success = SKIndexRemoveDocument(searchIndex, document);
if ( success ) [self _incrementChangeCount];
bail:
if ( document ) CFRelease(document);
[writeLock unlock];
[pool release];
return success;
}
#pragma mark -
- (BOOL) replaceDocument:(NSURL*)oldDocumentURL withDocument:(NSURL*)newDocumentURL typeHint:(NSString*)inMimeHint {
NSAssert( oldDocumentURL!=nil, @"oldDocumentURL must not be nil");
NSAssert( newDocumentURL!=nil, @"newDocumentURL must not be nil");
if ( self.usesConcurrentIndexing ) {
if ( indexQue == nil ) return NO;
[indexQue addOperationWithBlock:^(void) {
[self _removeDocument:oldDocumentURL];
}];
[indexQue addOperationWithBlock:^(void) {
[self _addDocument:newDocumentURL typeHint:inMimeHint];
}];
return YES;
}
else {
BOOL success = [self _removeDocument:oldDocumentURL];
success = ( success && [self _addDocument:newDocumentURL typeHint:inMimeHint] );
return success;
}
}
- (BOOL) replaceDocument:(NSURL*)oldDocumentURI withDocument:(NSURL*)newDocumentURI withText:(NSString*)inContents {
NSAssert( oldDocumentURI!=nil, @"oldDocumentURL must not be nil");
NSAssert( newDocumentURI!=nil, @"newDocumentURL must not be nil");
NSAssert( inContents!=nil, @"inContents must not be nil");
if ( self.usesConcurrentIndexing ) {
if ( indexQue == nil ) return NO;
[indexQue addOperationWithBlock:^(void) {
[self _removeDocument:oldDocumentURI];
}];
[indexQue addOperationWithBlock:^(void) {
[self _addDocument:newDocumentURI withText:inContents];
}];
return YES;
}
else {
BOOL success = [self _removeDocument:oldDocumentURI];
success = ( success && [self _addDocument:newDocumentURI withText:inContents] );
return success;
}
}
#pragma mark -
- (void) setProperties:(NSDictionary*)inProperties forDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inDocumentURI cannot be nil");
NSAssert( inProperties!=nil, @"inProperties cannot be nil");
[writeLock lock];
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
SKIndexSetDocumentProperties(searchIndex, document, (CFDictionaryRef)inProperties);
bail:
if ( document ) CFRelease(document);
[writeLock unlock];
}
- (NSDictionary*) propertiesForDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inDocumentURI cannot be nil");
[readLock lock];
CFDictionaryRef properties = NULL;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
properties = SKIndexCopyDocumentProperties(searchIndex, document);
[(id)properties autorelease];
bail:
if ( document ) CFRelease(document);
[readLock unlock];
return (NSDictionary*)properties;
}
- (BOOL) setName:(NSString*)inTitle forDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inDocumentURI cannot be nil");
NSAssert( inTitle!=nil, @"inTitle must not be nil");
[writeLock lock];
BOOL success = NO;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
success = SKIndexRenameDocument(searchIndex, document, (CFStringRef)inTitle);
bail:
if ( document ) CFRelease(document);
[writeLock unlock];
return success;
}
- (NSString*) nameOfDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inDocumentURI cannot be nil");
[readLock lock];
CFStringRef documentName = NULL;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
documentName = SKDocumentGetName(document);
bail:
if ( document ) CFRelease(document);
[readLock unlock];
return (NSString*)documentName;
}
- (SKDocumentIndexState) stateOfDocument:(NSURL*)inDocumentURI {
NSAssert( inDocumentURI!=nil, @"inDocumentURI cannot be nil");
[readLock lock];
SKDocumentIndexState documentState = kSKDocumentStateNotIndexed;
SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)inDocumentURI);
if ( document == NULL ) goto bail;
documentState = SKIndexGetDocumentState(searchIndex, document);
bail:
if ( document ) CFRelease(document);
[readLock unlock];
return documentState;
}
#pragma mark -
- (NSArray*) allDocuments:(BOOL)ignoreEmptyDocuments {
// There is some curious behavior here regarding the additions SearchKit makes when indexing file
// based documents. In addition to indexing the specified file, SearchKit also adds every parent
// folder up to a certain (unknown) point. The folders aren't actually indexed, nor their files
// which haven't been specified.
// The SKIndexDocumentIteratorRef will consequently return all of these "documents", even though
// none of them were actually added to the index. Fortunately, these documents all have zero terms,
// so we check for empty documents prior to adding them to our array.
// The trouble with this approach is that indexed documents which have a zero term count will also
// be filtered by this method.
[self _flushIndexIfNecessary];
[readLock lock];
[writeLock lock];
NSArray *allDocuments = [self _allDocumentsForDocumentRef:NULL ignoreEmptyDocuments:ignoreEmptyDocuments];
// Recursion. Yum.
bail:
[writeLock unlock];
[readLock unlock];
return [[allDocuments copy] autorelease];
}
- (NSArray*) _allDocumentsForDocumentRef:(SKDocumentRef)document ignoreEmptyDocuments:(BOOL)ignoresEmpty {
NSMutableArray *allDocuments = [NSMutableArray array];
SKIndexDocumentIteratorRef docIterator = SKIndexDocumentIteratorCreate(searchIndex, document);
if ( docIterator == NULL ) goto bail;
SKDocumentRef subDocument = SKIndexDocumentIteratorCopyNext(docIterator);
if ( subDocument == NULL ) goto bail;
while ( subDocument != NULL ) {
CFIndex termCount = 0;
SKDocumentID subDocumentId = SKIndexGetDocumentID(searchIndex, subDocument);
if ( subDocumentId != kCFNotFound ) termCount = SKIndexGetDocumentTermCount(searchIndex, subDocumentId);
if ( !( ignoresEmpty && (termCount == 0) ) ) {
CFURLRef subDocumentURL = SKDocumentCopyURL(subDocument);
if ( subDocumentURL != NULL ) {
[allDocuments addObject:(NSURL*)subDocumentURL];
CFRelease(subDocumentURL);
subDocumentURL = NULL;
}
}
NSArray *subDocuments = [self _allDocumentsForDocumentRef:subDocument ignoreEmptyDocuments:ignoresEmpty];
if ( subDocuments ) [allDocuments addObjectsFromArray:subDocuments];
CFRelease(subDocument);
subDocument = NULL;
subDocument = SKIndexDocumentIteratorCopyNext(docIterator);
}
bail:
if ( docIterator ) CFRelease(docIterator);
return [[allDocuments copy] autorelease];
}
#pragma mark -
- (BOOL) compactStore:(float)tolerance {
BOOL willCompact = NO;
if ( tolerance == 0 ) {
willCompact = YES;
}
else {
SKDocumentID maxDocumentId;
CFIndex documentCount;
[readLock lock];
documentCount = SKIndexGetDocumentCount(searchIndex);
maxDocumentId = SKIndexGetMaximumDocumentID(searchIndex);
[readLock unlock];
if ( documentCount > 0 && maxDocumentId > 0 ) {
CFIndex dif = ( maxDocumentId - documentCount );
willCompact = ( (float)( (float)dif / (float)documentCount ) > tolerance );
}
}
if ( willCompact ) {
if ( indexQue == nil ) {
indexQue = [[NSOperationQueue alloc] init];
[indexQue setMaxConcurrentOperationCount:1];
}
[indexQue addOperationWithBlock:^(void) {
[self _compactIndex];
}];
}
return willCompact;
}
- (BOOL) saveChangesToStore {
// This is actually something we do every time a search or term request is made;
// otherwise the store will not return the correct results. The store is not
// updated until a search or term request is made, even if there have been multiple
// documents added, removed or replaced to the store since the last save.
return [self _flushIndexIfNecessary];
}
- (BOOL) closeStore {
BOOL success = NO;
[self cancelSearch];
[readLock lock];
[writeLock lock];
SKIndexClose(searchIndex);
searchIndex = NULL;
[writeLock unlock];
[readLock unlock];
return success;
}
#pragma mark -
#pragma mark Searching
- (void) prepareSearch:(NSString*)searchQuery options:(SKSearchOptions)searchOptions {
NSAssert( searchQuery!=nil, @"searchQuery must not be nil");
if ( [self isStillSearching] )
[self cancelSearch];
[self _flushIndexIfNecessary];
[readLock lock];
currentSearch = SKSearchCreate(searchIndex, (CFStringRef)searchQuery, searchOptions);
if ( currentSearch == NULL ) NSLog(@"there was a problem creating the search query");
[readLock unlock];
}
- (BOOL) fetchResults:(NSArray**)outDocuments ranksArray:(NSArray**)outRanks untilFinished:(BOOL)untilComplete {
// Convenience method to use NSArray for outRanks. May be slower due to Obj-C overhead.
float * ranks = NULL;
BOOL complete = [self fetchResults:outDocuments ranks:(outRanks==NULL?NULL:&ranks) untilFinished:untilComplete];
if ( outRanks != NULL && ranks != NULL ) {
NSUInteger count = [*outDocuments count];
NSMutableArray *allRanks = [NSMutableArray arrayWithCapacity:count];
NSInteger i;
for ( i = 0; i < count; i++ ) {
[allRanks addObject:[NSNumber numberWithFloat:ranks[i] ]];
}
*outRanks = [[allRanks copy] autorelease];
free(ranks);
}
return complete;
}
- (BOOL) fetchResults:(NSArray**)outDocuments ranks:(float**)outRanks untilFinished:(BOOL)untilComplete {
NSAssert( currentSearch!=NULL, @"currentSearch must not be nil, call prepareSearch:options: prior to this method");
NSAssert( outDocuments!=NULL, @"outDocuments must not be nil");
BOOL stillSearching = YES;
if ( untilComplete ) {
// fetch the results as many times as is necessary until we have acquired all of it
NSMutableArray *allDocuments = [NSMutableArray array];
float * allRanks = NULL;
CFIndex count = 0;
NSInteger i;
while ( stillSearching ) {
NSArray * localResults = nil;
float * localRanks = (outRanks==NULL ? NULL : calloc(self.fetchCount,sizeof(float)) );
NSInteger localCount = 0;
stillSearching = [self _fetchResults:&localResults ranks:localRanks
maxTime:(CFTimeInterval)self.fetchTime
maxCount:(CFIndex)self.fetchCount];
localCount = [localResults count];
count += (CFIndex)localCount;
[allDocuments addObjectsFromArray:localResults];
if ( outRanks != NULL ) { // I need to keep a growing track of the ranks
allRanks = reallocf( allRanks, count*sizeof(float) );
if ( allRanks != NULL ) {
for ( i = 0; i < localCount; i++ ) {
allRanks[i+count-localCount] = localRanks[i];
}
}
free(localRanks);
localRanks = NULL;
}
}
*outDocuments = [[allDocuments copy] autorelease];
if ( outRanks != NULL ) *outRanks = allRanks; // caller must free
}
else {
// perform once, simply passing in the parameters we are given
float * localRanks = (outRanks==NULL ? NULL : calloc(self.fetchCount,sizeof(float)) );
stillSearching = [self _fetchResults:outDocuments ranks:localRanks
maxTime:(CFTimeInterval)self.fetchTime
maxCount:(CFIndex)self.fetchCount];
if ( outRanks != NULL ) *outRanks = localRanks;
}
if ( stillSearching == NO ) {
SKSearchCancel(currentSearch);
CFRelease(currentSearch);
currentSearch = NULL;
}
return stillSearching;
}
- (BOOL) _fetchResults:(NSArray**)outDocuments ranks:(float*)outRanks
maxTime:(CFTimeInterval)maxTime maxCount:(CFIndex)maxCount {
// outRanks should contain enough memory to hold maxCount floats
CFTimeInterval kMaxTime = maxTime;
CFIndex kMaxCount = maxCount;
NSMutableArray *documents = [NSMutableArray array];
BOOL stillSearching = YES;
NSInteger i;
[readLock lock];
float *documentScores = ( outRanks == NULL ? NULL : calloc(kMaxCount,sizeof(float)) );
SKDocumentID *documentIds = calloc(kMaxCount,sizeof(SKDocumentID));
CFURLRef *documentURLs = NULL;
CFIndex documentCount = 0;
stillSearching = SKSearchFindMatches(currentSearch, kMaxCount, documentIds,
documentScores, kMaxTime, &documentCount);
documentURLs = calloc(documentCount, sizeof(CFURLRef));
SKIndexCopyDocumentURLsForDocumentIDs(searchIndex, documentCount, documentIds, documentURLs);
for ( i = 0; i < documentCount; i++ ) {
if ( outRanks != NULL ) outRanks[i] = documentScores[i];
[documents addObject:(NSURL*)documentURLs[i]];
CFRelease(documentURLs[i]);
}
free(documentScores);
free(documentURLs);
free(documentIds);
*outDocuments = [[documents copy] autorelease];
[readLock unlock];
return stillSearching;
}
#pragma mark -
- (float*) copyNormalizedRankings:(float*)inRankings {
float maxValue = 0.0;
NSInteger i;
NSUInteger count = sizeof(inRankings) / sizeof(float);
float *normalizedRankings = calloc(count, sizeof(float));
for ( i = 0; i < count; i++ ) {
if ( inRankings[i] > maxValue ) maxValue = inRankings[i];
}
for ( i = 0; i < count; i++ ) {
normalizedRankings[i] = ( maxValue == 0.0 ? 1.0 : inRankings[i] / maxValue );
}
return normalizedRankings;
}
- (NSArray*) normalizedRankingsArray:(NSArray*)inRankings {
float maxValue = 0.0;
NSUInteger count = [inRankings count];
NSInteger i;
NSMutableArray *normalizedArray = [NSMutableArray arrayWithCapacity:count];
for ( i = 0; i < count; i++ ) {
float val = [[inRankings objectAtIndex:i] floatValue];
if ( val > maxValue ) maxValue = val;
}
for ( i = 0; i < count; i++ ) {
float val = [[inRankings objectAtIndex:i] floatValue];
float normalized = ( maxValue == 0.0 ? 1.0 : val / maxValue );
[normalizedArray addObject:[NSNumber numberWithFloat:normalized]];
}
return [[normalizedArray copy] autorelease];
}
- (BOOL) isStillSearching {
BOOL stillSearching;
[readLock lock];
stillSearching = ( currentSearch != NULL );
[readLock unlock];
return stillSearching;
}
- (void) cancelSearch {
[readLock lock];
if ( currentSearch != NULL ) {
SKSearchCancel(currentSearch);
CFRelease(currentSearch);
currentSearch = NULL;
}
[readLock unlock];
}
#pragma mark -
#pragma mark Document Terms
- (NSArray*) allTerms {
NSAssert( indexType == kSKIndexInvertedVector, @"index must be of type kSKIndexInvertedVector");
[self _flushIndexIfNecessary];
[readLock lock];
// flush the index before calling - (BOOL) writeIndexToDisk
NSMutableSet *allTerms = [NSMutableSet set];
CFIndex maxTermID = SKIndexGetMaximumTermID(searchIndex);
CFIndex aTermID;
for ( aTermID = 0; aTermID < maxTermID; aTermID++ )
{
CFIndex documentCount = SKIndexGetTermDocumentCount( searchIndex, aTermID );
if ( documentCount == 0 ) // may be the case if the index has not been recently flushed
continue;
CFStringRef aTerm = SKIndexCopyTermStringForTermID( searchIndex, aTermID );
if ( aTerm == NULL ) {
NSLog(@"%s - unable to get term for term index %ld", __PRETTY_FUNCTION__, aTermID);
continue;
}
if ( !( self.ignoresNumericTerms && CFStringGetCharacterAtIndex(aTerm,0) < 0x0041 ) )
[allTerms addObject:(NSString*)aTerm];
CFRelease(aTerm);
}
[readLock unlock];
// somewhat annoyingly, SearchKit includes the stop words as document terms
if ( self.stopWords != nil ) [allTerms minusSet:self.stopWords];
NSArray *termsArray = [allTerms allObjects];
return termsArray;
}
#pragma mark -
- (NSUInteger) documentCountForTerm:(NSString*)inTerm {
NSAssert( indexType == kSKIndexInvertedVector, @"index must be of type kSKIndexInvertedVector");
NSAssert( inTerm != nil && [inTerm length] > 0, @"inTerm must not be nil or an empty string" );
[self _flushIndexIfNecessary];
[readLock lock];