103.2. Advanced TAP queries#
103.2. Advanced queries¶
For the Rubin Science Platform at data.lsst.cloud.
Data Release: Prompt Products
Container Size: Large
LSST Science Pipelines version: r30.0.11
Last verified to run: 2026-11-27
Repository: github.com/lsst/tutorial-notebooks
DOI: 10.11578/rubin/dc.20250909.20
Learning objective: How to do advanced TAP queries for the Prompt Products Database (PPDB).
LSST data products: Prompt DiaObject, DiaSource, DiaForcedSource table
Packages: lsst.rsp.RSPDiscovery
Credit: Originally developed by the Rubin Community Science team. Please consider acknowledging them if this notebook is used for the preparation of journal articles, software releases, or other notebooks.
Get Support: Everyone is encouraged to ask questions or raise issues in the Support Category of the Rubin Community Forum. Rubin staff will respond to all questions posted there.
1. Introduction¶
This tutorial builds on the basics of querying the Prompt Products Database (PPDB) and shows more advanced ADQL queries for realistic science cases. Because the PPDB is served by Google BigQuery rather than Qserv, efficiency matters even more for advanced queries. Each example follows the practices introduced in the first tutorial (103.1): use asynchronous queries, request only the columns you need, use spatial and time constraints, filter each table in a join, and batch your lookups into as few queries as possible.
Related tutorials: Tutorial 103.1 demonstrates the basics of using the TAP service for the PPDB and writing simple ADQL queries.
1.1. Import packages¶
Import general python packages numpy, matplotlib, and astropy.time. Import the RSPDiscovery class from the Rubin lsst package to access the RSP TAP service and plotting functions from lsst.utils to apply Rubin's standard filter colors and symbols.
import numpy as np
import matplotlib.pyplot as plt
from astropy.time import Time
from lsst.rsp import RSPDiscovery
from lsst.utils.plotting import (get_multiband_plot_colors,
get_multiband_plot_symbols,
set_rubin_plotstyle)
1.2. Define parameters¶
Instantiate RSPDiscovery with the PPDB release, create an instance of the TAP service, and assert that it exists.
discovery = RSPDiscovery("prompt")
service = discovery.get_tap_client()
Define filter names, plot markers, and colors for plotting
set_rubin_plotstyle()
filter_colors = get_multiband_plot_colors()
filter_symbols = get_multiband_plot_symbols()
2. Advanced PPDB queries¶
This section shows advanced PPDB querie examples that go beyond single-table searches: joining tables, retrieving data for many objects at once, and summarizing results on the server.
2.1. Join tables to retrieve light curves for every object in a cone¶
Join the DiaObject table to the DiaSource table on their shared column, diaObjectId. The cone search on DiaObject selects objects within 0.05° of (RA, Dec) = (150.11°, 2.23°), and the join returns every detection of those objects from DiaSource. Add a second, slightly larger cone (0.0506°, about 2″ wider) on DiaSource itself. Each PPDB table is organized by sky position separately, so the cone on DiaObject alone does not let the server skip any DiaSource data. The extra margin keeps detections that scatter slightly beyond an object's average position. The constraint nDiaSources >= 30 keeps only objects with at least 30 detections across all bands.
query = """
SELECT o.diaObjectId, s.midpointMjdTai, s.band,
s.psfFlux, s.psfFluxErr
FROM ppdb.DiaObject AS o
JOIN ppdb.DiaSource AS s
ON s.diaObjectId = o.diaObjectId
WHERE CONTAINS(POINT('ICRS', o.ra, o.dec),
CIRCLE('ICRS', 150.11, 2.23, 0.05)) = 1
AND CONTAINS(POINT('ICRS', s.ra, s.dec),
CIRCLE('ICRS', 150.11, 2.23, 0.0506)) = 1
AND o.nDiaSources >= 30
"""
job = service.submit_job(query)
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
results = job.fetch_result().to_table()
print('Number of diaObjects: ', len(results))
Number of diaObjects: 1909
The result has one row per detection. Print the first ten rows of the table to check the results.
results[0:10]
| diaObjectId | midpointMjdTai | band | psfFlux | psfFluxErr |
|---|---|---|---|---|
| d | nJy | nJy | ||
| int64 | float64 | str1 | float32 | float32 |
| 313928194980839467 | 61060.29476511259 | r | 724.7105 | 129.95969 |
| 313998569362686112 | 61057.30405358569 | g | 745.18634 | 151.3734 |
| 313875416814714998 | 61057.30405358569 | g | -837.85394 | 118.58626 |
| 313998569362686112 | 61057.30245449782 | g | -719.4391 | 140.68753 |
| 313875416814714998 | 61032.32800285226 | g | -740.4309 | 135.83194 |
| 313888627057754272 | 61032.32800285226 | g | -672.3057 | 126.05662 |
| 313928194980839467 | 61058.30066636704 | r | 953.3464 | 116.200966 |
| 313998569362686112 | 61059.29627806878 | g | 971.0592 | 176.63158 |
| 313928194980839467 | 61053.25234978343 | i | 1961.6061 | 307.61197 |
| 313928194980839467 | 61051.19350022562 | i | 1508.3069 | 259.60123 |
job.delete()
del query, results
2.2. Retrieve light curves of multiple objects with one batch query¶
Retrieve $g$- and $r$-band light curves for a list of objects, such as candidates from a broker or a published catalog, in a single query
Build a list of diaObjectId values, and pass it to the query with WHERE diaObjectId IN (...). The example list below has two Rubin transients: AT2026ekf (diaObjectId = 170032917163016282) and AT2026eqf (diaObjectId = 313994139532263447), and one RR Lyrae (diaObjectId = 313985345023639575). The query returns the detections of all objects at once.
target_ids = [170032917163016282,
313994139532263447,
313985345023639575]
id_list = ", ".join(str(i) for i in target_ids)
query = f"""
SELECT diaObjectId, midpointMjdTai, band, psfFlux, psfFluxErr
FROM ppdb.DiaSource
WHERE diaObjectId IN ({id_list})
AND band IN ('g', 'r')
"""
job = service.submit_job(query)
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
lcs = job.fetch_result().to_table()
Split the results into individual light curves for each object with group_by.
groups = lcs.group_by('diaObjectId').groups
Plot the difference-image PSF fluxes and their uncertainties as a function of MJD for each object.
fig, axes = plt.subplots(len(groups), 1, figsize=(6, 3 * len(groups)))
axes = axes.ravel()
for ax, grp in zip(axes, groups):
for band in ['g', 'r']:
sel = grp['band'] == band
if not np.any(sel):
continue
ax.errorbar(grp['midpointMjdTai'][sel], grp['psfFlux'][sel],
yerr=grp['psfFluxErr'][sel],
fmt=filter_symbols[band], ms=6, mew=1.5,
mec=filter_colors[band], ecolor=filter_colors[band],
color='none', alpha=0.7, label=band)
ax.axhline(0, color='gray', lw=0.8, ls='--')
ax.set_title(f"diaObjectId = {grp['diaObjectId'][0]}", fontsize=10)
ax.set_ylabel('PSF flux (nJy)')
ax.legend(fontsize=8, loc='best')
axes[-1].set_xlabel('MJD (TAI)')
plt.tight_layout()
plt.show()
Figure 1: $g$- and $r$-band light curves of three objects retrieved in a single batch query from the PPDB
DiaSourcetable. (Top) Light curve of the transient AT2026ekf (diaObjectId= 170032917163016282). (Middle) Light curve of an RR Lyrae star (diaObjectId= 313985345023639575). (Bottom) Light curve of the transient AT2026eqf (diaObjectId= 313994139532263447). Each panel shows the difference-image PSF flux with 1σ uncertainties against observation time. The dashed line marks zero flux, the brightness level in the template image.
job.delete()
del query, lcs, groups
2.3. Aggregate detections on the server with GROUP BY¶
Server-side aggregation is useful when you need a summary of many detections rather than the detections themselves. For example, use it to find recently active or multi-band objects for follow-up, to screen for transients with short detection spans and high peak fluxes, or to check how well a field is sampled. Only one row per object is returned, so downloads stay small, even for large areas or long time windows. Use the summary to choose the objects of interest, then retrieve their full light curves with a batch query (Section 2.2).
To find recently active objects within 0.5° of (RA, Dec) = (150.11°, 2.23°) since MJD 61351 that were detected at least four times in two or more bands, and summarize each one without downloading every detection. Query the DiaSource table for detections within 0.5° of (RA, Dec) = (150.11°, 2.23°) since MJD 61351. Group the detections by diaObjectId, and use aggregate functions to compute a summary for each object: the number of detections (COUNT(*)), the number of distinct bands (COUNT(DISTINCT s.band)), the first and last detection times (MIN and MAX of midpointMjdTai) and the peak flux (MAX(s.psfFlux)). The HAVING clause filters the grouped results, keeping only objects with at least four detections in at least two bands.
query = """
SELECT s.diaObjectId,
COUNT(*) AS nDet,
COUNT(DISTINCT s.band) AS nBands,
MIN(s.midpointMjdTai) AS tFirst,
MAX(s.midpointMjdTai) AS tLast,
MAX(s.psfFlux) AS peakFlux
FROM ppdb.DiaSource AS s
WHERE CONTAINS(POINT('ICRS', s.ra, s.dec),
CIRCLE('ICRS', 150.11, 2.23, 0.5)) = 1
AND s.midpointMjdTai > 61351
GROUP BY s.diaObjectId
HAVING COUNT(*) >= 4 AND COUNT(DISTINCT s.band) >= 2
"""
job = service.submit_job(query)
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
results = job.fetch_result().to_table()
Display the results table.
results
| diaObjectId | nDet | nBands | tFirst | tLast | peakFlux |
|---|---|---|---|---|---|
| int64 | int64 | int64 | float64 | float64 | float32 |
| 313853517445464071 | 16 | 3 | 61355.329556867095 | 61357.33454214936 | 14755.53 |
| 313972183909531813 | 15 | 3 | 61355.33011627959 | 61357.3350751538 | -5661.726 |
| 313972182584131784 | 6 | 2 | 61355.335704449986 | 61357.3322241823 | -1568.5178 |
| 313875416814715013 | 14 | 3 | 61355.33011627959 | 61357.3350751538 | 7676.6733 |
| 313853533150511259 | 11 | 3 | 61355.335704449986 | 61357.3350751538 | 3416.3506 |
| 170028510653448349 | 4 | 2 | 61355.335704449986 | 61357.3322241823 | -1368.0797 |
| 170028500605468803 | 17 | 3 | 61355.329556867095 | 61357.3350751538 | -4418.544 |
| 170050499135406261 | 16 | 3 | 61355.329556867095 | 61357.3350751538 | 4773.1875 |
| 313888627035734156 | 4 | 3 | 61357.32725147149 | 61357.33454214936 | -2559.4993 |
| ... | ... | ... | ... | ... | ... |
| 170028512775241784 | 10 | 3 | 61355.33011627959 | 61357.33454214936 | 3996.5757 |
| 313871014339543090 | 7 | 3 | 61355.33011627959 | 61357.3350751538 | 3426.509 |
| 170028521921445983 | 11 | 3 | 61355.33011627959 | 61357.3350751538 | 6100.5005 |
| 313985345562083345 | 6 | 3 | 61357.326055370635 | 61357.33454214936 | 4350.964 |
| 313888627194593429 | 8 | 2 | 61355.335704449986 | 61357.3322241823 | -2204.156 |
| 313998569902178423 | 8 | 2 | 61355.335704449986 | 61357.3322241823 | -2054.5825 |
| 313875416819957922 | 6 | 2 | 61355.335704449986 | 61357.3322241823 | 3712.57 |
| 170028514250588334 | 4 | 3 | 61357.326055370635 | 61357.33454214936 | 4656.424 |
| 313967766931505175 | 17 | 2 | 61355.329556867095 | 61357.3322241823 | 13714.134 |
| 170028510647156885 | 14 | 2 | 61355.329556867095 | 61357.33172527598 | 12731.6 |
job.delete()
del query, results