简体   繁体   中英

Exclude Objects from realm query - attempting to sort by relevance (Swift)

I need to sort search results by relevance, while attempting to work around Realm's NSPredicate limitations.

My current attempt duplicates results:

if searchText.characters.count > 0 {
        //First search is attempting exact match
        relevantResults = Array(dataModel.terms.filter("%K BEGINSWITH[c] %@", "title", searchText).sorted(byProperty: "title"))
        //Appended Results are looking for 'close enough' but include results that were already in the first search
        relevantResults.append(contentsOf: Array(dataModel.terms.filter("%K CONTAINS[c] %@", "title", searchText).sorted(byProperty: "title")))
    } else {
        relevantResults = Array()
    }

I've tried to get creative with some other predicate filters such as:

"title NOT BEGINSWITH[c] %@ AND title CONTAINS[c] %@"

and

"SELF NOT IN %@"

Which are either not supported by Realm, or not valid predicate filters. Either way I need to find a solution to sort by relevance without duplicates.

There will be more search results shown in a separate TableView Section, that I would like to exclude the "best match" results as well.

I want to avoid looping to get all the titles from the first set of results if possible, but it seems like I may have to resort to that, unless there are some array functions that I'm not considering? Any suggestions?

Apparently my predicate string was a little off.

"title CONTAINS[c] %@ AND NOT title BEGINSWITH[c] %@"

ended up working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM