Skip to Content
go-dicom(3)

Query/retrieve and worklist

How the Query/Retrieve service works and what go-dicom gives for each side of it: the matching rules in package matching, the on-disk archive in package dcmstore, the qrscp command, and Modality Worklist with wlmscp and findscu -worklist. For the client calls themselves see Writing an SCU.

Overview

A requestor asks with an identifier: a data set naming a level, the keys to match, and the attributes to return. The SCP answers C-FIND with one pending response per match, and C-MOVE or C-GET by sending the matching instances as C-STORE sub-operations.

Information modelLevelsSOP classes (FIND, MOVE, GET)
Patient RootPATIENT, STUDY, SERIES, IMAGE1.2.840.10008.5.1.4.1.2.1.{1,2,3}
Study RootSTUDY, SERIES, IMAGE1.2.840.10008.5.1.4.1.2.2.{1,2,3} (network.StudyRootQueryRetrieveFind, ...Move, ...Get)
Patient/Study Only (retired)PATIENT, STUDY1.2.840.10008.5.1.4.1.2.3.{1,2,3}
Modality Worklistnone1.2.840.10008.5.1.4.31 (FIND only)

Identifiers and keys

  • Query/Retrieve Level (0008,0052) says what is searched for: PATIENT, STUDY, SERIES or IMAGE.
  • Unique keys identify each level: Patient ID, Study Instance UID, Series Instance UID, SOP Instance UID.
  • A C-FIND identifier has the unique key of each level above the query level, each a single value, and no other key of those levels. The unique key of the query level may be absent, a value, empty or a list.
  • A C-MOVE or C-GET identifier has the unique key of the retrieval level and every level above it, and no other keys. The key of the retrieval level may be a list of UIDs.

matching.CheckHierarchy applies these rules (PS3.4 C.4.1.2.1 and C.2.2.1.1) for a model (matching.PatientRoot, matching.StudyRoot) and an operation (matching.OperationFind, matching.OperationRetrieve). It returns a *HierarchyError, which a handler returns as its error to have A900 sent with the reason as the Error Comment.

Matching rules

Package matching decides whether an identifier matches a data set, by the rules of PS3.4 C.2.2.2. dcmstore, qrscp, wlmscp and the DICOMweb server all use it, so a query answers the same way over each.

RuleQuery valueMatches
Universalemptyevery candidate, and the attribute is returned
Single valueSMITH^JOHN, CTequal values; padding ignored; a person name in any case
List of UID1.2.3\1.2.4any UID in the list
WildcardSmith*, ?MR* and ? in AE, CS, LO, LT, PN, SH, ST, UC, UT; literal elsewhere
Range20240101-20241231, 2024-, -1200DA, TM and DT, both ends inclusive, either optional
Sequenceone item of keysa candidate with one item that meets every key of it
Empty value"" (two quotation marks)a candidate where the attribute is empty or absent
Multiple valuesCT\MRa candidate matching any one value

Where the standard leaves the choice to the SCP: person names match in any case (smith* finds SMITH^JOHN), accents are kept (Jerome does not match Jérôme), there is no fuzzy matching, a date written 1997.04.24 is read as 19970424, and a candidate without the attribute matches only universal, * and "". The query and the candidate are each read in their own Specific Character Set. CONFORMANCE.md §2.7 has the full table.

matching.Options adjusts a query: Skip names keys this caller does not support (they are neither matched nor returned), Literal keys that take single value matching only, CombinedDateTime and CombineDateTime date and time pairs matched as one period.

An archive: dcmstore

dcmstore is a directory of files and an index. Instances are filed under a directory per study and series, named by their UIDs, which are validated before they become paths. index.json holds the attributes a query matches on and index.log what changed since; a missing or unreadable index is rebuilt from the files. dcmstore.Handler answers C-ECHO, C-STORE, C-FIND at every level, C-MOVE, C-GET and storage commitment from it.

store, err := dcmstore.Open(dir)
if err != nil {
	return err
}
handler := dcmstore.NewHandler(store)
handler.OnStored = func(ctx context.Context, inst *dcmstore.Instance) error {
	log.Printf("stored %s at %s", inst.SOPInstanceUID, inst.Path)
	return nil // an error here is logged; the C-STORE has already succeeded
}
server, err := network.StartServer(ctx, network.SCPConfig{
	AETitle:          "ARCHIVE",
	BindAddress:      "127.0.0.1",
	AbstractSyntaxes: dcmstore.SupportedSOPClasses(),
	TransferSyntaxes: dcmstore.SupportedTransferSyntaxes(),
	MoveDestinations: map[string]string{"STORESCP": "127.0.0.1:41002"},
	AnswerSOPClassExtended: network.AnswerQueryRetrieveNegotiation(
		dcmstore.QueryNegotiation(), network.RetrieveExtendedNegotiation{}),
}, handler)
if err != nil {
	return err
}
defer server.Stop()
  • MoveDestinations maps each C-MOVE destination AE title to host:port; ResolveMoveDestination looks one up instead, and ResolveOutbound decides the whole outbound association (titles, address, TLS, timeouts). An unknown title is answered A801. The destination must answer to that title: the SCP calls it by it.
  • AnswerQueryRetrieveNegotiation agrees to the extended negotiation behaviors the store supports: empty value and multiple value matching.
  • store.Query answers an identifier directly, without the network:
answers, err := store.Query(ctx, query) // QueryRetrieveLevel STUDY, PatientName "compressed*", StudyDate "2004-"
if err != nil {
	return err
}
for _, a := range answers {
	fmt.Println(a.GetStringByKeyword("PatientName"), a.GetStringByKeyword("StudyDate"))
}

which printed CompressedSamples^CT1 20040119 and CompressedSamples^MR1 20040826.

What the store keeps and how:

  • Only the attributes PS3.4 defines as keys are indexed, with those a DICOMweb search returns. A key it does not hold is returned empty, not matched on.
  • Two sequences are indexed for sequence matching: Scheduled Procedure Step Sequence and Request Attributes Sequence.
  • Uncompressed instances are written as Explicit VR Little Endian; compressed ones in the syntax they arrived in, never decoded.
  • A retrieval reads one instance off disk at a time and stops on C-CANCEL, through the streaming handler interfaces.
  • It is not a database. Counts are computed by scanning the index; an archive of millions of instances wants real indexes behind the same handler interfaces.

The qrscp command

qrscp is that archive as a command: it stores what it is sent, answers C-FIND, C-MOVE and C-GET from it, answers storage commitment, and with -web serves the same store over DICOMweb (DICOMweb server).

$ go-dicom qrscp -port 41003 -output archive -move-dest STORESCP=127.0.0.1:41002 -web 41080
Starting DICOM Query/Retrieve SCP
  AE Title:  QRSCP
  Port:      41003
  Storage:   archive
  Indexed:   0 instance(s) already present
  Services:  Verification, Storage, Query/Retrieve
  SOP Classes: 203
  DICOMweb:  http://127.0.0.1:41080/dicom-web
Listening for associations... (Ctrl+C to stop)
$ go-dicom storescu -aec QRSCP 127.0.0.1:41003 study/ct.dcm study/mr.dcm
...
Results: 2 sent, 0 failed
$ go-dicom findscu -aec QRSCP -level PATIENT -patient-name "compressedsamples*" 127.0.0.1:41003
...
Found 2 result(s)
$ go-dicom movescu -aec QRSCP -dest STORESCP -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 127.0.0.1:41003
Moving from 127.0.0.1:41003 to STORESCP (level: STUDY)
C-MOVE completed successfully

dcmtk's tools work against it as against any archive:

$ findscu -S -aec QRSCP -k QueryRetrieveLevel=STUDY -k "PatientName=Compressed*" -k StudyInstanceUID 127.0.0.1 41003
I: Find Response: 1 (Pending)
...
I: (0010,0010) PN [CompressedSamples^CT1 ]                 #  22, 1 PatientName
...
$ movescu -S -aec QRSCP -aem STORESCP -k QueryRetrieveLevel=STUDY -k StudyInstanceUID=1.3.6.1.4.1.5962.1.2.4.20040826185059.5457 127.0.0.1 41003
FlagMeaning
-port, -aetListen port (11112) and AE title (QRSCP)
-outputThe store's directory (./received)
-move-destC‑MOVE destinations, AETITLE=host:port, comma separated
-allow, -allow-fileWho may associate
-max-opsOperations of one association performed at once
-web, -web-tokenDICOMweb on a port (this machine only) or host:port (needs a token)
-tls, -tls-cert, -tls-key, -tls-ca, -tls-outboundTLS in, and for the associations it opens
-eventsThe -events log

Retrieving from stored bytes

QueryRetrieveHandler and dcmstore.Handler hand the SCP decoded data sets, which it encodes again for each sub-operation. A handler that implements CMoveStoredSender or CGetStoredSender sends the stored bytes instead, byte for byte:

  • PlanCMove / PlanCGet return a RetrievePlan: how many instances, and every pair of SOP class and transfer syntax among them, from which the C-MOVE proposes its contexts (StoreStreamContexts).
  • SendCMove / SendCGet emit a RetrieveItem per instance: its UIDs and syntax, an Open function for the data set's bytes, and a Done callback told how its sub-operation ended.
  • Without RetrievePlan.Transcode an instance goes out only on a context of its own syntax, or fails with ErrRetrieveNoContext. With it, it is re-encoded into a syntax the peer accepted, read whole into memory first.

The SCP uses these in place of the streaming and slice interfaces when a handler implements them. dcmstore.Handler does not.

Modality Worklist

A modality asks a worklist SCP which procedures are scheduled for it. The query has no Query/Retrieve Level; its keys are the patient, the order, and the Scheduled Procedure Step Sequence, matched as a sequence (PS3.4 K.6.1.2).

wlmscp serves a directory of worklist files, one entry per file, read again at every query:

$ go-dicom wlmscp -dir wlist -port 41006
Starting DICOM Modality Worklist SCP
  AE Title:  WLMSCP
  Port:      41006
  Worklist:  wlist (10 entries)
Listening for worklist queries... (Ctrl+C to stop)
$ go-dicom findscu -aec WLMSCP -worklist -patient-name "vivaldi*" -date 19951015 127.0.0.1:41006
Querying 127.0.0.1:41006 (Modality Worklist)

--- Result 1 ---
  Accession Number                         00000
  Referring Physician's Name
  Patient's Name                           VIVALDI^ANTONIO
  Patient ID                               AV35674
  ...
  Scheduled Procedure Step Sequence
    Item 1
      Modality                                 MR
      Scheduled Station AE Title               AA32\AA33
      Scheduled Procedure Step Start Date      19951015
      Scheduled Procedure Step Start Time      085607
      ...
  Requested Procedure ID                   RP454G234

Found 1 result(s)

The files here are dcmtk's sample worklist (wlistdb/OFFIS, converted with dump2dcm). findscu -worklist takes -modality, -date (a date, a range or today), -station-aet, -patient-name and -patient-id.

In Go, WorklistHandler gives the query to a function and sends what it returns; it does no matching of its own. Package matching does it, with the options a worklist needs:

opts := matching.Options{
	// Basic Worklist has no Query/Retrieve Level: do not match or return it.
	Skip: func(parent tag.Tag, elem *dataelem.DataElement) bool {
		t, _ := elem.Tag()
		return parent == 0 && t == tag.New(0x0008, 0x0052)
	},
	CombineDateTime: matching.WorklistDateTime, // start date and time are one period
}
wl, err := network.StartServer(ctx, network.SCPConfig{
	AETitle:          "RIS",
	BindAddress:      "127.0.0.1",
	AbstractSyntaxes: []string{network.VerificationSOPClassUID, network.ModalityWorklistInformationModelFindUID},
}, &network.WorklistHandler{
	OnWorklist: func(ctx context.Context, query *dataset.Dataset) ([]*dataset.Dataset, error) {
		id, err := matching.Compile(query, opts)
		if err != nil {
			return nil, err
		}
		var answers []*dataset.Dataset
		for _, e := range worklist {
			if !id.MatchDataset(e) {
				continue
			}
			answer, err := matching.Response(query, e, opts) // the keys asked for, with e's values
			if err != nil {
				return nil, err
			}
			answers = append(answers, answer)
		}
		return answers, nil
	},
})

A worklist SCU proposes network.BasicWorklistPresentationContexts() and queries with FindWithSOPClass(ctx, network.ModalityWorklistInformationModelFindUID, query).

Limits and gotchas

  • Relational queries and fuzzy name matching are not offered by the archive; extended negotiation for them is refused.
  • A retrieval returns instances at any level: a C-GET at STUDY level sends every instance of the matching studies.
  • qrscp accepts Modality Worklist contexts but does not serve a worklist: findscu -worklist against it is answered A900. Use wlmscp.
  • A worklist key differs from wlmscpfs in one way: wlmscp matches vivaldi* to VIVALDI^ANTONIO; dcmtk's wlmscpfs does not.
  • CONFORMANCE.md §2.5.1 gives the final statuses and counts of a retrieve.

See also

On this page