Gremlin query to order vertices with some locked to specific positions

I'm working with a product catalog in a graph database using Gremlin.

The graph structure includes:

  1. Product vertices
  2. Category vertices
  3. belongsTo edges connecting products to categories. The edge can have an optional lockedPosition property as integer.
I need to create a query that returns products in a specific order, where:

  1. Some products are "locked" to specific positions (stored as a lockedPosition property on the belongsTo edge)
  2. Other "unlocked" products should fill in around these fixed positions
For example, if I have 20 products in a category, and product A is locked to position 3 and product B to position 7, the result should return these products in those exact positions, with other products filling the remaining slots with whatever sorting order. (this "product pinning/locking" functionality is used by merchandising team to manually re-arrange products on a product listing page).

Can anyone suggest a Gremlin query to achieve this?

Also, maybe my data model is wrong for this use case, so I am also keen to accept other suggestions to represent this use case.

Thank you!
Solution
you can play tricks like this to move the 0 index to last place, but that still leaves the 7 one row off
gremlin> g.V().hasLabel("Category").
......1>       inE("belongsTo").as('a').outV().
......2>       path().
......3>         from('a').
......4>         by(coalesce(values('lockedPosition'),constant(0))).
......5>         by('name').
......6>         fold().
......7>         index().
......8>         unfold().
......9>         order().
.....10>           by(choose(limit(local,1).limit(local,1).is(neq(0)),limit(local,1).limit(local,1),tail(local))).
.....11>           by(limit(local,1),desc).
.....12>         fold().
.....13>         union(range(local,1,-1).unfold(),limit(local,1)).fold().unfold()   
==>[[0,Product6],1]
==>[[0,Product1],2]
==>[[3,Product10],9]
==>[[0,Product7],3]
==>[[0,Product2],4]
==>[[0,Product8],5]
==>[[0,Product3],6]
==>[[7,Product9],7]
==>[[0,Product4],8]
==>[[0,Product5],0]               
Was this page helpful?