dgraph

Query variables in Dgraph filter


I am trying to use a variables (which is a scalar) in a @filter(ge(...)) call, but I run into an error

Given the following query

{
  ua(func: uid(0xfb7f7)) {
    uid
    start_ua {
      sua as index
    }
    recorded_in {
      actions @filter(ge(index, sua)){
        index
      }
    }
  }
}

I get the following error

{
  "errors": [
    {
      "code": "ErrorInvalidRequest",
      "message": "Some variables are defined but not used\nDefined:[sua]\nUsed:[]\n"
    }
  ],
  "data": null
}

Now if I remove the sua as ... and the @filter(...) from the query, all works fine. My Dgraph version is v1.0.13.

I tried replacing @filter(ge(index, sua)) with @filter(ge(index, val(sua))) but I still run into an error:

{
  "errors": [
    {
      "code": "ErrorInvalidRequest",
      "message": ": No value found for value variable \"sua\""
    }
  ],
  "data": null
}

What am I doing wrong?


Solution

  • Here's what the Dgraph docs say about value variables (emphasis added): https://docs.dgraph.io/query-language/#value-variables

    Value variables store scalar values. Value variables are a map from the UIDs of the enclosing block to the corresponding values.

    It therefore only makes sense to use the values from a value variable in a context that matches the same UIDs - if used in a block matching different UIDs the value variable is undefined.

    The start_ua and recorded_in are different subgraphs, which means variables defined in one are undefined in the other within the same query block.

    What you can do is use multiple query blocks. Variables can be accessed across blocks:

    {
      block1(func: uid(0xfb7f7)) {
        uid
        start_ua (first: 1) {
          sua as index
        }
    
      }
      
      block2(func: uid(0xfb7f7)) {
        recorded_in {
          actions @filter(ge(index, val(sua))) {
            index
          }
        }
      }
    }
    

    I also added (first: 1) to the start_ua predicate, so that at most 1 node is fetched and stored the sua variable. If your data is already structured that way, then that's not needed.

    val(sua) gets the value of the variable sua.