簡體   English   中英

SPARQL:基於謂詞對主題進行分組

[英]SPARQL: group subjects based on predicates

在語義網圖中,我有一組主題(S1,S2,...,Sn)和一組謂詞(P1,P2,...,Pn)。 我想根據實例的謂詞對實例進行分組(即,選擇具有相同謂詞集的所有實例,而不管對象的值如何)。

例如,如果我有

S1 P1 v1.
S1 P2 v2.
S2 P3 v3.
S2 P4 v4.
S3 P1 v5.
S3 P2 v6.

我希望有兩組{S1,S3}和{S2}。 我自己生成了圖形,因此如果可以幫助實現此要求,則可以更改其結構。

這比聽起來要復雜一些,而且我不完全確定是否有可能以一種完全通用的方式來實現,但是我認為您可以在大多數端點上實現這一點。 如果你想基於該謂詞,一個對象具有群體,那么你首先需要能夠得到的一組對象具有謂詞,並可以與其他套謂詞進行比較的方法。 SPARQL沒有設置值數據類型的概念,但是使用group_concatdistinct ,您可以獲得包含所有某些謂詞的字符串,並且如果在選擇它們時使用order by ,則大多數端點將保持順序不變,因此group_concat字符串本質上是規范的。 但是,據我所知,該行為並不能得到規范的保證。

@prefix : <urn:ex:>

:S1 :P1 :v1 .
:S1 :P2 :v2 .
:S2 :P3 :v3 .
:S2 :P4 :v4 .
:S3 :P1 :v5 .
:S3 :P2 :v6 .
prefix : <urn:ex:>

#-- The behavior in most (all?) endpoints seems to be
#-- to preserve the order during the group_concat
#-- operation, so you'll get "noramlized" values
#-- for ?preds.  I don't think is *guaranteed*, though.
select ?s (group_concat(?p) as ?preds) where {
  #-- get the values of ?s and ?p and ensure that
  #-- they're in some kind of standarized order.
  #-- Just ordering by ?p might be fine, too.
  { select distinct ?s ?p {
      ?s ?p ?o
    }
    order by ?p
  }
}
group by ?s
-------------------------------
| s   | preds                 |
===============================
| :S2 | "urn:ex:P3 urn:ex:P4" |
| :S3 | "urn:ex:P1 urn:ex:P2" |
| :S1 | "urn:ex:P1 urn:ex:P2" |
-------------------------------

現在,您只需要更進一步,然后將這些結果按?preds分組即可:

prefix : <urn:ex:>

select (group_concat(?s) as ?subjects) {
  select ?s (group_concat(?p) as ?preds) where {
    { select distinct ?s ?p {
        ?s ?p ?o
      }
      order by ?p
    }
  }
  group by ?s
}
group by ?preds
-------------------------
| subjects              |
=========================
| "urn:ex:S1 urn:ex:S3" |
| "urn:ex:S2"           |
-------------------------

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM