Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
- }
Add Comment
Please, Sign In to add comment