Aswathi Raj K T
Aswathi Raj K T

Reputation: 71

Query inner elements based on role in grakn

I have a keyspace name 'server' in grakn with one entity named 'node' having an attribute "name". This keyspace is having only one relation named 'node_relation' that connects entities. The entity node acts the role as 'base' and 'dependent' in the node_relation.

Graph for keyspace : server

This graph is aligned in such a way that all the elements in the left side are acting as base and right side act ad dependent in the node_relation.

I need to query nodes that act as base node for an entity and if the queried node has any node that is acting as a base node, I need to get it also until the queried node is not having any nodes with role base.

For example, if I want all nodes with role base for node named "F", I should get the answer as of "A,B,C,D,E,DD,EE,FF,XX,YY,ZZ".

Currently i am using the query

match $x isa node, has name "F";$y isa node;$rel(base:$x,$y);get $y;** 

This query return E and DD as result and i will execute this query until a node is not having any node with role base.

Is their any some way to get all the node in a single query ?

Upvotes: 1

Views: 104

Answers (1)

Adam Mitchell
Adam Mitchell

Reputation: 61

Disclaimer: I'm pretty new to Grakn still.

The kind of relation you are looking for is transitive (if a->b and b->c then a->c). You can use Grakn rules to model this relation then use it in your query; Grakn infers the transitive relation when you execute the query.

Here's how I wrote the rules, include this in your schema.gql:

node_superrelation sub relation,
  relates base,
  relates dependent;

node-relation-is-superrelation-rule sub rule,
  when {
    (base: $a, dependent: $b) isa node_relation;
  },
  then {
    (base: $a, dependent: $b) isa node_superrelation;
  };

node-superrelation-is-transitive-rule sub rule,
  when {
    (base: $a, dependent: $b) isa node_superrelation;
    (base: $b, dependent: $c) isa node_superrelation;
  },
  then {
    (base: $a, dependent: $c) isa node_superrelation;
  };

Now you can use the following query to get all bases of node F. Note that we specifically request those related by a node_superrelation.

match $d isa node, has name "F";$b isa node; $rel(base:$b,dependent:$d) isa node_superrelation;get $b;

You could make node_relation transitive and achieve this in one rule, but then queries using node_relation of F would always include all of the results without using a limit, which is probably not what you want. You could also define new roles for node_superrelation, which may also further simplify things, or use the shared roles to some other advantage. Hopefully, you can see that Grakn's rules are really very powerful and should let you describe these kinds of relations in a way that makes sense for your model!

Hope this helps!

EDIT: Just to add quickly that the convention in Grakn is to use hyphens rather than underscores.

Upvotes: 1

Related Questions