[SPARQL][WIKIDATA] FILTER vs FILTER EXISTS
FILTER vs FILTER EXISTS
How did I encounter this?
While writing SPARQL queries, I needed to implement filtering to retrieve specific results. I got to find that there are 2 similar keywords with different sytanx : FILTER and FILTER EXISTS.
Syntax
FILTER(...)
It evaluates a boolean expression over variables in the current solution. If the expression is
It evaluates a boolean expression over variables in the current solution. If the expression is
true, the row is kept; otherwise, it’s discarded. FILTER EXISTS { ... }
It evaluates whether a pattern exists in the data. If the inner pattern can be matched, the row is kept; if not, it’s excluded. More specifically, it evaluates whether an extra pattern can match for each solution.
It evaluates whether a pattern exists in the data. If the inner pattern can be matched, the row is kept; if not, it’s excluded. More specifically, it evaluates whether an extra pattern can match for each solution.
Both can refine results, but they handle conditions differently:
FILTER is about variable-based logic, while FILTER EXISTS is about data patterns in the underlying RDF graph.Details
FILTER(...) for Logical Expressions
Usage
FILTER(CONTAINS(LCASE(?label), "ragnarok"))Here, SPARQL checks if ?label (lowercased) contains the substring "ragnarok". If yes, that solution is retained; if no, it’s removed. It focuses on conditions involving variables (comparisons, string operations, numeric checks).
FILTER EXISTS { ... } for Pattern Matching
Usage
SELECT ?itemWHERE { ?item wdt:P136 wd:Q859369. # item has genre = "action game" FILTER EXISTS { ?item wdt:P400 wd:Q500446. # item also has platform = "PlayStation 5" }}This means: keep ?item only if it is an action game and that same ?item can be matched with “platform = PlayStation 5.” If FILTER EXISTS fails, the row is removed.
Comments
Post a Comment