使用SPARQL查找列表中元素的相对位置

时间:2018-04-25 05:01:04

标签: sparql

我试图根据主题在有序列表中的相对位置返回主题。

主题可以与多个对象相关联(通过单个谓词),并且所有对象都在有序列表中。给定此列表中的参考对象,我希望按照对象与参考对象的相对距离的顺序返回主题。

:a : :x     
:b : :v
:b : :z
:c : :v
:c : :y

:ls :list (:v :w :x :y :z)

将x作为列表中的起始对象,下面的代码返回

:a :x :0
:c :y :1
:b :v :2
:b :z :2
:c :v :2

我不想返回所有位置,而只希望与主题相关的对象的最小对象距离'要返回(这可能意味着每个主题最多两个对象 - 在列表中上下)。所以我想回来

:a :x :0
:c :y :1
:b :v :2
:b :z :2

到目前为止的代码...... (得到了Find lists containing ALL values in a set?Is it possible to get the position of an element in an RDF Collection in SPARQL?

的大量帮助
SELECT ?s ?p (abs(?refPos-?pos) as ?dif) 
WHERE {
      :ls :list/rdf:rest*/rdf:first ?o .
      ?s : ?o .
      {
      SELECT ?o (count(?mid) as ?pos) ?refPos 
      WHERE {
            [] :list/rdf:rest* ?mid . ?mid rdf:rest* ?node .
            ?node rdf:first ?o .
            {
            SELECT ?o (count(?mid2) as ?refPos)
            WHERE {
                  [] :list/rdf:rest* ?mid2 . ?mid2 rdf:rest* ?node2 .
                  ?node2 rdf:first :x .
                  }
            }
            }
            GROUP BY ?o
      }
      }
      GROUP BY ?s ?o
      ORDER BY ?dif

我一直试图通过分组来获得最小的差异(差异/距离),但因为我必须将这个(类似于?dif =?minDif)应用于?s?o分组从早些时候开始,我不知道如何在这两个分组之间前后移动。

感谢您提供的任何帮助

1 个答案:

答案 0 :(得分:1)

所有你需要复合解决方案的是Joshua Taylor的另一个回答:thisthis

下面我使用Jena函数,但我希望这个想法很清楚。

查询1

PREFIX list: <http://jena.hpl.hp.com/ARQ/list#>
SELECT ?s ?el ?dif {
    ?s : ?el .
    :ls :list/list:index (?pos ?el) .
    :ls :list/list:index (?ref :x) .
    BIND (ABS(?pos -?ref) AS ?dif) 
    {
    SELECT ?s (MIN (?dif_) AS ?dif) WHERE {
        ?s : ?el_ .
        :ls :list/list:index (?pos_ ?el_) .
        :ls :list/list:index (?ref_ :x) .
        BIND (ABS(?pos_ - ?ref_) AS ?dif_)
        } GROUP by ?s
    }
}

查询2

PREFIX list: <http://jena.apache.org/ARQ/list#>    
SELECT ?s ?el ?dif {
    ?s : ?el .
    :ls :list/list:index (?pos ?el) .
    :ls :list/list:index (?ref :x) .
    BIND (ABS(?pos -?ref) AS ?dif) 
    FILTER NOT EXISTS {
        ?s : ?el_ .
        :ls :list/list:index (?pos_ ?el_) .
        BIND (ABS(?pos_ - ?ref) AS ?dif_) .
        FILTER(?dif_ < ?dif)                                           
    }
}

<强>更新

可以用这种方式重写查询1:

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

SELECT ?s ?el ?dif {
  ?s : ?el 
  { select (count(*) as ?pos) ?el {[] :list/rdf:rest*/rdf:rest*/rdf:first ?el} group by ?el }
  { select (count(*) as ?ref)     {[] :list/rdf:rest*/rdf:rest*/rdf:first :x} } 
  BIND (ABS(?pos - ?ref) AS ?dif) 
  {
  SELECT ?s (MIN(?dif_) AS ?diff) {
    ?s : ?el_ 
    { select (count(*) as ?pos_) ?el_ {[] :list/rdf:rest*/rdf:rest*/rdf:first ?el_} group by ?el_ }
    { select (count(*) as ?ref_)      {[] :list/rdf:rest*/rdf:rest*/rdf:first :x} } 
    BIND (ABS(?pos_ - ?ref_) AS ?dif_)
    } GROUP by ?s
  }
  FILTER (?dif = ?diff)
}

备注

  • 正如您所看到的,这不是SPARQL的设计目标。例如,Blazegraph支持Gremlin ......
  • 可能这不是RDF的设计目标。或者尝试其他建模方法:你真的需要RDF列表吗?
  • 我还没有在Virtuoso中测试过上述查询。