How to use distinct in GraphQL query?

Viewed 16340

Here is query where I try to use distinct in graphQl query:

query{
    contacts(take: 10, distinct: true) {
        firstName
        lastName
        title
    }
}

But I am getting error:

{
    "errors": [
        {
            "message": "Unknown argument \"distinct\" on field \"contacts\" of type \"QuerySchema\".",
            "locations": [
                {
                    "line": 2,
                    "column": 21
                }
            ]
        }
    ]
}
3 Answers

GraphQL has no built-in sorting/filtering. It is up to the server to implement features like that, so if you're relying on a third party API and it doesn't support it then you will have to filter the response yourself.

You need to specify the column that GraphQL will use to check wether a value is distinct. In your case you can do something like:

query MyQuery {
  contacts(distinct_on: firstName) {
    firstName
    lastName
    title
  }
}

Here is a example of distinct query.

query {
  contacts {
    distinct(field: title)
  }
}

Result will be.

{
  "data": {
    "contacts": {
      "distinct": [
        "This is my test post",
        "This is my test post1",
        "This is my test post2"
      ]
    }
  }
}

This query binds all titles and deduplicates.

Related