Need Query Help

I need some help formulating a query:

schema:

type Foo {
   bars: [Bar!]!
}

type Bar {
   name: String!
}

I want to get all Foos that have a Bar with name == “Alice” and a Bar with name == “Bob”.
I don’t want to get incomplete Foos, i.e. entities that only have a bar with one of these names.
I also don’t want to add another field to Foo

Preferable this should be done using GraphQL, but DQL would also be possible.

Thanks!

in DQL

{ 
   var(func: has(Foo.bars){
        B as Foo.bars
  }
    q(func: uid(B)) @filter(eq(Bar.name, "Alice")) {
       Bar.name
   }
}

In GraphQL is another Story. I would have to get my head in sync with GraphQL to be able to help you. As GraphQL doesn’t have multi-blocks and variables. I think this strategy is quite different.

How you’d do it in graphql is something like this:

{
   queryFoo {
       bars (filter: {name: $name}  { name }
   }
   queryBar (filter: {name: "Bob"}) { name }
}

Hi @MichelDiz ,

thanks for your suggestion. But that was not what I was trying to achieve.
Given this database state:

{
  "data": {
    "queryFoo": [
      {
        "id": "123",
        "bars": [
          {
            "id": "1",
            "name": "Alice"
          },
          {
            "id": "2",
            "name": "Bob"
          }
        ]
      },
      {
        "id": "1234",
        "bars": [
          {
            "id": "12",
            "name": "Alice"
          }
        ]
      }
    ]
  },

I want to query only the Foo with id=“123”.

Your query returns:

"data": {
    "q": [
      {
        "Bar.name": "Alice"
      },
      {
        "Bar.name": "Alice"
      }
    ]
  },

The correct result that I need to query would be:

"data": {
    "q": [
      {
        "Foo.id": "123"
      },
    ]
  },

So that would be something like

{ 
   q(func: has(Foo.bars)) @cascade @normalize {
        id : Foo.id
        Foo.bars @filter(eq(Bar.name, "Alice") AND eq(Bar.name, "Bob")) { uid }
  }
}

That returns:

{
  "data": {
    "q": [
      {
        "id": "1234"
      },
      {
        "id": "123"
      }
    ]
  },

Notice, that Foo with id “1234” should not be queried.

I just updated the query.

Now I get an empty list:

  "data": {
    "q": [ ]
  },

Bar.name can’t be “Alice” and “Bob” at the same time.

Try this

{ 
   q(func: has(Foo.bars)) @filter(uid_in(Foo.bars, uid(A)) AND uid_in(Foo.bars, uid(B))) {
       Foo.id
  }
    A as var(func: eq(Bar.name, "Alice"))
    B as var(func: eq(Bar.name, "Bob"))
}
1 Like

That works when I add @search(by: [hash]) to Bar.name. Thank you!

1 Like