I am currently using this whereField on my query for documents:
.whereField("tags", arrayContainsAny: ["Sports", "Fashion", "Gaming"])
.
Where the “tags” field is an array of strings (ex: [“Sports”, “Gaming”]. This works great to filter out any documents that have the tags field with none of the arrayContainsAny values in it. I am hoping to be able to sort the returned documents by number of tags inside of the arrayContainsAny array. For example if the tags field for a document had one value in the arrayContainsAny, it would have lower priority than one that had two values in the arrayContainsAny and so on. The logic would look something like this:
documents = documents.sorted { first, second in
let firstNumberOfTagsInFilters = filters.filter { first.tags?.contains($0) ?? false }.count
let secondNumberOfTagsInFilters = filters.filter { second.tags?.contains($0) ?? false }.count
return firstNumberOfTagsInFilters > secondNumberOfTagsInFilters
}
The above code block works great to sort the returned documents. The only issue is I am using pagination with my query, so I wouldn’t be able to sort the documents like this since I only retrieve a certain amount at a time:
query
.whereField("tags", arrayContainsAny: tags)
.limit(to: count)
.startOptionally(afterDocument: lastDocument)
Is it possible to add this sort functionality in the query itself, before the limit? If not maybe an array isn’t the best approach for these tags and different way is possible?
user24923683 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.