Sorting with nested key and also filter

I have a question relating to sorting with a nested key, and filtering at the same time. This is a Q&A (question and answer) kind of application like Stack Overflow. Here is the schema.

type Question {
  title: string
  description: string
  owner: User
  answers: [Answer]
  createdTs: datetime
}

type Answer {
  description: string 
  owner: User 
  createdTs: datetime
}

type User {
  firstName: string 
  lastName: string 
}

answers: [uid] @reverse .
owner: uid @reverse .

I want to create a query to fetch “My Answers”, which should return the questions, to which a particular user posted answers, and the questions to be sorted by the order of the created time of the answer. So, that I can see the question to which I posted an answer recently, on the top.

This is a common use case, like the Stack Overflow’s My Answers section. Can someone help me out? I have tried several methods, but nothing gives exactly what I’m looking for.

Note: This is already answered in
(LINK NOT LIVE ANYMORE)

Would it be possible to have the answer copied here? I can’t access that slack workspace.

I don’t remember what I have answered him. But it was like (with several modifications as uid_in accepts variables now)

{
  #Get the answers based on the user traversing via reverse edges
  me(func: eq(firstName, "Michel")) @filter(eq(lastName, "Diz")) {
    #User Level
    <~owner> {
    #Answer Level
    <~answers> { 
    #Question Level
         title
         description
         createdTs
       }
     }
  }
}
{
  #Get the answers based on the user
  ME as var(func: eq(firstName, "Michel")) @filter(eq(lastName, "Diz")) 
    
  #Traversing via reverse edges and returning only my answers
  me(func: uid(ME)) @cascade {
    #User Level
    <~owner> {
    #Answer Level
    <~answers> { 
    #Question Level
         title
         description
         createdTs
         answers @filter(uid_in(owner, uid(ME) )) (orderasc: createdTs) { 
          #Answer Level
          description
          createdTs
        }
       }
     }
  }
}

Note that this query isn’t tested anywhere. I just read the schema and imagined how it would be.

1 Like

One more example - This one isn’t user-based, so it doesn’t need the reverse edges.

{
  #Get the user
  ME as var(func: eq(firstName, "Michel")) @filter(eq(lastName, "Diz")) 

  #Query for questions
  me(func: type(Question)) @cascade {
    #Question Level
         title
         description
         createdTs
         answers @filter(uid_in(owner, uid(ME) )) (orderasc: createdTs) { 
          #Answer Level
          description
          createdTs
        }
       }
     }
  }
}

BTW, using the reserve index can potentially reduce the time of the queries. But they are bigger queries.