GalB1t
GalB1t

Reputation: 265

Retrieving distinct values with rdflib

The following python code is part of a larger piece (everything else is working fine):

import rdflib

g1 = rdflib.Graph()
g1.parse("existing_graph.nt", format="nt")

q = "select ?ent_a ?ent_b where { ?ent_a <http://www.example.org/rel> ?c . " \
    "?ent_b <http://www.example.org/rel> ?c. }"
res = g1.query(q)

I wish to get in my results only cases where ent_a differs from ent_b and can't find the relevant documentation.

Upvotes: 0

Views: 396

Answers (3)

Terran
Terran

Reputation: 1149

Why do you run slow SPARQL queries when you loaded the whole graph into memory already? You can loop over tripples in any way you want and compare for equalness etc. http://rdflib.readthedocs.org/en/latest/intro_to_graphs.html#basic-triple-matching

Upvotes: 0

AndyS
AndyS

Reputation: 16630

You will get every differerent ?a ?b pair with FILTER !=, but also ?b ?a (the pair reversed)

If ?a and ?b are URIs, then this pattern may help:

select *
where {
    ?a a ?s.
    ?b a ?s.
filter (str(?a) > str(?b))
} 

Upvotes: 2

Artemis
Artemis

Reputation: 3301

The easiest way to just say that two things are not the same is to use != sign.

select distinct *
where {
    ?a a ?s.
    ?b a ?s.
filter (?a!=?b)
} 

However, this query is very strange because by just writing:

select distinct *
where {
    ?a ?p ?s.
} 

You are able to extract every distinct ?a that has a ?p relation with ?s. Thus, depending on your use, you have already generated your result set.

If you need to dig deeper, as per your comment:

I have an ontology where objects of type "teams" have a "locatedIn" relationship with their "hometown", and I wish to find all of the possible local derbies.

You need to add more restrictions by adding another triple that relates to the first tripe. For example, in dbpedia, the following query will give you all the teams and their grounds:

select distinct *
where{
    ?o a dbpedia-owl:SportsTeam.
    ?o dbpedia-owl:ground ?ground.
}

Upvotes: 1

Related Questions