如何使用GitHub GraphQL高效筛选指定时间段的组织提交?
Great question—filtering commits efficiently in GitHub's GraphQL API is totally doable, and it’ll save you from slogging through tons of irrelevant commit history. Let’s break down the best ways to narrow down your results without redundant requests:
1. Use since and until for Precise Date Ranges
The CommitHistoryConnection field supports since and until arguments (ISO 8601 formatted dates) to filter commits by their authored date. This is the most direct way to target your "last month to this month" range, and it filters results before pagination kicks in—so you only get relevant commits right off the bat.
Here’s your updated code with date filtering added:
query GetOrgRepoCommits { repository(owner: "myOrg", name: "myRepo") { ref(qualifiedName: "master") { target { ... on Commit { history( first: 100 since: "2024-08-01T00:00:00Z" # Start of last month until: "2024-09-30T23:59:59Z" # End of current month ) { nodes { oid messageHeadline authoredDate author { name email } } pageInfo { hasNextPage endCursor } } } } } } }
- You can calculate these ISO dates dynamically in your code (e.g., grab the first day of last month and last day of the current month) instead of hardcoding them.
- This eliminates the need to paginate through commits outside your target window entirely.
2. Advanced Filtering with the search Query
If you need more granular filters—like commits from a specific author, with a keyword in the message, or across multiple branches—you can use the top-level search query with type:COMMIT. This works even though you initially thought it might not cover commits:
query SearchTargetCommits { search( query: "repo:myOrg/myRepo author:jdoe created:2024-08-01..2024-09-30 type:COMMIT" type: COMMIT first: 100 ) { edges { node { ... on Commit { oid messageHeadline authoredDate author { name } } } } pageInfo { hasNextPage endCursor } } }
- The
querystring uses GitHub’s standard commit search syntax, so you can mix and match filters (date ranges, authors, keywords, etc.) to get exactly what you need. - This is ideal if you need cross-branch commit data or more specific attribute filtering.
3. Optimize Pagination to Cut Redundant Requests
To avoid unnecessary API calls:
- Always check the
pageInfo.hasNextPageflag before fetching the next page. Only paginate if there are more commits in your filtered range. - Use the maximum allowed
firstvalue (100 for both commit history and search results) to reduce the total number of pagination calls needed.
内容的提问来源于stack exchange,提问作者mcheah

