Area: API
Sub-Area: GraphQL
Applies to: OSS + Cloud
Issue
You want to run complex GraphQL queries, fetch many entities in one request, and page through large result sets with the Python SDK.
You Might Be Asking
- How do I write complex GraphQL queries?
- Can I batch operations?
- How do I handle pagination?
- Why do my Python examples fail with a validation error or a KeyError?
Cause
Common mistakes in GraphQL scripts:
-
DatahubClientConfigrequiresserver, soDataHubGraph(DatahubClientConfig())with no arguments fails validation. -
execute_graphqlreturns the GraphQLdataobject directly. It raisesGraphErrorif the response contains errors. Readingresult['data']['search']fails. Readresult['search']. -
SearchResult.entityis theEntityinterface. It only definesurn,typeandrelationships. Fields such asnamemust go inside an inline fragment like... on Dataset { name }. - Offset paging with
searchis for shallow pagination only. The docs saysearch*APIs are designed for shallow pagination (under about 50) and can't paginate beyond 10k results. - The
DownstreamOfrelationship is declared on the downstream dataset and points to its upstream dataset.relationships(input: {types: ["DownstreamOf"], direction: INCOMING})returns the dataset's downstream datasets, not its upstreams.OUTGOINGreturns its upstreams.
Solution
1. Connect with the Python SDK
get_default_graph() is defined in datahub/ingestion/graph/client.py. If you build the client yourself, pass server and token to DatahubClientConfig. On DataHub Cloud the server URL is https://YOUR_PREFIX.acryl.io/gms. For more setup details, see Getting started with the GraphQL API.
from datahub.ingestion.graph.client import get_default_graph
graph = get_default_graph()
2. Complex queries with fragments
Use a fragment on Dataset and put type-specific fields inside it:
fragment DatasetInfo on Dataset {
urn
name
}
query datasetsByUrn($urns: [String!]!) {
entities(urns: $urns) {
urn
type
...DatasetInfo
}
}
For lineage, DataHub docs recommend the searchAcrossLineage and scrollAcrossLineage root queries. They support indirect lineage (depth greater than 1) through a degree filter. Use direction: UPSTREAM for upstreams. See GraphQL best practices.
3. Batch several entities in one request
Use entities(urns: [String!]!, checkForExistence: Boolean): [Entity]. The results are Entity, so use inline fragments for type-specific fields. The existence check runs only when checkForExistence is exactly true. If you leave it out or set it to false, there is no check. When it is true, it does one extra lookup per URN (n+1 SQL calls) and drops URNs that don't exist from the result. Leave it off unless you need missing URNs filtered out. See GraphQL queries for the entities reference.
def batch_get_datasets(graph, urns: list):
query = """
query batch($urns: [String!]!) {
entities(urns: $urns) {
urn
... on Dataset { name }
}
}
"""
result = graph.execute_graphql(query, variables={"urns": urns})
return {e["urn"]: e for e in result["entities"] if e}
execute_graphql returns the data object, so you read result["entities"].
4. Page through large result sets with scroll
Use scrollAcrossEntities for deep or bulk pagination. See the deep pagination guide and the GraphQL queries reference. Notes:
-
queryis required (String!). Use"*"for all. -
scrollAcrossEntitieshas nofiltersfield and nostartfield. Sending either one fails validation, evenfilters: []. Filter withorFilters: [{ and: [ {field, values, condition, negated} ] }]. - Leave
scrollIdout on the first page. Pass the returnednextScrollIdasscrollIdon the next request. -
nextScrollIdis null when a page comes back short or empty. Loop until it is null. If the last page is exactly full, you get one more request that returns zero results. - Sort by
urn, not by_score, so the scroll order is stable. - Declare every variable you use.
def scroll_all(graph, query: str = "*", page_size: int = 500):
gql = """
query scroll($input: ScrollAcrossEntitiesInput!) {
scrollAcrossEntities(input: $input) {
nextScrollId
searchResults {
entity {
urn
... on Dataset { name }
}
}
}
}
"""
scroll_id = None
while True:
inp = {
"types": ["DATASET"],
"query": query,
"count": page_size,
"sortInput": {
"sortCriteria": [{"field": "urn", "sortOrder": "ASCENDING"}]
},
}
if scroll_id:
inp["scrollId"] = scroll_id
result = graph.execute_graphql(gql, variables={"input": inp})
page = result["scrollAcrossEntities"]
for item in page["searchResults"]:
yield item
scroll_id = page["nextScrollId"]
if not scroll_id:
break
for item in scroll_all(graph, "analytics"):
print(item["entity"]["urn"])
Page size: with minimal attributes, one page can return 1,000 to 2,000 results. For very complex requests with many nested objects, lower count to 20 to 25. List only the entity types you need in types.
If you still page with search (start and count), keep it shallow and stop when start >= total.
5. Limits and errors
- Queries over the limits fail with errors that start with
maximum query depth exceededormaximum query complexity exceeded. The default depth limit is 50. The default complexity limit is 2010 in OSS v1.9.0 and 2100 in DataHub Cloud v2.4.4. Reduce nesting, select fewer fields, or lowercount. - A server-side timeout returns the GraphQL error code
DEADLINE_EXCEEDED, which maps to HTTP 504. Make the query smaller. - OSS: these limits are GMS settings (
GRAPHQL_QUERY_DEPTH_LIMIT,GRAPHQL_QUERY_COMPLEXITY_LIMIT). Cloud: contact DataHub Support if you need a limit changed. - The GraphQL endpoint accepts POST requests only.
Tips
Use fragments to reduce duplication. Select only the fields you need. Batch known URNs with entities. Test queries in GraphiQL first.