다음을 통해 공유


해결 프로그램을 위한 Cosmos DB 데이터 원본

적용 대상: 개발자 | 기본 | 기본 v2 | 표준 | 표준 v2 | 프리미엄

cosmosdb-data-source 해결 프로그램 정책은 Cosmos DB 데이터 원본을 사용하여 GraphQL 스키마의 개체 형식 및 필드에 대한 데이터를 확인합니다. 스키마는 GraphQL API로 API Management에 가져와야 합니다.

정책을 사용하여 단일 쿼리 요청, 읽기 요청, 삭제 요청 또는 쓰기 요청 및 Cosmos DB 데이터 원본의 선택적 응답을 구성합니다.

참고 항목

이 정책은 미리 보기로 제공됩니다. 현재 이 정책은 API Management 소비 계층에서 지원되지 않습니다.

참고 항목

정책 문에 제공된 순서대로 정책의 요소 및 자식 요소를 설정합니다. API Management 정책을 설정하거나 편집하는 방법에 대해 자세히 알아봅니다.

정책 문

<cosmosdb-data-source> 
    <!-- Required information that specifies connection to Cosmos DB -->
    <connection-info> 
        <connection-string use-managed-identity="true | false"> 
            AccountEndpoint=...;[AccountKey=...;]
        </connection-string> 
        <database-name>Cosmos DB database name</database-name> 
        <container-name>Name of container in Cosmos DB database</container-name>     
    </connection-info>

    <!-- Settings to query using a SQL statement and optional query parameters -->
    <query-request enable-low-precision-order-by="true | false"> 
        <sql-statement> 
            SQL statement 
        </sql-statement> 
        <parameters> 
            <parameter name="Query parameter name in @ notation"> 
                "Query parameter value or expression"
            </parameter>
            <!-- if there are multiple parameters, then add additional parameter elements --> 
        </parameters> 
        <partition-key data-type="string | number | bool | none | null" template="liquid" > 
            "Container partition key" 
        </partition-key> 
        <paging> 
            <max-item-count template="liquid" > 
                Maximum number of items returned by query
            </max-item-count> 
            <continuation-token template="liquid"> 
                Continuation token for paging 
            </continuation-token> 
        </paging>
    </query-request>
    
    <!-- Settings to read item by item ID and optional partition key --> 
    <read-request> 
        <id template="liquid" >
            "Item ID in container"
        </id> 
        <partition-key data-type="string | number | bool | none | null" template="liquid" > 
            "Container partition key" 
        </partition-key>  
    </read-request> 
    
    <!-- Settings to delete item by ID and optional partition key --> 
    <delete-request consistency-level="bounded-staleness | consistent-prefix | eventual | session | strong" pre-trigger="myPreTrigger" post-trigger="myPostTrigger">
        <etag type="entity tag type" template="liquid" > 
            "System-generated entity tag" 
        </etag> 
        <id template="liquid">
            "Item ID in container"
        </id> 
        <partition-key data-type="string | number | bool | none | null" template="liquid"> 
            "Container partition key" 
        </partition-key> 
    </delete-request> 
    
    <!-- Settings to write item -->
    <write-request type="insert | replace | upsert" consistency-level="bounded-staleness | consistent-prefix | eventual | session | strong" pre-trigger="myPreTrigger" post-trigger="myPostTrigger">
        <id template="liquid">
            "Item ID in container"
        </id>
         <partition-key data-type="string | number | bool | none | null" template="liquid"> 
            "Container partition key"
        </partition-key>      
        <etag type="match | no-match" template="liquid" > 
            "System-generated entity tag" 
        </etag>
        <set-body template="liquid" >...set-body policy configuration...</set-body> 
    </write-request>
    
    <response> 
        <set-body>...set-body policy configuration...</set-body> 
        <publish-event>...publish-event policy configuration...</publish-event>
    </response>
    
</cosmosdb-data-source> 

Elements

이름 설명 필수
connection-info Cosmos DB 데이터베이스의 컨테이너에 대한 연결을 지정합니다.
query-request Cosmos DB 컨테이너에 대한 쿼리 요청의 설정을 지정합니다. query-request, read-request, delete-request, write-request 중 하나를 구성
read-request Cosmos DB 컨테이너에 대한 읽기 요청의 설정을 지정합니다. query-request, read-request, delete-request, write-request 중 하나를 구성
delete-request Cosmos DB 컨테이너에 대한 삭제 요청의 설정을 지정합니다. query-request, read-request, delete-request, write-request 중 하나를 구성
write-request Cosmos DB 컨테이너에 대한 쓰기 요청의 설정을 지정합니다. query-request, read-request, delete-request, write-request 중 하나를 구성
response 선택적으로 해결 프로그램의 응답을 구성하는 자식 정책을 지정합니다. 지정하지 않으면 Cosmos DB에서 JSON으로 응답이 반환됩니다. 아니요

connection-info 요소

이름 설명 필수
connection-string Cosmos DB 계정에 대한 연결 문자열을 지정합니다. API Management 관리 ID가 구성된 경우 계정 키를 생략합니다.
database-name 문자열입니다. Cosmos DB 데이터베이스의 이름입니다.
container-name 문자열입니다. Cosmos DB 데이터베이스의 컨테이너 이름입니다.

connection-string 특성

attribute 설명 필수 항목 기본값
use-managed-identity 부울입니다. Cosmos DB 계정에 연결하는 데 연결 문자열의 계정 키 대신 API Management 인스턴스의 시스템 할당 관리 ID를 사용할지 여부를 지정합니다. Cosmos DB 컨테이너에 액세스하도록 ID를 구성해야 합니다. 아니요 false

query-request 특성

attribute 설명 필수 항목 기본값
enable-low-precision-order-by 부울입니다. Cosmos DB 서비스에서 EnableLowPrecisionOrderBy 쿼리 요청 속성을 사용할지 여부를 지정합니다. 아니요 해당 없음

query-request 요소

이름 설명 필수
sql-statement 쿼리 요청에 대한 SQL 문입니다. 아니요
매개 변수 쿼리 요청에 대한 매개 변수 하위 요소의 쿼리 매개 변수 목록입니다. 아니요
partition-key 쿼리를 컨테이너의 위치로 라우팅하는 Cosmos DB 파티션 키 입니다. 아니요
paging 쿼리 결과를 여러 페이지로 분할하는 설정을 지정합니다. 아니요

parameter 특성

attribute 설명 필수 항목 기본값
name 문자열입니다. @ 표기법의 매개 변수 이름입니다. 해당 없음

paging 요소

이름 설명 필수
max-item-count 쿼리에서 반환되는 최대 항목 수를 지정합니다. 쿼리 실행당 결과 수에 제한을 두지 않으려면 -1로 설정합니다.
continuation-token 다음 결과 집합을 가져오기 위해 쿼리에 연결할 연속 토큰 을 지정합니다.

max-item-count attribute

attribute 설명 필수 항목 기본값
템플릿 max-item-count에 대한 템플릿 모드를 설정하는 데 사용됩니다. 현재 지원되는 유일한 값:

- liquid - max-item-count은(는) liquid 템플릿 엔진을 사용합니다.
아니요 해당 없음

continuation-token 특성

attribute 설명 필수 항목 기본값
템플릿 연속 토큰에 대한 템플릿 모드를 설정하는 데 사용됩니다. 현재 지원되는 유일한 값:

- liquid - 연속 토큰은 liquid 템플릿 엔진을 사용합니다.
아니요 해당 없음

read-request 요소

이름 설명 필수
id 컨테이너에서 읽을 항목의 식별자입니다.
partition-key 컨테이너에 있는 항목의 위치에 대한 파티션 키입니다. id(으)로 지정된 경우 컨테이너에 있는 항목의 빠른 지점 읽기(키/값 조회)를 사용하도록 설정합니다. 아니요

delete-request 특성

attribute 설명 필수 항목 기본값
consistency-level 문자열입니다. 삭제 요청의 Cosmos DB 일관성 수준을 설정합니다. 아니요 해당 없음
pre-trigger 문자열입니다. Cosmos DB 컨테이너에 등록된 pre-trigger 함수의 식별자입니다. 아니요 해당 없음
post-trigger 문자열입니다. Cosmos DB 컨테이너에 등록된 post-trigger 함수의 식별자입니다. 아니요 해당 없음

delete-request 요소

이름 설명 필수
id 컨테이너에서 삭제할 항목의 식별자입니다.
partition-key 컨테이너에 있는 항목의 위치에 대한 파티션 키입니다. 아니요
etag 컨테이너의 항목에 대한 엔터티 태그로, 낙관적 동시성 제어에 사용됩니다. 아니요

write-request 특성

attribute 설명 필수 항목 기본값
type 쓰기 요청 형식(insert, replace 또는 upsert)입니다. 아니요 upsert
consistency-level 문자열입니다. 쓰기 요청의 Cosmos DB 일관성 수준을 설정합니다. 아니요 해당 없음
indexing-directive 컨테이너 항목을 인덱싱하는 방법을 결정하는 인덱싱 정책입니다. 아니요 default
pre-trigger 문자열입니다. Cosmos DB 컨테이너에 등록된 pre-trigger 함수의 식별자입니다. 아니요 해당 없음
post-trigger 문자열입니다. Cosmos DB 컨테이너에 등록된 post-trigger 함수의 식별자입니다. 아니요 해당 없음

write-request 요소

이름 설명 필수
id 컨테이너에 있는 항목의 식별자입니다. type이(가) replace이면 예입니다.
etag 컨테이너의 항목에 대한 엔터티 태그로, 낙관적 동시성 제어에 사용됩니다. 아니요
set-body 쓰기 요청의 본문을 설정합니다. 제공되지 않으면 요청 페이로드는 인수를 JSON 형식으로 매핑합니다. 아니요

response 요소

이름 설명 필수
set-body 해결 프로그램의 응답에서 본문을 설정합니다. 제공되지 않고 반환된 JSON에 GraphQL 스키마의 필드와 일치하는 필드 이름이 포함되어 있으면 필드가 자동으로 매핑됩니다. 아니요
publish-event GraphQL API 스키마에 지정된 하나 이상의 구독에 이벤트를 게시합니다. 아니요

partition-key 특성

attribute 설명 필수 항목 기본값
data-type 파티션 키의 데이터 형식(string, number, bool, none 또는 null)입니다. 아니요 string
템플릿 파티션 키에 대한 템플릿 모드를 설정하는 데 사용됩니다. 현재 지원되는 유일한 값:

- liquid - 파티션 키는 liquid 템플릿 엔진을 사용합니다.
아니요 해당 없음

etag 특성

attribute 설명 필수 항목 기본값
type 문자열입니다. 다음 값 중 하나:

- match - etag 값이 항목의 시스템 생성 엔터티 태그와 일치해야 합니다.

- no-match - etag 값이 항목의 시스템 생성 엔터티 태그와 일치할 필요가 없습니다.
아니요 match
템플릿 etag에 대한 템플릿 모드를 설정하는 데 사용됩니다. 현재 지원되는 유일한 값:

- liquid - etag는 liquid 템플릿 엔진을 사용합니다.
아니요 해당 없음

사용

사용법 참고 사항

  • 이 정책을 사용하여 해결 프로그램을 구성하고 관리하려면 GraphQL 해결 프로그램 구성을 참조하세요.
  • 이 정책은 스키마의 일치하는 작업 형식에서 단일 필드를 확인할 때만 호출됩니다.

Cosmos DB와 관리 ID의 통합 구성

Cosmos DB 계정에 액세스하는 데 연결 문자열의 계정 키를 제공하는 대신 API Management 시스템이 할당한 관리 ID를 구성할 수 있습니다.

다음 단계에 따라 Azure CLI를 사용하여 관리 ID를 구성합니다.

필수 조건

관리 ID를 구성하는 Azure CLI 스크립트

# Set variables

# Variable for Azure Cosmos DB account name
cosmosName="<MY-COSMOS-DB-ACCOUNT>"

# Variable for resource group name
resourceGroupName="<MY-RESOURCE-GROUP>"

# Variable for subscription
resourceGroupName="<MY-SUBSCRIPTION-NAME>"

# Set principal variable to the value from Managed identities page of API Management instance in Azure portal
principal="<MY-APIM-MANAGED-ID-PRINCIPAL-ID>"

# Get the scope value of Cosmos DB account
 
scope=$(
    az cosmosdb show \
        --resource-group $resourceGroupName \
        --name $cosmosName \
        --subscription $subscriptionName \
        --query id \
        --output tsv
)

# List the built-in Cosmos DB roles
# Currently, the roles aren't visible in the portal

az cosmosdb sql role definition list \
    --resource-group $resourceGroupName \
    --account-name $cosmosName \
    --subscription $subscriptionName \

# Take note of the role you want to assign, such as "Cosmos DB Built-in Data Contributor" in this example

# Assign desired Cosmos DB role to managed identity

az cosmosdb sql role assignment create \
    --resource-group $resourceGroupName \
    --account-name $cosmosName \
    --subscription $subscriptionName \
    --role-definition-name "Cosmos DB Built-in Data Contributor" \
    --principal-id $principal \
    --scope $scope    

예제

Cosmos DB 쿼리 요청

다음 예제에서는 Cosmos DB 컨테이너에 대한 SQL 쿼리를 사용하여 GraphQL 쿼리를 해결합니다.

<cosmosdb-data-source>
    <connection-info>
        <connection-string>
            AccountEndpoint=https://contoso-cosmosdb.
documents.azure.com:443/;AccountKey=CONTOSOKEY;
        </connection-string>
        <database-name>myDatabase</database-name>
        <container-name>myContainer</container-name>
    </connection-info>
    <query-request>
        <sql-statement>SELECT * FROM c </sql-statement>
    </query-request>
</cosmosdb-data-source>

Cosmos DB 읽기 요청

다음 예제에서는 Cosmos DB 컨테이너에 대한 지점 읽기 요청을 사용하여 GraphQL 쿼리를 해결합니다. Cosmos DB 계정에 대한 연결은 API Management 인스턴스의 시스템이 할당한 관리 ID를 사용합니다. Cosmos DB 컨테이너에 액세스하도록 ID를 구성해야 합니다.

읽기 요청에 사용되는 id과(와) partition-key은(는) 쿼리 매개 변수로 전달되고 context.GraphQL.Arguments["id"] 컨텍스트 변수를 사용하여 액세스됩니다.

<cosmosdb-data-source>
    <connection-info>
        <connection-string use-managed-identity="true">
            AccountEndpoint=https://contoso-cosmosdb.
documents.azure.com:443/;
        </connection-string>
        <database-name>myDatabase</database-name>
        <container-name>myContainer</container-name>
    </connection-info>
    <read-request>
        <id>
            @(context.GraphQL.Arguments["id"].ToString())
        </id>
        <partition-key>
            @(context.GraphQL.Arguments["id"].ToString())
    <read-request>
</cosmosdb-data-source>

Cosmos DB 삭제 요청

다음 예제에서는 Cosmos DB 컨테이너에 대한 삭제 요청으로 GraphQL 변형을 해결합니다. 삭제 요청에 사용되는 id과(와) partition-key은(는) 쿼리 매개 변수로 전달되고 context.GraphQL.Arguments["id"] 컨텍스트 변수를 사용하여 액세스됩니다.

<cosmosdb-data-source>
    <connection-info>
        <connection-string>
            AccountEndpoint=https://contoso-cosmosdb.
documents.azure.com:443/;AccountKey=CONTOSOKEY;
        </connection-string>
        <database-name>myDatabase</database-name>
        <container-name>myContainer</container-name>
    </connection-info>
    <delete-request>
        <id>
            @(context.GraphQL.Arguments["id"].ToString())
        </id>
        <partition-key>
            @(context.GraphQL.Arguments["id"].ToString())
        </partition-key>
    </delete-request>
</cosmosdb-data-source>

Cosmos DB 쓰기 요청

다음 예제에서는 Cosmos DB 컨테이너에 대한 upsert 요청으로 GraphQL 변형을 해결합니다. Cosmos DB 계정에 대한 연결은 API Management 인스턴스의 시스템이 할당한 관리 ID를 사용합니다. Cosmos DB 컨테이너에 액세스하도록 ID를 구성해야 합니다.

쓰기 요청에 사용되는 partition-key은(는) 쿼리 매개 변수로 전달되고 컨텍스트 변수를 context.GraphQL.Arguments["id"] 사용하여 액세스됩니다. upsert 요청에는 "validateInput"이라는 사전 트리거 작업이 있습니다. 요청 본문은 liquid 템플릿을 사용하여 매핑됩니다.

<cosmosdb-data-source>
    <connection-info>
        <connection-string use-managed-identity="true">
            AccountEndpoint=https://contoso-cosmosdb.
documents.azure.com:443/;
        </connection-string>
        <database-name>myDatabase</database-name>
        <container-name>myContainer</container-name>
    </connection-info>
    <write-request type="upsert" pre-trigger="validateInput">
        <partition-key>
            @(context.GraphQL.Arguments["id"].ToString())
        </partition-key>
        <set-body template="liquid">
            {"id" : "{{body.arguments.id}}" ,
            "firstName" : "{{body.arguments.firstName}}",
            "intField" : {{body.arguments.intField}} ,
            "floatField" : {{body.arguments.floatField}} ,
            "boolField" : {{body.arguments.boolField}}}
        </set-body>
    </write-request>
</cosmosdb-data-source>

Cosmos DB 쿼리에 대한 매개 변수 입력 생성

다음 예제에서는 정책 식을 사용하여 Cosmos DB 매개 변수화된 쿼리를 생성하는 방법을 보여줍니다. 매개 변수 입력의 형식에 따라 메서드를 선택합니다.

예제는 다음 샘플 GraphQL 스키마를 기반으로 하며, 상응하는 Cosmos DB 매개 변수화된 쿼리를 생성합니다.

예제 GraphQL 스키마

input personInput {
  id: String!
  firstName: String
}

type Query {
  personsStringParam(stringInput: String): personsConnection
  personsPersonParam(input: personInput): personsConnection
}

예제 Cosmos DB 쿼리

{
    "query": "query { 
        personsPersonParam(input: { id: \"3\" } { 
        items { id firstName lastName } 
        } 
    }"
}    

식에서 JObject(JSON 개체) 전달

예제 정책

[...]
<query-request>
    <sql-statement>SELECT * FROM c where c.familyId =@param.id</sql-statement>
    <parameters>
        <parameter name="@param">@(context.GraphQL.Arguments["input"])</parameter>
    </parameters>
    </query-request>
[...]

식에서 .NET 입력 형식(string, int, decimal, bool) 전달

예제 정책

[...]
<query-request>
    <sql-statement>SELECT * FROM c where c.familyId =@param</sql-statement>
    <parameters>
        <parameter name="@param">@($"start.{context.GraphQL.Arguments["stringInput"]}")</parameter>
    </parameters>
</query-request>
[...]

식에서 JValue(JSON 값) 전달

예제 정책

[...]
<query-request>
    <sql-statement>SELECT * FROM c where c.familyId =@param</sql-statement>
    <parameters>
        <parameter name="@param">@(context.GraphQL.Arguments["stringInput"])</parameter>
    </parameters>
</query-request>
[...]

정책 작업에 대한 자세한 내용은 다음을 참조하세요.