beda-software / fhirpath-py

FHIRPath implementation in Python.
MIT License
62 stars 12 forks source link

Support for resolve() #42

Open vadi2 opened 1 week ago

vadi2 commented 1 week ago

It would be nice if resolve() was supported for references that are within the Bundle you are operating on.

vadi2 commented 1 week ago

I haven't got the bandwidth to add resolve natively, but in case anyone is looking for a naive implementation to use externally, this works well:

def evaluate_with_resolve(bundle, fhirpath):
    if '.resolve()' not in fhirpath:
        return evaluate(bundle, fhirpath)

    path_segments = fhirpath.split('.resolve()')
    current_result = evaluate(bundle, path_segments[0])

    for segment in path_segments[1:]:
        if not current_result:
            return None
        reference_id = current_result[0]
        if not reference_id:
            return None
        # Find referenced resource in bundle
        referenced_resource = next(
          (entry['resource'] for entry in bundle['entry'] 
          if entry.get('fullUrl') == reference_id),
          None)

        if not referenced_resource:
            return None
        current_result = evaluate(referenced_resource, segment.lstrip('.'))
    return current_result
ruscoder commented 1 week ago

Hi @vadi2, thanks for posting your solution, it's useful feature.

The only addition from my side to this feature - it should follow the specification of resolving references, in that case reference 'Patient/123' should be also resolved into the entry with fullUrl http://example.com/fhir/Patient/123.

ruscoder commented 1 week ago

The fhirpath specification says nothing about how exactly url's should be resolved.

For me, it looks logical to have a Bundle as context, and use it like: evaluate(bundle, 'entry.resource.ofType(Patient).managingOrganization.resolve()') should return all patients' organizations.