ctwheels
ctwheels

Reputation: 22817

How to only return subset of larger query in GraphQL without returning the whole thing?

I am new to GraphQL and trying to understand how to only return a subsection of the resulting query. For example, here is my cypher query in Neo4j:

MATCH (u:User)-[HAS_FRIEND]-(f:User)
WHERE u.name = "Joe"
RETURN f.name

Notice how the above query only returns the friend names.

GraphQL

Here's a sample of GraphQL version of the above cypher query.

Input

{
    "where": {
        "name": "Joe"
    }
}

Query

query Query($where: NameWhere) {
  names(where: $where) {
    name
    friends {
        name
    }
  }
}

Expected Output

Obviously, I expect output to include friends name array and the name of the user having the friend. But, what if I only want the friends array like the cypher query gives me?

While this is a simple example, I am using a graph database that has a series of connections and my nesting is looking pretty deep, but I only really need a subquery from the result. A great example is with localization - I don't need the country and language (locale), etc. in every query; I only want the subquery result (e.g. the spelling in UK/ENG is colour and in US/ENG is color).

Upvotes: 0

Views: 189

Answers (1)

Thomas Wiss
Thomas Wiss

Reputation: 144

Neo4j offers a Javascript GraphQL library that is able to handle your use case (and many more)!

Please have a look at the documentation for information on how to get started. See even the example queries, where this one is fairly close to what you are looking for.

Anyhow, the GraphQL query provided above, using the @neo4j/graphql library, could look like so:

query Query {
  users (where: { name: "Joe" }) {
     friends {
        name
     }
  }
}

(Note that the where parameter ("Joe") is provided in-line in this case)

Upvotes: 2

Related Questions