Area: API
Sub-Area: Data Access
Applies to: OSS + Cloud
Issue
You need to fetch a large number of entities from DataHub through GraphQL, for example every dataset on one platform. The search query pages with an offset and is built for shallow pagination. The scrollAcrossEntities query pages with a cursor and is built for deep pagination and bulk export. Requests written for scrollAcrossEntities often fail validation because they use fields that the scroll input doesn't have.
You Might Be Asking
- How do I fetch all datasets from DataHub efficiently?
- What's the difference between
searchandscrollAcrossEntities? - Why does my scroll query fail with a validation error when I send
filters? - How do I filter a scroll by platform?
- What page size should I use?
- How do I keep the response small?
Cause
DataHub documents search* queries (search, searchAcrossEntities) for shallow pagination, below about 50 results, and they can't page beyond 10,000 results. Use the scroll* queries, such as scrollAcrossEntities, for deep pagination.
Scroll queries have their own input type, ScrollAcrossEntitiesInput. It differs from the search input:
search (SearchInput) |
scrollAcrossEntities (ScrollAcrossEntitiesInput) |
|
|---|---|---|
| Entity types |
type, required, exactly one |
types, optional list |
| Query string |
query, required |
query, required |
| Paging |
start (offset) and count
|
scrollId and count. There is no start. |
| Filters |
orFilters (filters is deprecated) |
orFilters. There is no filters field. |
Sending filters, even as filters: [], to scrollAcrossEntities fails GraphQL validation. Leaving out query fails too.
Solution
Authenticate
Send an access token in the header Authorization: Bearer <access-token>. A personal access token carries the privileges of the user who made it. The GraphQL endpoint accepts POST requests only. See GraphQL endpoint and authentication.
Page through results
- Send the first request with
queryandcount. LeavescrollIdout. - Read
nextScrollIdfrom the response. It is an opaque ID and can be null. - Send the next request with that value as
scrollId. - Stop when
nextScrollIdis null.
The server returns a non-null nextScrollId only when a page comes back full. A short or empty page returns null. If the last page is exactly full, you get one more request that returns zero results and a null nextScrollId.
Sort by urn so the order stays stable for the whole scroll. Don't sort by _score first. See Deep Pagination: search* vs scroll* APIs.
Declare the input as a variable and pass the whole input object in variables:
query scrollEntities($input: ScrollAcrossEntitiesInput!) {
scrollAcrossEntities(input: $input) {
nextScrollId
searchResults {
entity {
urn
type
... on Dataset {
name
}
}
}
}
}
Variables for the first page:
{
"input": {
"types": ["DATASET"],
"query": "*",
"count": 1000,
"sortInput": {
"sortCriteria": [{ "field": "urn", "sortOrder": "ASCENDING" }]
}
}
}
For the next page, add "scrollId": "<nextScrollId from the previous response>" to input.
entity is the Entity interface. It has only urn, type and relationships. Put every other field, such as name, inside an inline fragment like ... on Dataset { name }. Selecting name directly on entity fails validation.
Validation errors come back with HTTP 200, so check the response body for errors on every request.
Filter a scroll
Use orFilters. Each entry has an and list of criteria. Criteria inside one and list are ANDed, and separate entries are ORed. Each criterion has field, values, and optionally condition and negated. When condition is unset, the match is equality.
The platform field is URN-typed, so use the full data platform URN, not a bare name:
{
"input": {
"types": ["DATASET"],
"query": "*",
"count": 1000,
"orFilters": [
{ "and": [ { "field": "platform", "values": ["urn:li:dataPlatform:snowflake"] } ] }
],
"sortInput": {
"sortCriteria": [{ "field": "urn", "sortOrder": "ASCENDING" }]
}
}
}
Other URN-typed filter fields include container, tags and domains. Not every field is URN-based. For example, origin (the Environment filter) holds a plain value such as PROD. To see the exact filter fields and values the UI sends, open your browser's Network tab, apply the filter in DataHub, and copy the GraphQL request.
See Search guide, GraphQL example for an official orFilters example.
Multiple entity types
types is an optional list of entity types. DATASET, DASHBOARD and CHART are all valid values, so ["DATASET", "DASHBOARD", "CHART"] works. List only the entity types you need. Use an inline fragment per type for type-specific fields.
Page size and response size
- With minimal attributes, a single page can return 1,000 to 2,000 results.
- For very complex requests with many nested objects, lower
countto 20 to 25. - In DataHub Cloud v2.4.4, the maximum result count per query defaults to 10,000. This is a server setting. Self-hosted admins set it on GMS. Cloud customers contact DataHub Support.
- The server rejects a query that is too deep or too complex. The error starts 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 Cloud v2.4.4.
- Depth is how far the selected fields nest. Complexity is a score based on the selected fields. The value of
countchanges neither number. - If you hit one of these errors, select fewer fields, remove deeply nested selections, or split the request into several requests.
Point-in-time snapshots
Point-in-time snapshots for the scroll API are off by default in OSS v1.9.0 and Cloud v2.4.4. By default, a nextScrollId encodes the sort values of the last result, with pitId null and expirationTime 0. Don't assume a fixed session timeout.
Python export script
The script posts the first page, follows nextScrollId, retries failed HTTP calls with backoff, and raises an error if all retries fail. It never returns a partial list as if the export had finished. If the response body contains errors, it raises an error that shows them.
For DataHub Cloud, use https://<your-instance>.acryl.io as the URL.
#!/usr/bin/env python3
"""Export entities from DataHub with scrollAcrossEntities."""
import argparse
import json
import time
import requests
QUERY = """
query scrollEntities($input: ScrollAcrossEntitiesInput!) {
scrollAcrossEntities(input: $input) {
nextScrollId
searchResults {
entity {
urn
type
... on Dataset {
name
}
}
}
}
}
"""
def post_graphql(url, headers, variables, max_retries=3, backoff_factor=2):
"""POST one GraphQL request. Retry HTTP and network failures with backoff."""
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
url,
json={"query": QUERY, "variables": variables},
headers=headers,
timeout=60,
)
response.raise_for_status()
except requests.RequestException as e:
if attempt == max_retries:
raise
wait = backoff_factor ** attempt
print(f"Error: {e}. Retrying in {wait}s...")
time.sleep(wait)
continue
data = response.json()
if "errors" in data:
raise RuntimeError(f"GraphQL errors: {data['errors']}")
return data["data"]["scrollAcrossEntities"]
def export_entities(url, token, entity_type, platform_urn, page_size, output_file):
graphql_url = f"{url}/api/graphql"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
scroll_input = {
"types": [entity_type],
"query": "*",
"count": page_size,
"sortInput": {
"sortCriteria": [{"field": "urn", "sortOrder": "ASCENDING"}]
},
}
if platform_urn:
scroll_input["orFilters"] = [
{"and": [{"field": "platform", "values": [platform_urn]}]}
]
all_entities = []
scroll_id = None
page = 0
while True:
page += 1
if scroll_id:
scroll_input["scrollId"] = scroll_id
result = post_graphql(graphql_url, headers, {"input": scroll_input})
results = result["searchResults"]
all_entities.extend(r["entity"] for r in results)
scroll_id = result["nextScrollId"]
print(f"Page {page}: {len(results)} entities (total {len(all_entities)})")
if not scroll_id or not results:
break
with open(output_file, "w") as f:
json.dump(all_entities, f, indent=2)
print(f"Exported {len(all_entities)} entities to {output_file}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--url", required=True)
parser.add_argument("--token", required=True)
parser.add_argument("--type", default="DATASET")
parser.add_argument("--platform-urn", default=None,
help="For example urn:li:dataPlatform:snowflake")
parser.add_argument("--page-size", type=int, default=1000)
parser.add_argument("--output", default="export.json")
args = parser.parse_args()
export_entities(args.url, args.token, args.type, args.platform_urn,
args.page_size, args.output)
If you use offset paging with search
Keep it to shallow pages. If you do page with start and count, stop when start is greater than or equal to total.
Related Documentation
- GraphQL API overview
- GraphQL endpoint and GraphiQL
- Deep Pagination: search* vs scroll* APIs
- GraphQL query reference
- Search guide, GraphQL example
- DataHub APIs overview
Tags: graphql, pagination, scroll, api, bulk-export, data-access, scrollAcrossEntities, performance, query-optimization, large-datasets