How to query for nodes belonging to intersection/union of two or more groups?

Hello,
I am wondering if there is an easy way to query for nodes that belong to the intersection of two (or more) groups, as you would do with filters.

Say we have group1 and group2, and the question is how to get the nodes in common. The following snippet doesn’t work of course:

q = QueryBuilder()
q.append(Group,filters={'label':'goup1'}, tag='g1')
q.append(Group, filters={'label':'goup2'}, tag='g2')
q.append(Node, with_group='g1')
q.append(Node, with_group='g2')

It would be nice something like:

q.append(Group,filters={'label':'goup1'}, tag='g1')
q.append(Group, filters={'label':'goup2'}, tag='g2')
q.append(Node, with_groups=['g1','g2'])

Any suggestion how to do this the best way?

Good question. Unfortunately, as far as I am aware, this syntax is not available and so the best I can think of is to do it in two queries:

builder = QueryBuilder()
builder.append(Group, filters={'label': 'group1'}, tag='g')
builder.append(Node, with_group='g', project='id')
pks = builder.all(flat=True)

builder = QueryBuilder()
builder.append(Group, filters={'label': 'group2'}, tag='g')
builder.append(Node, with_group='g', filters={'id': {'in': pks}})
nodes = builder.all(flat=True)

It would be great if we could support the syntax you sketched out, but not sure if it is possible to implement. Maybe the performance of the alternative above is not so bad compared to a single query. Of course if group1 is large, having to load all pks into memory is not ideal.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.