GRAQL中的递归查询?

问题描述

是否有一种方法可以在GRAQL中定义递归查询,即匹配实体之间确切谓词路径未知(例如,其中有多少个实体)的模式?

SPARQL在1.1版本中添加了对这些功能的支持。 Apache Jena Documentation中的示例:

# Find the types of :x,following subClassOf
SELECT *
{
   :x  rdf:type/rdfs:subClassOf*  ?t
}

CYPHER也从一开始就允许他们使用。示例:

MATCH (alice:Person { name:"Alice" })-[:friend *1..2]->(friend:Person)
RETURN friend.name;

是否可以在GRAQL中做类似的事情?

解决方法

可以使用Grakn的推理引擎在Graql中实现这一目标。

Graql match查询不支持循环查询语法(虽然,但已计划),但是您可以使用rule在Grakn中定义递归逻辑。为了实现递归,应该有一个规则,在其when中包含与规则then中推断出的类型相同的内容。

在Graql中,此确切的friend示例如下。此示例不使用递归,因为我们只在寻找1或2跳循环。

首先,您需要一个架构:

define

name sub attribute,value string;

person sub entity,has name,plays friend;

friend sub relation,relates friend;

如果这是您的初始模式,则需要按如下所示扩展它,以在新的n-degree-friendship关系中添加递归:

define

friend-of-a-friend isa relation,relates connected-friend;

person sub entity,plays connected-friend;

infer-friend-of-a-friend sub rule,when {
  (friend: $p1,friend: $p2) isa friendship;
  (friend: $p2,friend: $p3) isa friendship;
},then {
  (connected-friend: $p1,connected-friend: $p3) isa friend-of-a-friend;
};

然后,您可以查询通过任意数量的friendship关系建立联系的朋友:

match $p1 isa person,has name "John"; 
$p2 isa person,has name $n;
{ (connected-friend: $p1,connected-friend: $p2) isa friend-of-a-friend; } 
or { (friend: $p1,friend: $p2) isa friendship; };
get $n;

friend示例不是递归的,但可以扩展为递归。 Grakn当前无法支持的是循环次数。

尽管如此,我们在subClassOf示例中看到了一个很好的递归示例:

define

class sub entity,plays subclass,plays superclass;

class-hierarchy sub relation,relates subclass,relates superclass;

class-hierarchy-is-recursive sub rule,when {
  (subclass: $c1,superclass: $c2) isa class-hierarchy;
  (subclass: $c2,superclass: $c3) isa class-hierarchy;
},then {
  (subclass: $c1,superclass: $c3) isa class-hierarchy;
};

然后匹配以找到x的所有子类:

match $x isa class; 
$y isa class; 
(superclass: $x,subclass: $x) isa subclass;
get $y;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...