搜索 FHIR 资源

本页面介绍了如何在 FHIR 存储区中搜索 FHIR 资源的基本说明。搜索 FHIR 资源是查询 FHIR 数据和从中汲取数据洞见的主要方法。

您可以通过以下方式在 Cloud Healthcare API 中搜索 FHIR 资源:

本页面汇总了许多常用搜索功能,但并未完整列出 Cloud Healthcare API 支持的部分 FHIR 搜索规范

使用 FHIR 查看器

FHIR 查看器是 Cloud Console 中的一个页面,让您可以搜索和查看 FHIR 资源的内容

如需在 FHIR 存储区中搜索资源,请按照以下步骤操作:

  1. 在 Cloud Console 中,转到 FHIR 查看器页面。

    转到 FHIR 查看器

  2. FHIR 存储区 (FHIR Store) 下拉列表中,选择一个数据集,然后在该数据集中选择 FHIR 存储区。

  3. 如需过滤资源类型列表,请搜索您要显示的资源类型:

    1. 点击资源类型字段。

    2. 在显示的属性下拉列表中,选择资源类型

    3. 输入一种资源类型。

    4. 如需搜索其他资源类型,请从显示的运算符下拉列表中选择 OR,然后输入其他资源类型。

  4. 在资源类型列表中,选择您要搜索的资源类型。

  5. 在显示的资源表的搜索框中,输入您要搜索的值。

FHIR 查看器会在表中显示搜索结果。选择一种资源后,FHIR 查看器会显示该资源的内容。

查看某资源的内容时,您可以搜索该资源内的数据。

如需搜索资源内的数据,请按照以下步骤操作:

  1. 选择一种资源。

  2. FHIR 查看器窗格中,点击元素标签页。

  3. 在搜索框中,输入您要搜索的值。

使用 search 方法

要使用 REST API 搜索 FHIR 资源,请使用 projects.locations.datasets.fhirStores.fhir.search 方法。您可以使用 GETPOST 请求调用此方法。

使用 search 方法和 GET

以下示例展示了如何使用 projects.locations.datasets.fhirStores.fhir.search 方法和 GET 在给定 FHIR 存储区中搜索资源。

curl

要搜索 FHIR 存储区中的资源,请发出 GET 请求并指定以下信息:

  • 数据集的名称
  • FHIR 存储区的名称
  • 要搜索的资源类型
  • 查询字符串包含要搜索的信息,如构建搜索查询部分中所述
  • 访问令牌

以下示例显示了一个使用 curl 搜索所有姓“Smith”患者的 GET 请求。

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient?family:exact=Smith"

如果请求成功,服务器将以 JSON 格式的 FHIR Bundle形式返回响应。Bundle.typesearchset,搜索结果是 Bundle.entry 数组中的条目。在此示例中,请求返回单个患者资源,包括该资源内的数据:

{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "LAST_UPDATED",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

PowerShell

要搜索 FHIR 存储区中的资源,请发出 GET 请求并指定以下信息:

  • 数据集的名称
  • FHIR 存储区的名称
  • 要搜索的资源类型
  • 查询字符串包含要搜索的信息,如构建搜索查询部分中所述
  • 访问令牌

以下示例显示了一个使用 Windows PowerShell 搜索所有姓“Smith”患者的 GET 请求。

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE?family:exact=Smith" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式的 FHIR Bundle形式返回响应。Bundle.typesearchset,搜索结果是 Bundle.entry 数组中的条目。在此示例中,请求返回单个患者资源,包括该资源内的数据:

{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "LAST_UPDATED",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

public class FhirResourceSearchGet {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceSearchGet(String resourceName)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

    HttpUriRequest request =
        RequestBuilder.get()
            .setUri(uriBuilder.build())
            .addHeader("Content-Type", "application/fhir+json")
            .addHeader("Accept-Charset", "utf-8")
            .addHeader("Accept", "application/fhir+json; charset=utf-8")
            .build();

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      System.err.print(
          String.format(
              "Exception searching GET FHIR resources: %s\n", response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.println("FHIR resource search results: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const searchFhirResourcesGet = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir`;
  const request = {parent, resourceType};

  const response =
    await healthcare.projects.locations.datasets.fhirStores.fhir.search(
      request
    );
  const resources = response.data.entry;
  console.log(`Resources found: ${resources.length}`);
  console.log(JSON.stringify(resources, null, 2));
};

searchFhirResourcesGet();

Python

def search_resources_get(
    project_id,
    location,
    dataset_id,
    fhir_store_id,
    resource_type,
):
    """
    Uses the searchResources GET method to search for resources in the given FHIR store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports Python's built-in "os" module
    import os

    # Imports the google.auth.transport.requests transport
    from google.auth.transport import requests

    # Imports a module to allow authentication using a service account
    from google.oauth2 import service_account

    # Gets credentials from the environment.
    credentials = service_account.Credentials.from_service_account_file(
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    )
    scoped_credentials = credentials.with_scopes(
        ["https://www.googleapis.com/auth/cloud-platform"]
    )
    # Creates a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    # URL to the Cloud Healthcare API endpoint and version
    base_url = "https://healthcare.googleapis.com/v1"

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    # fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID
    # resource_type = 'Patient'  # replace with the FHIR resource type
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, location)

    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/{}".format(
        url, dataset_id, fhir_store_id, resource_type
    )

    response = session.get(resource_path)
    response.raise_for_status()

    resources = response.json()

    print(
        "Using GET request, found a total of {} {} resources:".format(
            resources["total"], resource_type
        )
    )
    print(json.dumps(resources, indent=2))

    return resources

使用 search 方法和 POST

以下示例展示了如何使用 projects.locations.datasets.fhirStores.fhir.search 方法和 POST 在给定 FHIR 存储区中搜索资源。

curl

要搜索 FHIR 存储区中的资源,请发出 POST 请求并指定以下信息:

  • 数据集的名称
  • FHIR 存储区的名称
  • 要搜索的资源类型
  • 查询字符串包含要搜索的信息,如构建搜索查询部分中所述
  • 访问令牌

以下示例显示了一个使用 curl 搜索所有姓“Smith”患者的 POST 请求。

curl -X POST \
    --data "" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/fhir+json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith"

如果请求成功,服务器将以 JSON 格式的 FHIR Bundle形式返回响应。Bundle.typesearchset,搜索结果是 Bundle.entry 数组中的条目。在此示例中,请求返回单个患者资源,包括该资源内的数据:

{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "LAST_UPDATED",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

PowerShell

要搜索 FHIR 存储区中的资源,请发出 POST 请求并指定以下信息:

  • 数据集的名称
  • FHIR 存储区的名称
  • 要搜索的资源类型
  • 查询字符串包含要搜索的信息,如构建搜索查询部分中所述
  • 访问令牌

以下示例显示了一个使用 Windows PowerShell 搜索所有姓“Smith”患者的 POST 请求。

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式的 FHIR Bundle形式返回响应。Bundle.typesearchset,搜索结果是 Bundle.entry 数组中的条目。在此示例中,请求返回单个患者资源,包括该资源内的数据:

{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "LAST_UPDATED",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

public class FhirResourceSearchPost {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceSearchPost(String resourceName)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s/_search", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
    StringEntity requestEntity = new StringEntity("");

    HttpUriRequest request =
        RequestBuilder.post()
            .setUri(uriBuilder.build())
            .setEntity(requestEntity)
            .addHeader("Content-Type", "application/fhir+json")
            .addHeader("Accept-Charset", "utf-8")
            .addHeader("Accept", "application/fhir+json; charset=utf-8")
            .build();

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      System.err.print(
          String.format(
              "Exception searching POST FHIR resources: %s\n",
              response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.println("FHIR resource search results: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  method: 'POST',
});

const searchFhirResourcesPost = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir`;
  const request = {parent, resourceType};

  const response =
    await healthcare.projects.locations.datasets.fhirStores.fhir.search(
      request
    );
  const resources = response.data.entry;
  console.log(`Resources found: ${resources.length}`);
  console.log(JSON.stringify(resources, null, 2));
};

searchFhirResourcesPost();

Python

def search_resources_post(project_id, location, dataset_id, fhir_store_id):
    """
    Searches for resources in the given FHIR store. Uses the
    _search POST method and a query string containing the
    information to search for. In this sample, the search criteria is
    'family:exact=Smith' on a Patient resource.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports Python's built-in "os" module
    import os

    # Imports the google.auth.transport.requests transport
    from google.auth.transport import requests

    # Imports a module to allow authentication using a service account
    from google.oauth2 import service_account

    # Gets credentials from the environment.
    credentials = service_account.Credentials.from_service_account_file(
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    )
    scoped_credentials = credentials.with_scopes(
        ["https://www.googleapis.com/auth/cloud-platform"]
    )
    # Creates a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    # URL to the Cloud Healthcare API endpoint and version
    base_url = "https://healthcare.googleapis.com/v1"

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    # fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, location)

    fhir_store_path = "{}/datasets/{}/fhirStores/{}/fhir".format(
        url, dataset_id, fhir_store_id
    )

    resource_path = "{}/Patient/_search?family:exact=Smith".format(fhir_store_path)

    # Sets required application/fhir+json header on the request
    headers = {"Content-Type": "application/fhir+json;charset=utf-8"}

    response = session.post(resource_path, headers=headers)
    response.raise_for_status()

    resources = response.json()
    print(
        "Using POST request, found a total of {} Patient resources:".format(
            resources["total"]
        )
    )

    print(json.dumps(resources, indent=2))

    return resources

构建搜索查询

查询字符串是一系列以网址形式编码的 name=value 对。搜索将所有对与逻辑 AND 组合。每个值都可以是逗号分隔列表中的值,这些值会被视为这些值的逻辑 OR。例如,Patient?key1=value1&key2=value2,value3 是使用以下条件对患者资源进行的搜索:

(key1 = value1) AND (key2 = value2 OR key2 = value3)

没有语法可执行两个 name=value 对的 OR

每种 FHIR 资源类型都会在每个版本的 FHIR 中定义自己的搜索参数。可用参数记录在每个资源的 FHIR 规范中。如需查看示例,请参阅 FHIR R4 患者。您可以通过功能语句以编程方式检索参数。Cloud Healthcare API 支持大多数搜索参数;您可以通过功能语句或 FHIR 一致性声明找到排除项。

分页和排序

_count 参数控制搜索方法返回的最大资源数。例如,_count=10 最多返回 10 个与查询匹配的资源。默认值为 100,允许的最大值为 1000。

如果搜索返回的资源超出一个页面所能容纳的次数,则响应会 Bundle.link 字段中包含分页网址。此字段中可能返回多个值;值为 Bundle.link.relation = next 表示您可以使用相应的 Bundle.link.url 来检索下一页。

Bundle.total 的值表示匹配资源的总数。如果结果完全适合一个网页,则此值是准确的,但随着结果的数量超过一个网页,此值会变为粗略的估算值。您可以重复跟踪分页链接,直到结果用尽,从而获取与许多结果相匹配的精确匹配的搜索总数。

您可以使用 _sort 参数对结果进行排序,该参数接受优先级顺序的逗号分隔搜索参数名称列表。您可以使用 - 前缀表示降序。例如,以下查询按状态升序排序、按日期降序排列断开关系以及按类别断开所有的剩余关系:

_sort=status,-date,category

索引延迟

FHIR 资源会以异步方式编入索引,因此资源的创建或更改时间与创建和更改反映在搜索结果中的时间可能会略有延迟。

搜索所有资源类型

某些搜索参数(通过 _id 等前导下划线显示)适用于所有资源类型。这些全资源参数在资源类型的 FHIR 规范中列出。

使用这些搜索参数时,您可以通过从请求路径中省略资源类型,跨多个资源类型执行搜索。例如,使用 GET .../fhir?_id=1234 而不是 GET .../fhir/Patient?_id=1234 搜索所有 FHIR 资源,而不是仅搜索患者资源。您可以对此类请求使用特殊参数 _type,将结果限制为以英文逗号分隔的资源类型列表。例如,以下查询仅返回 ObservationCondition 资源的匹配结果:

GET .../fhir?_tag=active&_type=Observation,Condition

数据类型

由 FHIR 定义的每个搜索参数都有一个数据类型,其中包括以下原始类型:

  • 字符串
  • 数字
  • 日期

数据类型还包括以下复杂类型:

  • 令牌
  • 参考
  • 数量

每种数据类型都有自己的语法,用于指定值。每种数据类型都支持用于改变搜索方式的修饰符。

以下部分介绍了如何使用数据类型。如需详细了解其他数据类型、值语法和修饰符,请参阅高级 FHIR 搜索功能

数字

搜索整数或浮点值。如需更改比较器,请在值前面加上以下修饰符之一:

  • ne
  • lt
  • le
  • gt
  • ge

例如,使用 [parameter]=100 表示相等性,或使用 [parameter]=ge100 大于或等于 100。

日期

搜索任何类型的日期、时间或时间段。日期参数格式如下:

yyyy-mm-ddThh:mm:ss[Z|(+|-)hh:mm]

使用与 number 相同的前缀修饰符。

字符串

默认为不区分大小写、重音符号或其他变音符号的前缀搜索。

令牌

搜索“code”的完全匹配字符串您可以将搜索范围限定为“system”的 URI,并使用以下格式指示从中获取代码的值集:

[parameter]=[system]|[code]

例如,仅当被限定为具有指定 URI 的编码系统的值时,以下搜索与 10738-3 的代码匹配:

code=http://hl7.org/fhir/ValueSet/observation-codes|10738-3

数量

使用与 number 相同的前缀修饰符搜索数值。您可以使用特定系统和代码来限定搜索,以下列格式指示值的单位:

[parameter]=[prefix][number]|[system]|[code]

例如,以下查询搜索小于 9.1 且具有指定单位系统和代码的数量值:

value-quantity=lt9.1|http://unitsofmeasure.org|mg

参考

搜索资源之间的引用。您可以使用以下查询来引用 FHIR 存储区中的资源:

  • [parameter]=[id]
  • [parameter]=[type]/[id]

您可以使用 [parameter]=[url] 通过可能在 FHIR 存储区之外的网址指定引用。

搜索参数处理

默认情况下,搜索方法会应用“宽松”处理,该处理会忽略搜索无法识别的参数。搜索方法使用请求中的任何剩余参数执行搜索,这些参数可能会返回超出预期的资源。

响应包括以下内容:

  • Bundle.link 中值为 Bundle.link.relation = self 的值
  • 网址中的 Bundle.link.url,仅包含已成功应用于搜索的参数。您可以检查此值,以确定是否忽略了任何参数。

您可以在搜索请求中将请求 HTTP 标头设置为 Prefer: handling=strict。设置标头会导致 FHIR 存储在任何无法识别的参数上返回错误。