I have a system build with micro-services (user service and device service) with hierarchy data:
Data is separated by organization. Users in OrgA
can see all the data (including data in OrgB
, OrgC
, OrgD
, OrgE
, OrgF
and OrgG
). However, users in OrgG
can only see the data in OrgG
.
organization
table (using nested set model + Adjacency List Model):
CREATE TABLE organization (
id serial primary key,
name varchar(50),
parent_id int,
lft int,
rgh int
);
user
table:
CREATE TABLE user (
id serial primary key,
name varchar(20),
org_id int
);
device
table (use org_id
field to separate organization's device):
CREATE TABLE device (
id serial primary key,
mac varchar(20),
org_id int
);
I created an API to use the nested set model algorithm to find children nodes:
SELECT p.id
FROM organization as p
INNER JOIN user as u ON u.org_id = p.id
INNER JOIN organization as c ON p.lft <= c.lft AND p.rgh >= c.rgh;
When I need to query the authorized device list in device micro service, I need to call the user service to get an authorized organization list first, and use this list to filter:
SELECT * FROM device WHERE org_id IN ([MY-AUTHORIZED-ORGANIZAITON-ID-LIST]);
But when I have a deep hierarchy the database has to perform an IN operator on a large set. This seems not efficient. How to implement the hierarchy data query in micro-service environment without losing performance?