Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Query): Add random keyword in DQL #7693

Merged
merged 3 commits into from
Apr 25, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions gql/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2595,7 +2595,7 @@ func parseLanguageList(it *lex.ItemIterator) ([]string, error) {

func validKeyAtRoot(k string) bool {
switch k {
case "func", "orderasc", "orderdesc", "first", "offset", "after":
case "func", "orderasc", "orderdesc", "first", "offset", "after", "random":
return true
case "from", "to", "numpaths", "minweight", "maxweight":
// Specific to shortest path
Expand All @@ -2609,7 +2609,7 @@ func validKeyAtRoot(k string) bool {
// Check for validity of key at non-root nodes.
func validKey(k string) bool {
switch k {
case "orderasc", "orderdesc", "first", "offset", "after":
case "orderasc", "orderdesc", "first", "offset", "after", "random":
return true
}
return false
Expand Down
49 changes: 48 additions & 1 deletion query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"fmt"
"math"
"math/rand"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -114,6 +115,8 @@ type params struct {
Count int
// Offset is the value of the "offset" parameter.
Offset int
// Random is the value of the "random" parameter
Random int
// AfterUID is the value of the "after" parameter.
AfterUID uint64
// DoCount is true if the count of the predicate is requested instead of its value.
Expand Down Expand Up @@ -745,6 +748,15 @@ func (args *params) fill(gq *gql.GraphQuery) error {
}
args.Count = int(first)
}

if v, ok := gq.Args["random"]; ok {
random_, err := strconv.ParseInt(v, 0, 32)
Samyak2 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}
args.Random = int(random_)
}

return nil
}

Expand Down Expand Up @@ -2298,6 +2310,13 @@ func ProcessGraph(ctx context.Context, sg, parent *SubGraph, rch chan error) {
}
}

if sg.Params.Random > 0 {
if err = sg.applyRandom(ctx); err != nil {
rch <- err
return
}
}

// Here we consider handling count with filtering. We do this after
// pagination because otherwise, we need to do the count with pagination
// taken into account. For example, a PL might have only 50 entries but the
Expand Down Expand Up @@ -2395,6 +2414,34 @@ func ProcessGraph(ctx context.Context, sg, parent *SubGraph, rch chan error) {
rch <- childErr
}

// applies "random" to lists inside uidMatrix
// Params.Random number of nodes are selected
// duplicates are not removed i.e., random selection by replacement is done
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not have duplicate results. I'd suggest having some map to keep track of what all we have already picked to randomly pick n unique results.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I'll do this, along with the filters application.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think you need to do anything for filters. You are already doing the random selection after filter application and pagination.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh okay. That explains why I couldn't figure out how to do it by looking at pagination xD.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have pushed a commit fixing these.

To remove duplicates, I had to:

  • introduce a new struct UidKey to store the index of a UID in the matrix
  • calculate total number of nodes and check if required number of nodes is less than that. If it's not, return all the nodes.

Because of the condition if sg.Params.Random >= totalNodes at line 2440, when the required number of nodes (sg.Params.Random) is equal to the total number of nodes, all of the nodes are returned without any processing. I did this thinking of it as an optimization (because there will be many overlaps in random numbers when only a few nodes are left to be selected). But I just realized that this will make it so that the order is not randomized when sg.Params.Random == totalNodes. Should I fix this to do the random selection even when all the nodes have to be selected?

// TODO: error handling here
func (sg *SubGraph) applyRandom(ctx context.Context) error {
sg.updateUidMatrix()

// store row id -> new uid list mapping
newUids := make(map[int][]uint64)
for i := 0; i < sg.Params.Random; i++ {
randomIdx := rand.Intn(len(sg.uidMatrix))
randomIdy := rand.Intn(len(sg.uidMatrix[randomIdx].Uids))

if newUids[randomIdx] == nil {
newUids[randomIdx] = make([]uint64, 0)
}

newUids[randomIdx] = append(newUids[randomIdx], sg.uidMatrix[randomIdx].Uids[randomIdy])
}

for idx, uids := range newUids {
sg.uidMatrix[idx].Uids = uids
}

sg.DestMap = codec.Merge(sg.uidMatrix)
return nil
}

// applyPagination applies count and offset to lists inside uidMatrix.
func (sg *SubGraph) applyPagination(ctx context.Context) error {
if sg.Params.Count == 0 && sg.Params.Offset == 0 { // No pagination.
Expand Down Expand Up @@ -2638,7 +2685,7 @@ func (sg *SubGraph) sortAndPaginateUsingVar(ctx context.Context) error {
func isValidArg(a string) bool {
switch a {
case "numpaths", "from", "to", "orderasc", "orderdesc", "first", "offset", "after", "depth",
"minweight", "maxweight":
"minweight", "maxweight", "random":
return true
}
return false
Expand Down