Scripted access
Gaia@AIP provides scripted access through the Table Access Protocol (TAP), DataLink, the Simple Join Service for Gaia DR2 and DR3, and the Data Delivery Service for Gaia DR4. This guide focuses on TAP, the main interface for querying the archive. TAP queries also supply the source and image identifiers used to retrieve products through the other services.
Requirements
Install PyVO 1.7 or later. Check the PyVO package requirements for supported Python versions.
python -m pip install "pyvo>=1.7" requests
To check your installed PyVO version, run python -m pip show pyvo.
API token
After signing in to Gaia@AIP, click your user name in the top-right menu and select API Token. Copy the token and replace <your-token> in the example below.
The token gives your script access to your query jobs and their results.
Quick start
This example submits an asynchronous TAP job, waits for it to complete, and prints the result.
import requests
import pyvo
URL_TAP = "https://gaia.aip.de/tap"
TOKEN = 'Token <your-token>'
tap_session = requests.Session()
tap_session.headers['Authorization'] = TOKEN
tap_service = pyvo.dal.TAPService(URL_TAP, session=tap_session)
query = "SELECT TOP 10 * FROM gaiadr4.gaia_source"
tap_results = tap_service.run_async(query)
tap_results.to_table().pprint()
Asynchronous jobs
Basic use
In the quick start, run_async() creates and starts a job on the archive server. PyVO waits for the job to finish, checks for errors, and fetches the result before the script continues. By default, it then archives the job on Gaia@AIP. PyVO TAPService documentation
Submit a job
Use submit_job() to work with the job directly. You can check its status, save its URL to retrieve the result later, or keep the result table for a subsequent query.
queuesets the job's runtime limit on the server. Choose"30s"(the default),"5m", or"2h"based on how long you expect the query to run. A 24-hour queue is available on request.languagedefaults to"ADQL". Uselanguage="PostgreSQL"to write PostgreSQL queries with pgSphere functions. ADQL and PostgreSQLrunidis an optional label you can use to find the job later.
This example uses the tap_service connection from the quick start. submit_job() creates the job and returns a job object. job.run() starts it.
query = "SELECT TOP 10 * FROM gaiadr4.gaia_source"
job = tap_service.submit_job(query, queue="30s", runid="gaia_source_sample")
job.run()
print(f"Job URL: {job.url}")
job.wait()
job.raise_if_error()
tap_results = job.fetch_result()
tap_results.to_table().pprint()
job.delete()
After fetching the result, call job.delete() as shown above. Gaia@AIP archives the job and removes its result table from the server, freeing space in your storage quota. The archive keeps the original query so you can rerun it later.
Keep the result table when you need it again, for example to join it with another table in a later query. Keeping the table can save you from rerunning a job that took an hour. With submit_job(), leave the job in place by omitting job.delete(). With run_async(), pass delete=False.
When you sign in with the same account, your scripted jobs appear in the Job list in the Query interface. Archiving a job removes it from that list.
Cone search example
This example searches for sources within 0.5 degrees of the centre of the M4 globular cluster at (245.8962°, −26.5222°). You can also use the archive's Cone Search API. Cone search guide
centre_ra = 245.8962
centre_dec = -26.5222
radius = 0.5
query = f"""
SELECT ra, dec,
DISTANCE(ra, dec, {centre_ra}, {centre_dec}) AS dist
FROM gaiadr4.gaia_source
WHERE DISTANCE(ra, dec, {centre_ra}, {centre_dec}) <= {radius}
"""
tap_results = tap_service.run_async(query, queue="2h")
tap_results.to_table().pprint(max_lines=10)
Advanced use
Retrieve results later
Once you start a job, it can continue to run on the server after your script exits. Save its URL so you can check its status and fetch its result in a later session. The same steps work with any queue.
This example selects nearby stars for a colour–magnitude diagram. The query can exceed the default 30-second limit, so the example uses the 2h queue.
query = """
SELECT TOP 10000 source_id, parallax, bp_rp,
phot_g_mean_mag + 5 * LOG10(parallax) - 10 AS absolute_g_mag
FROM gaiadr4.gaia_source
WHERE parallax >= 10
AND parallax_over_error >= 10
AND unreliable_astrometry = 'false'
AND bp_rp IS NOT NULL
AND phot_g_mean_mag IS NOT NULL
ORDER BY random_index
"""
job = tap_service.submit_job(query, queue="2h", runid="colour_magnitude_sample")
job.run()
with open("job_url.txt", "w", encoding="utf-8") as file:
file.write(job.url)
In the later session, set up tap_session with the same API token as in the quick start. Read the URL and check the job's phase. If the job is still running, run this snippet again later.
with open("job_url.txt", encoding="utf-8") as file:
job_url = file.read().strip()
job = pyvo.dal.AsyncTAPJob(job_url, session=tap_session)
phase = job.phase
print(f"Job phase: {phase}")
if phase in ("COMPLETED", "ERROR", "ABORTED"):
job.raise_if_error()
tap_results = job.fetch_result()
tap_results.to_table().pprint(max_lines=10)
job.delete()
Split a large query into smaller jobs
If a query exceeds the time limit, you can divide the selection into subsets and submit a shorter query for each one.
- Partition by ranges of
random_index. - Partition by sky position using right ascension and declination.
- Partition by HEALPix cell.
Archive and rerun jobs
Archive completed jobs
Use this example after you have retrieved the results and finished working with the server tables. It archives every completed job returned by get_job_list(). Filter the list first if you need to keep some of the result tables.
completed_jobs = tap_service.get_job_list(phases=["COMPLETED"])
for job_description in completed_jobs:
job_url = f"{tap_service.baseurl}/async/{job_description.jobid}"
job = pyvo.dal.AsyncTAPJob(job_url, session=tap_session)
print(f"Archiving: {job.url}")
job.delete()
Rerun archived jobs
Gaia@AIP keeps the query and job parameters after archiving. This example reruns the two most recently started archived jobs using their original query language and queue. Save the new job URLs to retrieve the results later.
archived_jobs = tap_service.get_job_list(phases=["ARCHIVED"], last=2)
for job_description in archived_jobs:
job_url = f"{tap_service.baseurl}/async/{job_description.jobid}"
archived_job = pyvo.dal.AsyncTAPJob(job_url, session=tap_session)
parameters = {
parameter.id_: parameter.content for parameter in archived_job.job.parameters
}
job = tap_service.submit_job(
archived_job.query,
language=parameters["query_language"],
queue=parameters["queue"],
runid="rerun",
)
job.run()
print(f"New job URL: {job.url}")
To rerun jobs with a particular label, use this list in the loop above.
target_runid = "colour_magnitude_sample"
archived_jobs = [
job_description
for job_description in tap_service.get_job_list(phases=["ARCHIVED"])
if job_description.runid == target_runid
]
Working with query results
Use to_table() to convert a TAPResults object to an Astropy table. From there you can display the result or convert it to another format.
Print the data. Use max_lines to limit the number of lines displayed.
tap_results.to_table().pprint(max_lines=10)
Save the first ten rows as an HTML table to open in a browser.
tap_results.to_table()[:10].write("tap-results.html", format="ascii.html")
Display the first ten rows in an IPython or Jupyter notebook.
from IPython.display import display
display(tap_results.to_table()[:10])
Convert the result to a NumPy array.
np_array = tap_results.to_table().as_array()
Convert the result to a pandas DataFrame and display the first rows.
df = tap_results.to_table().to_pandas()
df.head()
Synchronous TAP for short queries
For a query that completes in a few seconds, you can use run_sync() to retrieve the result in one call. The HTTP request stays open while the query runs, so it can quickly hit a server or connection timeout. Use asynchronous jobs when you need more time or want to retrieve the results later.
This query retrieves the astrometric observations of asteroid (8) Flora in time order and returns fewer than 400 rows.
query = """
SELECT s.source_id, s.number_mp, s.denomination, o.transit_id,
o.epoch, o.ra, o.dec, o.al_orbit_residual
FROM gaiadr4.sso_source AS s
JOIN gaiadr4.sso_observation AS o ON s.source_id = o.source_id
WHERE s.number_mp = 8
AND s."type" = 3
ORDER BY o.epoch
"""
tap_result = tap_service.run_sync(query)
PyVO returns a TAPResults object for both synchronous and asynchronous queries.