简体   繁体   中英

Gremlin - Best way to select properties from multiple vertices in single query

I have two related vertices with labels 'DeviceFamily' and 'Device'. They are related as shown below:

(DeviceFamily)-[:RELATION]->(Device)

The DeviceFamily vertex has a few properties say p,q,r and Device vertex has properties say x,y,z.

Given a Device id, if I require to find out x,y,z properties of the corresponding Device vertex and p,q,r properties of the related DeviceFamily, what query should I execute?

One solution I found is:

g.V('<id>').hasLabel('Device').as('d1', 'd2', 'd3').inE('RELATION').outV().as('f1', 'f2', 'f3').select('d1', 'd2', 'd3', 'f1', 'f2', 'f3').by('x', 'y', 'z', 'p', 'q', 'r');

This query works but I am not sure if this is the best way to do it. Please let me know if there is a better way.

Thanks.

I think that you should use some form of project() :

g.V('<id>').
  project('device','family').
    by(__.valueMap('x','y','z'))
    by(__.in('RELATION').valueMap('p','q','r'))

Note that I omitted the hasLabel('Device') as it's redundant as you know the unique identifier for the vertex. Further note that while I used valueMap() in the by() modulators of project() you could easily supply any Gremlin you want there to shape your data into those two keys (I just chose valueMap() as it's convenient to write).

If you'd like something more matched to your output you could still use project() in this direct fashion (i've been assuming there is only one "RELATION" edge - hope that is the case):

g.V('<id>').
  project('x','y','z','p','q','r').
    by('x').
    by('y').
    by('z').
    by(in('RELATION').values('p')).
    by(in('RELATION').values('q')).
    by(in('RELATION').values('r'))

I don't think most graph databases will optimize the final three by() modulators to a single traverse over the "RELATION" edge. I'd therefore suggest a slight adjustment - project() the edge instead:

g.V('<id>').
  inE('RELATION').
  project('x','y','z','p','q','r').
    by(inV().values('x')).
    by(inV().values('y')).
    by(inV().values('z')).
    by(outV().values('p')).
    by(outV().values('q')).
    by(outV().values('r'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM