关于 clinicaltrials-database
此技能提供 Python 辅助函数和指南,用于搜索 ClinicalTrials.gov 并获取研究记录。它支持条件筛选、详细研究查询、分页和 CSV 导出,可用于研究分析与试验跟踪。
主要功能
- 01按疾病、干预、地点或申办方搜索
- 02按研究状态筛选
- 03获取详细研究记录
- 04分页检索匹配研究
- 05将结果导出为 CSV
适用场景
- 01查找某种疾病的招募中试验
- 02定位测试特定药物的研究
- 03查看资格标准和联系信息
- 04导出试验数据以供分析
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill clinicaltrials-database安装后在 Claude Code 中输入/clinicaltrials-database确认已加载。
附带文件SKILL.json
详细介绍
ClinicalTrials.gov 数据库
概述
ClinicalTrials.gov 是由美国国家医学图书馆维护的全球临床试验综合注册库。通过 API v2,可以搜索试验、检索详细研究信息、按多种条件筛选,并导出数据用于分析。该 API 是公开的(无需身份验证),速率限制约为每分钟 50 次请求,支持 JSON 和 CSV 格式。
何时使用此技能
在处理临床试验数据的场景中应使用此技能,例如:
- 患者匹配 - 为特定疾病或患者群体寻找正在招募的试验
- 研究分析 - 分析临床试验趋势、结果或研究设计
- 药物/干预研究 - 识别测试特定药物或干预措施的试验
- 地理搜索 - 查找特定地点或区域的试验
- 申办方/机构追踪 - 查找特定机构开展的试验
- 数据导出 - 提取临床试验数据用于进一步分析或报告
- 试验监测 - 追踪特定试验的状态更新或结果
- 资格筛查 - 审查试验的入选/排除标准
快速开始
基本搜索查询
使用辅助脚本搜索临床试验:
cd scientific-databases/clinicaltrials-database/scripts
python3 query_clinicaltrials.py
或直接使用 Python 的 requests 库:
import requests
url = "https://clinicaltrials.gov/api/v2/studies"
params = {
"query.cond": "breast cancer",
"filter.overallStatus": "RECRUITING",
"pageSize": 10
}
response = requests.get(url, params=params)
data = response.json()
print(f"Found {data['totalCount']} trials")
检索特定试验
使用 NCT ID 获取试验的详细信息:
import requests
nct_id = "NCT04852770"
url = f"https://clinicaltrials.gov/api/v2/studies/{nct_id}"
response = requests.get(url)
study = response.json()
# Access specific modules
title = study['protocolSection']['identificationModule']['briefTitle']
status = study['protocolSection']['statusModule']['overallStatus']
核心功能
1. 按疾病/病症搜索
使用 query.cond 参数查找研究特定疾病或病症的试验。
示例:查找正在招募的糖尿病试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="type 2 diabetes",
status="RECRUITING",
page_size=20,
sort="LastUpdatePostDate:desc"
)
print(f"Found {results['totalCount']} recruiting diabetes trials")
for study in results['studies']:
protocol = study['protocolSection']
nct_id = protocol['identificationModule']['nctId']
title = protocol['identificationModule']['briefTitle']
print(f"{nct_id}: {title}")
常见用例:
- 查找罕见病试验
- 识别合并症试验
- 追踪特定诊断的试验可用性
2. 按干预措施/药物搜索
使用 query.intr 参数搜索测试特定干预措施、药物、器械或操作的试验。
示例:查找测试 Pembrolizumab 的 3 期试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
intervention="Pembrolizumab",
status=["RECRUITING", "ACTIVE_NOT_RECRUITING"],
page_size=50
)
# Filter by phase in results
phase3_trials = [
study for study in results['studies']
if 'PHASE3' in study['protocolSection'].get('designModule', {}).get('phases', [])
]
常见用例:
- 药物开发追踪
- 制药公司的竞争情报
- 临床医生的治疗方案研究
3. 地理搜索
使用 query.locn 参数查找特定地点的试验。
示例:查找纽约的癌症试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="cancer",
location="New York",
status="RECRUITING",
page_size=100
)
# Extract location details
for study in results['studies']:
locations_module = study['protocolSection'].get('contactsLocationsModule', {})
locations = locations_module.get('locations', [])
for loc in locations:
if 'New York' in loc.get('city', ''):
print(f"{loc['facility']}: {loc['city']}, {loc.get('state', '')}")
常见用例:
- 将患者转诊至本地试验
- 地理试验分布分析
- 新试验的站点选择
4. 按申办方/机构搜索
使用 query.spons 参数查找特定机构开展的试验。
示例:查找 NCI 申办的试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
sponsor="National Cancer Institute",
page_size=100
)
# Extract sponsor information
for study in results['studies']:
sponsor_module = study['protocolSection']['sponsorCollaboratorsModule']
lead_sponsor = sponsor_module['leadSponsor']['name']
collaborators = sponsor_module.get('collaborators', [])
print(f"Lead: {lead_sponsor}")
if collaborators:
print(f" Collaborators: {', '.join([c['name'] for c in collaborators])}")
常见用例:
- 追踪机构研究组合
- 分析资助机构的优先事项
- 识别合作机会
5. 按研究状态筛选
使用 filter.overallStatus 参数按招募或完成状态筛选试验。
有效状态值:
RECRUITING- 正在招募参与者NOT_YET_RECRUITING- 尚未开放招募ENROLLING_BY_INVITATION- 仅通过邀请招募ACTIVE_NOT_RECRUITING- 活跃但不再招募SUSPENDED- 暂时中止TERMINATED- 提前停止COMPLETED- 研究已结束WITHDRAWN- 在入组前撤回
示例:查找最近完成且有结果的试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="alzheimer disease",
status="COMPLETED",
sort="LastUpdatePostDate:desc",
page_size=50
)
# Filter for trials with results
trials_with_results = [
study for study in results['studies']
if study.get('hasResults', False)
]
print(f"Found {len(trials_with_results)} completed trials with results")
6. 检索详细研究信息
获取特定试验的全面信息,包括资格标准、结局、联系人和地点。
示例:提取资格标准
from scripts.query_clinicaltrials import get_study_details
study = get_study_details("NCT04852770")
eligibility = study['protocolSection']['eligibilityModule']
print(f"Eligible Ages: {eligibility.get('minimumAge')} - {eligibility.get('maximumAge')}")
print(f"Eligible Sex: {eligibility.get('sex')}")
print(f"\nInclusion Criteria:")
print(eligibility.get('eligibilityCriteria'))
示例:提取联系信息
from scripts.query_clinicaltrials import get_study_details
study = get_study_details("NCT04852770")
contacts_module = study['protocolSection']['contactsLocationsModule']
# Overall contacts
if 'centralContacts' in contacts_module:
for contact in contacts_module['centralContacts']:
print(f"Contact: {contact.get('name')}")
print(f"Phone: {contact.get('phone')}")
print(f"Email: {contact.get('email')}")
# Study locations
if 'locations' in contacts_module:
for location in contacts_module['locations']:
print(f"\nFacility: {location.get('facility')}")
print(f"City: {location.get('city')}, {location.get('state')}")
if location.get('status'):
print(f"Status: {location['status']}")
7. 分页和批量数据检索
使用分页高效处理大型结果集。
示例:检索所有匹配的试验
from scripts.query_clinicaltrials import search_with_all_results
# Get all trials (automatically handles pagination)
all_trials = search_with_all_results(
condition="rare disease",
status="RECRUITING"
)
print(f"Retrieved {len(all_trials)} total trials")
示例:可控制的手动分页
from scripts.query_clinicaltrials import search_studies
all_studies = []
page_token = None
max_pages = 10 # Limit to avoid excessive requests
for page in range(max_pages):
results = search_studies(
condition="cancer",
page_size=1000, # Max page size
page_token=page_token
)
all_studies.extend(results['studies'])
# Check for next page
page_token = results.get('pageToken')
if not page_token:
break
print(f"Retrieved {len(all_studies)} studies across {page + 1} pages")
8. 将数据导出为 CSV
将试验数据导出为 CSV 格式,以便在电子表格软件或数据分析工具中进行分析。
示例:导出为 CSV 文件
from scripts.query_clinicaltrials import search_studies
# Request CSV format
results = search_studies(
condition="heart disease",
status="RECRUITING",
format="csv",
page_size=1000
)
# Save to file
with open("heart_disease_trials.csv", "w") as f:
f.write(results)
print("Data exported to heart_disease_trials.csv")
注意: CSV 格式返回的是字符串,而不是 JSON 字典。
9. 提取并总结研究信息
提取关键信息,以便快速概览或生成报告。
示例:创建试验摘要
from scripts.query_clinicaltrials import get_study_details, extract_study_summary
# Get details and extract summary
study = get_study_details("NCT04852770")
summary = extract_study_summary(study)
print(f"NCT ID: {summary['nct_id']}")
print(f"Title: {summary['title']}")
print(f"Status: {summary['status']}")
print(f"Phase: {', '.join(summary['phase'])}")
print(f"Enrollment: {summary['enrollment']}")
print(f"Last Update: {summary['last_update']}")
print(f"\nBrief Summary:\n{summary['brief_summary']}")
10. 组合查询策略
组合多个筛选条件,实现定向搜索。
示例:多条件搜索
from scripts.query_clinicaltrials import search_studies
# Find Phase 2/3 immunotherapy trials for lung cancer in California
results = search_studies(
condition="lung cancer",
intervention="immunotherapy",
location="California",
status=["RECRUITING", "NOT_YET_RECRUITING"],
page_size=100
)
# Further filter by phase
phase2_3_trials = [
study for study in results['studies']
if any(phase in ['PHASE2', 'PHASE3']
for phase in study['protocolSection'].get('designModule', {}).get('phases', []))
]
print(f"Found {len(phase2_3_trials)} Phase 2/3 immunotherapy trials")
资源
scripts/query_clinicaltrials.py
功能全面的 Python 脚本,为常见查询模式提供辅助函数:
search_studies()- 使用各种筛选条件搜索试验get_study_details()- 检索特定试验的完整信息search_with_all_results()- 自动分页获取所有结果extract_study_summary()- 提取关键信息以便快速概览
直接运行该脚本可查看用法示例:
python3 scripts/query_clinicaltrials.py
references/api_reference.md
详细的 API 文档,包括:
- 完整的端点规范
- 所有查询参数及有效值
- 响应数据结构与模块
- 带代码示例的常见用例
- 错误处理与最佳实践
- 数据标准(ISO 8601 日期、CommonMark markdown)
在使用不熟悉的 API 功能或排查问题时,请加载此参考文档。
最佳实践
速率限制管理
该 API 的速率限制约为每分钟 50 次请求。对于批量数据检索:
- 使用最大分页大小(1000)以尽量减少请求次数
- 对速率限制错误(429 状态)实现指数退避
- 在大规模数据收集时,在请求之间添加延迟
import time
import requests
def search_with_rate_limit(params):
try:
response = requests.get("https://clinicaltrials.gov/api/v2/studies", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
print("Rate limited. Waiting 60 seconds...")
time.sleep(60)
return search_with_rate_limit(params) # Retry
raise
数据结构导航
API 响应具有嵌套结构。常见信息的关键路径:
- NCT ID:
study['protocolSection']['identificationModule']['nctId'] - 标题:
study['protocolSection']['identificationModule']['briefTitle'] - 状态:
study['protocolSection']['statusModule']['overallStatus'] - 阶段:
study['protocolSection']['designModule']['phases'] - 入选标准:
study['protocolSection']['eligibilityModule'] - 地点:
study['protocolSection']['contactsLocationsModule']['locations'] - 干预措施:
study['protocolSection']['armsInterventionsModule']['interventions']
错误处理
始终为网络请求实现适当的错误处理:
import requests
try:
response = requests.get(url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e.response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
except ValueError as e:
print(f"JSON decode error: {e}")
处理缺失数据
并非所有试验都具备完整信息。始终检查字段是否存在:
# Safe navigation with .get()
phases = study['protocolSection'].get('designModule', {}).get('phases', [])
enrollment = study['protocolSection'].get('designModule', {}).get('enrollmentInfo', {}).get('count', 'N/A')
# Check before accessing
if 'resultsSection' in study:
# Process results
pass
技术规格
- 基础 URL:
https://clinicaltrials.gov/api/v2 - 身份验证:不需要(公共 API)
- 速率限制:每个 IP 约 50 次请求/分钟
- 响应格式:JSON(默认)、CSV
- 最大分页大小:每次请求 1000 项研究
- 日期格式:ISO 8601
- 文本格式:富文本字段使用 CommonMark Markdown
- API 版本:2.0(2024 年 3 月发布)
- API 规范:OpenAPI 3.0
完整技术细节请参阅 references/api_reference.md。