How to count the number of matches from a compound WHERE query

I am trying to create a table with related notes, based on four criteria: (1) notes that link to the current note; (2) notes that are linked from the current note; (3) notes that share at least one tag with the current note; (4) notes with a tag that matches the name of the current file. I can do this with the following query:

TABLE type as "type"
WHERE contains(file.outlinks, this.file.link) OR contains(file.inlinks, this.file.link) OR any(contains(file.tags, this.file.tags)) OR any(contains(file.tags, this.file.name)) AND file.name != this.file.name
SORT type ASC

However, I would want to sort the table by a make-shift relevance score, i.e., notes returned by the query above should be ranked (=sorted) higher based on (1) the number of criteria met and (2) the number of tags that are shared with the current page.

I have no idea where to start – any help would be greatly appreciated!