중요합니다
여러 지역에서 99.999% 가용성 서비스 수준 계약, 즉각적인 자동 크기 조정 및 자동 장애 조치(failover)가 있는 대규모 시나리오에 대한 데이터베이스 솔루션을 찾고 있나요? NoSQL용 Azure Cosmos DB를 고려합니다.
OLAP(온라인 분석 처리) 그래프를 구현하거나 기존 Apache Gremlin 애플리케이션을 마이그레이션하시겠습니까? Microsoft Fabric에서 그래프를 고려합니다.
구조화되지 않은 데이터를 저장, 관리 및 쿼리하는 Node.js Azure Cosmos DB for Apache Gremlin 클라이언트 라이브러리를 시작합니다. 이 가이드의 단계에 따라 새 계정을 만들고, Node.js 클라이언트 라이브러리를 설치하고, 계정에 연결하고, 일반적인 작업을 수행하고, 최종 샘플 데이터를 쿼리합니다.
필수 구성 요소
Azure 구독
- Azure 구독이 없는 경우, 시작하기 전에 무료 계정을 만드십시오.
Azure Cloud Shell에서 최신 버전의 Azure CLI입니다.
- CLI 참조 명령을 로컬로 실행하려면 명령을 사용하여 Azure CLI에 로그인합니다
az login.
- CLI 참조 명령을 로컬로 실행하려면 명령을 사용하여 Azure CLI에 로그인합니다
- Node.js 22 이상
설치
먼저 이 가이드에 대한 계정 및 개발 환경을 설정합니다. 이 섹션에서는 계정을 만들고 자격 증명을 얻은 다음 개발 환경을 준비하는 프로세스를 안내합니다.
계정 만들기
먼저 Apache Gremlin 계정에 대한 API를 만듭니다. 계정이 만들어지면 데이터베이스 및 그래프 리소스를 만듭니다.
대상 리소스 그룹이 아직 없는 경우 이 명령을 사용하여
az group create구독에 새 리소스 그룹을 만듭니다.az group create \ --name "<resource-group-name>" \ --location "<location>"명령을
az cosmosdb create사용하여 기본 설정으로 새 Azure Cosmos DB for Apache Gremlin 계정을 만듭니다.az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableGremlin"새 데이터베이스를
az cosmosdb gremlin database create로 생성하고cosmicworks으로 명명합니다.az cosmosdb gremlin database create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"명령을
az cosmosdb gremlin graph create사용하여 이름이 지정된 새 그래프를 만듭니다products.az cosmosdb gremlin graph create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --database-name "cosmicworks" \ --name "products" \ --partition-key-path "/category"
자격 증명 가져오기
이제 최근에 만든 계정에 대한 연결을 만드는 데 사용할 클라이언트 라이브러리의 암호를 가져옵니다.
az cosmosdb show를 사용하여 계정의 호스트를 가져옵니다.az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{host:name}"이전 명령의
host출력에서 속성 값을 기록합니다. 이 속성의 값은 이 가이드의 뒷부분에서 라이브러리를 사용하여 계정에 연결하는 데 사용하는 호스트 입니다.계정의
az cosmosdb keys list가져오는 데 사용합니다.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"이전 명령의
primaryMasterKey출력에서 속성 값을 기록합니다. 이 속성의 값은 이 가이드의 뒷부분에서 라이브러리를 사용하여 계정에 연결하는 데 사용하는 키 입니다.
개발 환경 준비
그런 다음 새 프로젝트 및 클라이언트 라이브러리를 사용하여 개발 환경을 구성합니다. 이 단계는 이 가이드의 나머지 단계로 넘어가기 전에 마지막으로 필요한 필수 구성 요소입니다.
빈 폴더에서 시작합니다.
새 모듈을 초기화합니다.
npm init es6 --yesgremlin노드 패키지 관리자(npm)에서 패키지를 설치합니다.npm install --save gremlinindex.js 파일을 만듭니다.
빈 폴더에서 시작합니다.
새 모듈을 초기화합니다.
npm init es6 --yestypescript노드 패키지 관리자(npm)에서 패키지를 설치합니다.npm install --save-dev typescripttsxnpm에서 패키지를 설치합니다.npm install --save-dev tsxgremlinnpm에서 패키지를 설치합니다.npm install --save gremlin@types/nodenpm에서 패키지를 설치합니다.npm install --save-dev @types/node@types/gremlinnpm에서 패키지를 설치합니다.npm install --save-dev @types/gremlin컴파일러(
tsc)를 사용하여 TypeScript 프로젝트를 초기화합니다.npx tsc --init --target es2017 --module es2022 --moduleResolution nodenextindex.ts 파일을 만듭니다.
개체 모델
| 설명 | |
|---|---|
DriverRemoteConnection |
Gremlin 서버에 대한 연결을 나타냅니다. |
GraphTraversalSource |
Gremlin 탐색을 생성하고 실행하는 데 사용됩니다. |
코드 예제
클라이언트 인증
먼저 이 가이드의 앞부분에서 수집한 자격 증명을 사용하여 클라이언트를 인증합니다.
IDE(통합 개발 환경)에서 index.js 파일을 엽니다.
gremlin패키지 및 필요한 타입을 임포트합니다.import gremlin from 'gremlin'; const { Client, auth } = gremlin.driver; const { PlainTextSaslAuthenticator } = auth;이 가이드의 앞부분에서 수집된 자격 증명에 대한 문자열 변수를 만듭니다. 변수
hostname와primaryKey의 이름을 지정하십시오.const hostname = '<host>'; const primaryKey = '<key>';이전 단계에서 만든 자격 증명 및 구성 변수를 사용하여 형식
PlainTextSaslAuthenticator의 개체를 만듭니다. 개체를 변수authenticator에 저장합니다.const authenticator = new PlainTextSaslAuthenticator( '/dbs/cosmicworks/colls/products', primaryKey );인증자
Client변수를 사용하여 개체를 만듭니다. 변수 이름을 지정합니다client.const client = new Client( `wss://${hostname}.gremlin.cosmos.azure.com:443/`, { authenticator, traversalsource: 'g', rejectUnauthorized: true, mimeType: 'application/vnd.gremlin-v2.0+json' } );
IDE(통합 개발 환경)에서 index.ts 파일을 엽니다.
gremlin패키지 및 필요한 타입을 임포트합니다.import gremlin from 'gremlin'; const { Client, auth } = gremlin.driver; const { PlainTextSaslAuthenticator } = auth;이 가이드의 앞부분에서 수집된 자격 증명에 대한 문자열 변수를 만듭니다. 변수
hostname와primaryKey의 이름을 지정하십시오.const hostname: string = '<host>'; const primaryKey: string = '<key>';이전 단계에서 만든 자격 증명 및 구성 변수를 사용하여 형식
PlainTextSaslAuthenticator의 개체를 만듭니다. 개체를 변수authenticator에 저장합니다.const authenticator = new PlainTextSaslAuthenticator( '/dbs/cosmicworks/colls/products', primaryKey );인증자
Client변수를 사용하여 개체를 만듭니다. 변수 이름을 지정합니다client.const client = new Client( `wss://${hostname}.gremlin.cosmos.azure.com:443/`, { authenticator, traversalsource: 'g', rejectUnauthorized: true, mimeType: 'application/vnd.gremlin-v2.0+json' } );
데이터 삽입
다음으로 그래프에 새 꼭짓점 및 에지 데이터를 삽입합니다. 새 데이터를 만들기 전에 기존 데이터의 그래프를 지웁다.
쿼리를
g.V().drop()실행하여 그래프에서 모든 꼭짓점 및 가장자리를 지웁니다.await client.submit('g.V().drop()');꼭짓점을 추가하는 Gremlin 쿼리를 만듭니다.
const insert_vertex_query = ` g.addV('product') .property('id', prop_id) .property('name', prop_name) .property('category', prop_category) .property('quantity', prop_quantity) .property('price', prop_price) .property('clearance', prop_clearance) `;단일 제품에 대한 꼭짓점을 추가합니다.
await client.submit(insert_vertex_query, { prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', prop_name: 'Yamba Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 12, prop_price: 850.00, prop_clearance: false, });두 개의 추가 제품을 위해 꼭짓점을 두 개 더 추가합니다.
await client.submit(insert_vertex_query, { prop_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_name: 'Montau Turtle Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 5, prop_price: 600.00, prop_clearance: true, }); await client.submit(insert_vertex_query, { prop_id: 'cccccccc-2222-3333-4444-dddddddddddd', prop_name: 'Noosa Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 31, prop_price: 1100.00, prop_clearance: false, });에지를 추가하는 다른 Gremlin 쿼리를 만듭니다.
const insert_edge_query = ` g.V([prop_partition_key, prop_source_id]) .addE('replaces') .to(g.V([prop_partition_key, prop_target_id])) `;두 개의 가장자리를 추가합니다.
await client.submit(insert_edge_query, { prop_partition_key: 'gear-surf-surfboards', prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_target_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', }); await client.submit(insert_edge_query, { prop_partition_key: 'gear-surf-surfboards', prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_target_id: 'cccccccc-2222-3333-4444-dddddddddddd', });
쿼리를
g.V().drop()실행하여 그래프에서 모든 꼭짓점 및 가장자리를 지웁니다.await client.submit('g.V().drop()');꼭짓점을 추가하는 Gremlin 쿼리를 만듭니다.
const insert_vertex_query: string = ` g.addV('product') .property('id', prop_id) .property('name', prop_name) .property('category', prop_category) .property('quantity', prop_quantity) .property('price', prop_price) .property('clearance', prop_clearance) `;단일 제품에 대한 꼭짓점을 추가합니다.
await client.submit(insert_vertex_query, { prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', prop_name: 'Yamba Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 12, prop_price: 850.00, prop_clearance: false, });두 개의 추가 제품을 위해 꼭짓점을 두 개 더 추가합니다.
await client.submit(insert_vertex_query, { prop_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_name: 'Montau Turtle Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 5, prop_price: 600.00, prop_clearance: true, }); await client.submit(insert_vertex_query, { prop_id: 'cccccccc-2222-3333-4444-dddddddddddd', prop_name: 'Noosa Surfboard', prop_category: 'gear-surf-surfboards', prop_quantity: 31, prop_price: 1100.00, prop_clearance: false, });에지를 추가하는 다른 Gremlin 쿼리를 만듭니다.
const insert_edge_query: string = ` g.V([prop_partition_key, prop_source_id]) .addE('replaces') .to(g.V([prop_partition_key, prop_target_id])) `;두 개의 가장자리를 추가합니다.
await client.submit(insert_edge_query, { prop_partition_key: 'gear-surf-surfboards', prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_target_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', }); await client.submit(insert_edge_query, { prop_partition_key: 'gear-surf-surfboards', prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc', prop_target_id: 'cccccccc-2222-3333-4444-dddddddddddd', });
데이터 읽기
그런 다음, 이전에 그래프에 삽입된 데이터를 읽습니다.
고유 식별자 및 파티션 키 값을 사용하여 꼭짓점을 읽는 쿼리를 만듭니다.
const read_vertex_query = 'g.V([prop_partition_key, prop_id])';그런 다음 필요한 매개 변수를 제공하여 꼭짓점을 읽습니다.
let read_results = await client.submit(read_vertex_query, { prop_partition_key: 'gear-surf-surfboards', prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', }); let matched_item = read_results._items[0];
고유 식별자 및 파티션 키 값을 사용하여 꼭짓점을 읽는 쿼리를 만듭니다.
const read_vertex_query: string = 'g.V([prop_partition_key, prop_id])';그런 다음 필요한 매개 변수를 제공하여 꼭짓점을 읽습니다.
let read_results = await client.submit(read_vertex_query, { prop_partition_key: 'gear-surf-surfboards', prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', }); let matched_item = read_results._items[0];
쿼리 데이터
마지막으로, 쿼리를 사용하여 그래프에서 특정 순회 또는 필터와 일치하는 모든 데이터를 찾습니다.
특정 꼭짓점에서 다른 꼭짓점으로 이동하는 모든 꼭짓점을 찾는 쿼리를 만듭니다.
const find_vertices_query = ` g.V().hasLabel('product') .has('category', prop_partition_key) .has('name', prop_name) .outE('replaces').inV() `;제품을 지정하는 쿼리를 실행합니다
Montau Turtle Surfboard.let find_results = await client.submit(find_vertices_query, { prop_partition_key: 'gear-surf-surfboards', prop_name: 'Montau Turtle Surfboard', });쿼리 결과를 반복합니다.
for (const item of find_results._items) { // Do something here with each result }
특정 꼭짓점에서 다른 꼭짓점으로 이동하는 모든 꼭짓점을 찾는 쿼리를 만듭니다.
const find_vertices_query: string = ` g.V().hasLabel('product') .has('category', prop_partition_key) .has('name', prop_name) .outE('replaces').inV() `;제품을 지정하는 쿼리를 실행합니다
Montau Turtle Surfboard.let find_results = await client.submit(find_vertices_query, { prop_partition_key: 'gear-surf-surfboards', prop_name: 'Montau Turtle Surfboard', });쿼리 결과를 반복합니다.
for (const item of find_results._items) { // Do something here with each result }
코드 실행
애플리케이션 디렉터리의 터미널을 사용하여 새로 만든 애플리케이션을 실행합니다.
node index.js
npx tsx index.ts
리소스 정리
계정이 더 이상 필요하지 않은 경우 리소스를 삭제하여 Azure 구독에서 계정을 제거합니다.
az cosmosdb delete \
--resource-group "<resource-group-name>" \
--name "<account-name>"