tags:

views:

73

answers:

2

In this simple sparql query I get a list of subjects whose object is 42

SELECT ?v WHERE { ?v ?p 42 }

If I add ?p as a variable

SELECT ?v ?p WHERE { ?v ?p 42 }

I will get two entities per row, the subject and the predicate. What if I wanted three entities, so including the 42? Something like:

SELECT ?v ?p ?m WHERE { ?v ?p (42 as m) }
+2  A: 

Standard SPARQL 1.0 does not really allow that. There may be some implementation-specific extensions for doing it, though.

As a workaround, if the data contains a triple with 42 as an object literal, you can do it e.g. like this:

SELECT ?v ?p ?m { ?v ?p 42, ?m FILTER(?m=42)}

which is equivalent with

 SELECT ?v ?p ?m WHERE { ?v ?p 42 . ?v ?p ?m FILTER(?m=42)}

as you can write graph patterns sharing the same subject and predicate with the comma object list notation, and the WHERE keyword is optional.

For efficiency, you want to use basic graph patterns to reduce the working triple to a smaller set and only then apply FILTER expressions to further prune the results.

laalto
Just realised that this doesn't work properly - this results in selecting any Triples that have the same subject and predicate as those with the object 42 so you potentially get a load of miscellaneous triples which are irrelevant to your query
RobV
@RobV: True, thanks for pointing that out. I've revised the answer.
laalto
Yeah that works perfectly now
RobV
A: 
select ?v ?p ?m where { ?v ?p ?m . FILTER( ?m = 42 ) }
Pēteris Caune
It would seem sensible but depending on your Triple Store and SPARQL engine it is likely to be very inefficient as a lot of SPARQL engines do FILTERs in-memory which means you'd effectively load the entire dataset (since ?v ?p ?m matches everything) and then have to FILTER over all of it for objects which are 42
RobV
True, but any SPARQL feature can be inefficient depending on Triple Store. For example, LIMIT and OFFSET seem like sensible things, these should work fast, right? For example on AllegroGraph these are postprocessing instructions, so very slow if you have lots of data.With regards to filter, FILTER, at least on Virtuoso it's very efficient, it translates to very simple SQL query with just two WHERE conditions.
Pēteris Caune
For a simple FILTER like this then it would translate to a simple SQL query assuming your store is SQL based. LIMIT and OFFSET are typically post-processing in any SPARQL implementation since you need to apply FILTERs and ORDER BYs before you can apply them - I would not expect them to be fast over large datasets. For such a case anyway laalto's approach is more efficient and more portable across different SPARQL implementations
RobV
I never took a close look at laalto's approach, it didn't look right in the beginning. But yeah, it is indeed better and would work better than mine in general case.
Pēteris Caune
Well it did have an error in it originally until he edited it the other day
RobV