Created
July 17, 2018 19:37
-
-
Save Palleas/49bd6240ae894b79bf5d470a0e2324ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import os.log | |
final class Searcher { | |
struct Result: Equatable { | |
let count: Int | |
let hasMore: Bool | |
} | |
let indexer: Indexer | |
init(index: Indexer) { | |
self.indexer = index | |
} | |
func search(query: String) -> Result { | |
let flushed = indexer.flush() | |
print("Flushed = \(flushed ? "yes": "no")") | |
let options = SKSearchOptions(kSKSearchOptionDefault) | |
let skSearch = SKSearchCreate(indexer.index, query as NSString, options).takeRetainedValue() | |
var documentIDs = [SKDocumentID]() | |
var scores = [Float]() | |
var foundCount = 0 | |
let hasMore = SKSearchFindMatches(skSearch, 100, &documentIDs, &scores, 0, &foundCount) | |
return Result(count: foundCount, hasMore: hasMore) | |
} | |
} | |
final class Indexer { | |
enum IndexerError: Error { | |
case unableToCreate | |
} | |
let index: SKIndex | |
init(url: URL, name: String) throws { | |
guard let index = SKIndexCreateWithURL(url as NSURL, name as NSString, SKIndexType(kSKIndexInverted.rawValue), nil)?.takeRetainedValue() else { | |
throw IndexerError.unableToCreate | |
} | |
self.index = index | |
} | |
func flush() -> Bool { | |
return SKIndexFlush(index) | |
} | |
func index(_ source: Searchable) { | |
let objectURL = source.URIRepresentation as NSURL | |
let document = SKDocumentCreateWithURL(objectURL).takeRetainedValue() | |
let indexed = SKIndexAddDocumentWithText(index, document, source.summary as NSString, true) | |
os_log("Indexed to disk: %@", indexed ? "true" : "false") | |
let flushed = self.flush() | |
os_log("Flushed index to disk: %@", flushed ? "true" : "false") | |
} | |
func createSearch() -> Searcher { | |
return Searcher(index: self) | |
} | |
func search(query: String) -> Searcher.Result { | |
return createSearch().search(query: query) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment