본 번역은 검증되지 않았습니다. AIP를 통해 영문원문으로부터 번역되었습니다.

유형 참조

레지스트리에 게시하려면 TypeScript 함수의 모든 입력 파라미터에 명시적 타입 어노테이션이 있어야 하며, 반환 타입도 명시적으로 지정해야 합니다. 아래는 현재 지원되는 함수 레지스트리 타입과 이에 대응하는 언어 타입의 전체 목록입니다.

Pipeline Builder에서 Python 함수를 사용자 정의 함수(UDF)로 사용하고 있습니까? 아래의 스칼라 타입(예: str 또는 int)은 UDF가 반환하는 값입니다. 함수가 행마다 한 번씩 실행되고 반환 값이 새 열이 되기 때문입니다. DataFrame을 반환하는 것이 아닙니다. 자세한 내용은 Pipeline Builder에서 Python 함수가 데이터를 처리하는 방식을 확인해 주세요.

Function 레지스트리 유형TypeScript v1 유형TypeScript v2 유형Python 유형
첨부 파일AttachmentAttachmentAttachment예제
불리언booleanbooleanbool예제
바이너리지원되지 않음지원되지 않음bytes예제
바이트지원되지 않음지원되지 않음int*예제
분류 마킹ClassificationMarkingClassificationMarkingClassificationMarking예제
날짜LocalDateDateISOStringdatetime.date예제
Decimal지원되지 않음지원되지 않음decimal.Decimal예제
DoubleDoubleDoublefloat*예제
FloatFloatFloatfloat예제
GeoPointGeoPointPointGeoPoint예제
GeoShapeGeoShapeGeometryGeoShape예제
그룹GroupGroupIdGroupId예제
정수IntegerIntegerint예제
인터페이스지원되지 않음Osdk.Instance<MyInterface>지원되지 않음예제
인터페이스 오브젝트셋지원되지 않음ObjectSet<MyInterface>지원되지 않음예제
리스트T[] 또는 Array<T>T[] 또는 Array<T>list[T]예제
LongLongLongint*예제
필수 마킹MandatoryMarkingMandatoryMarkingMandatoryMarking예제
맵FunctionsMap<K, V>Record<K, V>dict[K, V]예제
미디어 참조MediaItemMediaMedia예제
알림NotificationNotificationNotification예제
오브젝트MyObjectTypeOsdk.Instance<MyObjectType>MyObjectType예제
오브젝트셋ObjectSet<MyObjectType>ObjectSet<MyObjectType>MyObjectTypeObjectSet예제
온톨로지 편집voidEditsOntologyEdit예제
선택적T | undefinedT | undefinedtyping.Optional 또는 T | None예제
보안 주체PrincipalPrincipalPrincipal예제
범위IRange<T>Range<T>Range[T]예제
집합Set<T>지원되지 않음set[T]예제
Short지원되지 않음지원되지 않음int*예제
스트링stringstringstr예제
구조체/사용자 정의 유형interfaceinterfacedataclasses.dataclass예제
타임스탬프TimestampTimestampISOStringdatetime.datetime예제
2차원 집계TwoDimensionalAggregation<K, V>TwoDimensionalAggregation<K, V>TwoDimensionalAggregation[K, V]예제
3차원 집계ThreeDimensionalAggregation<K, S, V>ThreeDimensionalAggregation<K, S, V>ThreeDimensionalAggregation[K, S, V]예제
사용자UserUserIdUserId예제

Integer와 Long은 모두 Python 타입 int에 대응하지만, 함수 시그니처에서 직접 int로 표시한 필드는 Integer 타입으로 등록됩니다. 따라서 숫자 데이터 타입을 등록할 때는 API의 Integer 또는 Long 타입을 사용하는 것이 좋습니다. Float와 Double에도 유사한 지침이 적용됩니다. 함수 시그니처에 Python 타입 float를 직접 사용하면 기본적으로 Float로 등록됩니다.

스칼라 타입

스칼라 타입은 단일 값을 나타내며 일반적으로 텍스트, 숫자 또는 시간 데이터를 저장하는 데 사용됩니다.

JavaScript와 TypeScript에는 정수와 부동 소수점 값을 모두 나타내는 데 일반적으로 사용되는 단일 number 타입이 있습니다. 추가적인 타입 검증과 구조를 제공하기 위해 TypeScript v1 함수에서는 @foundry/functions-api 패키지에서 내보내는 숫자 타입 별칭만 지원하며, TypeScript v2 함수에서는 @osdk/functions 패키지에서 내보내는 숫자 타입 별칭만 지원합니다. 마찬가지로 Python 함수에서 숫자 타입을 사용할 때는 functions.api 모듈에서 내보내는 타입 별칭을 사용하는 것이 좋습니다.

Boolean

Copied!
1 2 3 4 5 6 7 8 import { Function, Integer } from "@foundry/functions-api"; export class MyFunctions { @Function() public isEven(num: Integer): boolean { return num % 2 === 0; } }
Copied!
1 2 3 4 5 6 7 import { Integer } from "@osdk/functions"; function isEven(num: Integer): boolean { return num % 2 === 0; } export default isEven;
Copied!
1 2 3 4 5 from functions.api import function, Integer @function def is_even(num: Integer) -> bool: return n % 2 == 0

스트링

Copied!
1 2 3 4 5 6 7 8 import { Function } from "@foundry/functions-api"; export class MyFunctions { @Function() public greet(name: string): string { return `Hello, ${name}!`; } }
Copied!
1 2 3 4 5 function greet(name: string): string { return `Hello, ${name}!`; } export default greet;
Copied!
1 2 3 4 5 from functions.api import function @function def greet(name: str) -> str: return f"Hello, {name}!"

Short

-32,768부터 32,767까지의 정수 값을 나타냅니다.

Python 함수에서 Short 타입은 내장 int 타입의 별칭입니다.

Copied!
1 2 3 4 5 from functions.api import function, Short @function def increment(num: Short) -> Short: return num + 1

Integer

(-231)부터 (231 - 1)까지의 정수 값을 나타냅니다.

  • TypeScript v1 및 v2 함수 모두에서 Integer 타입은 내장 number 타입의 별칭입니다.
  • Python 함수에서 Integer 타입은 내장 int 타입의 별칭입니다.
Copied!
1 2 3 4 5 6 7 8 import { Function, Integer } from "@foundry/functions-api"; export class MyFunctions { @Function() public sum(a: Integer, b: Integer): Integer { return a + b; } }
Copied!
1 2 3 4 5 6 7 import { Integer } from "@osdk/functions"; function sum(a: Integer, b: Integer): Integer { return a + b; } export default sum;
Copied!
1 2 3 4 5 from functions.api import function, Integer @function def sum(a: Integer, b: Integer) -> Integer: return a + b

Long

-(253 - 1)부터 (253 - 1)까지의 정수 값을 나타냅니다. 이 경계값은 JavaScript의 Number.MIN_SAFE_INTEGER 및 Number.MAX_SAFE_INTEGER와 같으며, 브라우저 컨텍스트에서 함수를 호출할 때 정밀도 손실을 방지하기 위한 것입니다.

  • TypeScript v1 함수에서 Long 타입은 내장 number 타입의 별칭입니다. TypeScript v2 함수에서 Long 타입은 내장 string 타입의 별칭입니다.
  • Python 함수에서 Long 타입은 내장 int 타입의 별칭입니다.
Copied!
1 2 3 4 5 6 7 8 import { Function, Long } from "@foundry/functions-api"; export class MyFunctions { @Function() public subtract(a: Long, b: Long): string { return (BigInt(a) - BigInt(b)).toString(); } }
Copied!
1 2 3 4 5 6 7 import { Long } from "@osdk/functions"; function subtract(a: Long, b: Long): string { return (BigInt(a) - BigInt(b)).toString(); } export default subtract;
Copied!
1 2 3 4 5 from functions.api import function, Long @function def subtract(a: Long, b: Long) -> str: return str(a - b)

Float

32비트 부동 소수점 숫자를 나타냅니다.

  • TypeScript v1 및 v2 함수 모두에서 Float 타입은 내장 number 타입의 별칭입니다.
  • Python 함수에서 Float 타입은 내장 float 타입의 별칭입니다.
Copied!
1 2 3 4 5 6 7 8 import { Float, Function } from "@foundry/functions-api"; export class MyFunctions { @Function() public multiply(a: Float, b: Float): Float { return a * b; } }
Copied!
1 2 3 4 5 6 7 import { Float } from "@osdk/functions"; function multiply(a: Float, b: Float): Float { return a * b; } export default multiply;
Copied!
1 2 3 4 5 from functions.api import function, Float @function def multiply(a: Float, b: Float) -> Float: return a * b

Double

64비트 부동 소수점 숫자를 나타냅니다.

  • TypeScript v1 및 v2 함수 모두에서 Double 타입은 내장 number 타입의 별칭입니다.
  • Python 함수에서 Double 타입은 내장 float 타입의 별칭입니다.
Copied!
1 2 3 4 5 6 7 8 import { Double, Function } from "@foundry/functions-api"; export class MyFunctions { @Function() public divide(a: Double, b: Double): Double { return a / b; } }
Copied!
1 2 3 4 5 6 7 import { Double } from "@osdk/functions"; function divide(a: Double, b: Double): Double { return a / b; } export default divide;
Copied!
1 2 3 4 5 from functions.api import function, Double @function def divide(a: Double, b: Double) -> Double: return a / b

Decimal

Copied!
1 2 3 4 5 6 from decimal import Decimal from functions.api import function @function def return_pi() -> Decimal: return Decimal('3.1415926535')

날짜

달력상의 날짜를 나타냅니다.

Copied!
1 2 3 4 5 6 7 8 import { Function, LocalDate } from "@foundry/functions-api"; export class MyFunctions { @Function() public returnDate(): LocalDate { return LocalDate.fromISOString("1999-10-17"); } }
Copied!
1 2 3 4 5 6 7 import { DateISOString } from "@osdk/functions"; function returnDate(): DateISOString { return "1999-10-17"; } export default returnDate;
Copied!
1 2 3 4 5 6 from datetime import date from functions.api import function, Date @function def return_date() -> Date: return date.fromisoformat('1999-10-17')

타임스탬프

특정 시점을 나타냅니다.

Copied!
1 2 3 4 5 6 7 8 import { Function, Timestamp } from "@foundry/functions-api"; export class MyFunctions { @Function() public getCurrentTimestamp(): Timestamp { return Timestamp.now(); } }
Copied!
1 2 3 4 5 6 7 8 import { TimestampISOString } from "@osdk/functions"; function getCurrentTimestamp(): TimestampISOString { const now = new Date(); return now.toISOString(); } export default getCurrentTimestamp;
Copied!
1 2 3 4 5 6 from datetime import datetime from functions.api import function, Timestamp @function def get_current_timestamp() -> Timestamp: return datetime.now()

Binary

Python 함수에서 Binary 타입은 내장 bytes 타입의 별칭입니다.

Copied!
1 2 3 4 5 from functions.api import function @function def encode_utf8(param: str) -> bytes: return param.encode('utf-8')

Byte

Python 함수에서 Byte 타입은 내장 int 타입의 별칭입니다.

Copied!
1 2 3 4 5 6 7 from functions.api import function, Byte @function def get_first_byte(param: str) -> Byte: if len(param) == 0: raise Exception("String length cannot be zero.") return param.encode('utf-8')[0]

필수 마킹

마킹은 데이터에 액세스하려면 사용자에게 특정 마킹이 있어야 하도록 요구하여 액세스를 제한하는 필수 제어 수단입니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 import { OntologyEditFunction, MandatoryMarking } from "@foundry/functions-api"; import { Employee, Objects } from "@foundry/ontology-api"; export class MyFunctions { @Edits(Employee) @OntologyEditFunction() public async editMandatoryMarkings(markings: MandatoryMarking[]): Promise<void> { const employeeOne = Objects.search().employee().filter(e => e.id.exactMatch(1)).all()[0]; employeeOne.markingsProperty = markings; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { Client } from "@osdk/client"; import { Employee } from "@ontology/sdk"; import { Edits, createEditBatch, MandatoryMarking } from "@osdk/functions"; type OntologyEdit = Edits.Object<Employee>; function editMandatoryMarkings(markings: MandatoryMarking[]): OntologyEdit[] { const batch = createEditBatch<OntologyEdit>(client); const employeeOne = await client(Employee).fetchOne(1); batch.update(employeeOne, { markingsProperty: markings }); return batch.getEdits(); } export default editMandatoryMarkings;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from foundry_sdk_runtime import Marking from functions.api import function, MandatoryMarking, OntologyEdit from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import Employee @function def edit_mandatory_markings(markings: list[MandatoryMarking]) -> list[OntologyEdit]: ontology_edits = FoundryClient().ontology.edits() employee: Optional[Employee] = client.ontology.objects.Employee.get("primary_key") if employee is None: return [] editable_employee = ontology_edits.objects.Employee.edit(employee) editable_employee.markings_property = [Marking(m) for m in markings] # "list[MandatoryMarking]" 유형을 할당해도 작동하지만, LSP 경고가 발생합니다: # editable_employee.markings_property = markings return ontology_edits.get_edits()

분류 마킹

분류 기반 액세스 제어(CBAC)는 민감한 정부 정보를 보호하는 데 사용되는 필수 제어 수단입니다. 정보에 액세스하려면 사용자에게 특정 분류 마킹이 있어야 하도록 요구하여 액세스를 제한합니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 import { OntologyEditFunction, ClassificationMarking } from "@foundry/functions-api"; import { Employee, Objects } from "@foundry/ontology-api"; export class MyFunctions { @Edits(Employee) @OntologyEditFunction() public async editClassificationMarkings(markings: ClassificationMarking[]): Promise<void> { const employeeOne = Objects.search().employee().filter(e => e.id.exactMatch(1)).all()[0]; employeeOne.markingsProperty = markings; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { Client } from "@osdk/client"; import { Employee } from "@ontology/sdk"; import { Edits, createEditBatch, ClassificationMarking } from "@osdk/functions"; type OntologyEdit = Edits.Object<Employee>; function editClassificationMarkings(markings: ClassificationMarking[]): OntologyEdit[] { const batch = createEditBatch<OntologyEdit>(client); const employeeOne = await client(Employee).fetchOne(1); batch.update(employeeOne, { markingsProperty: markings }); return batch.getEdits(); } export default editClassificationMarkings;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from foundry_sdk_runtime import Marking from functions.api import ClassificationMarking, function, OntologyEdit from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import Employee @function def edit_classification_markings(markings: list[ClassificationMarking]) -> list[OntologyEdit]: ontology_edits = FoundryClient().ontology.edits() employee: Optional[Employee] = client.ontology.objects.Employee.get("primary_key") if employee is None: return [] editable_employee = ontology_edits.objects.Employee.edit(employee) editable_employee.markings_property = [Marking(m) for m in markings] # "list[ClassificationMarking]" 유형을 할당해도 작동하지만, LSP 경고가 발생합니다: # editable_employee.markings_property = markings return ontology_edits.get_edits()

컬렉션 타입

컬렉션 타입은 다른 타입을 파라미터로 받습니다. 예를 들어 Array[String]은 스트링 목록이고 Map[String, Integer]는 스트링 키와 정수 값을 가진 딕셔너리입니다. 파라미터로 사용할 타입을 지정해야 하며, 해당 타입은 지원되는 다른 타입이어야 합니다. Map 키는 스칼라 타입 또는 온톨로지 오브젝트 유형만 사용할 수 있습니다.

List

Copied!
1 2 3 4 5 6 7 8 import { Function, Integer } from "@foundry/functions-api"; export class MyFunctions { @Function() public filterForEvenIntegers(nums: Integer[]): Integer[] { return nums.filter(num => num % 2 === 0); } }
Copied!
1 2 3 4 5 6 7 import { Integer } from "@osdk/functions"; function filterForEvenIntegers(nums: Integer[]): Integer[] { return nums.filter(num => num % 2 === 0); } export default filterForEvenIntegers;
Copied!
1 2 3 4 5 from functions.api import function, Integer @function def filter_for_even_integers(nums: list[Integer]) -> list[Integer]: return [n for n in nums if n % 2 == 0]

Map

맵은 일반적으로 스칼라 타입을 키로 사용하고, 다른 함수 레지스트리 타입 중 어떤 타입이든 될 수 있는 관련 값에 액세스하는 데 사용됩니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 import { Function, FunctionsMap } from "@foundry/functions-api"; export class MyFunctions { @Function() public getMap(): FunctionsMap<string, string> { const myMap = new FunctionsMap<string, string>(); myMap.set("Name", "Phil"); myMap.set("Favorite Color", "Blue"); return myMap; } }
Copied!
1 2 3 4 5 6 7 8 9 10 function getMap(): Record<string, string> { const myMap: Record<string, string> = {}; myMap["Name"] = "Phil"; myMap["Favorite Color"] = "Blue"; return myMap; } export default getMap;
Copied!
1 2 3 4 5 6 7 8 9 10 from functions.api import function @function def get_map() -> dict[str, str]: my_map = {} my_map["Name"] = "Phil" my_map["Favorite Color"] = "Blue" return my_map

또한 맵은 온톨로지 오브젝트를 키로 지원합니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { Function, FunctionsMap } from "@foundry/functions-api"; import { Airplane } from "@foundry/ontology-api"; export class MyFunctions { @Function() public getObjectMap(aircraft: Airplane[]): FunctionsMap<Airplane, Integer | undefined> { const myMap = new FunctionsMap<Airplane, Integer | undefined>(); aircraft.forEach(obj => { myMap.set(obj, obj.capacity); }); return myMap; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { ObjectSpecifier, Osdk } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Airplane } from "@ontology/sdk"; function getObjectMap(aircraft: Osdk.Instance<Airplane>[]): Record<ObjectSpecifier<Airplane>, Integer | undefined> { const myMap: Record<ObjectSpecifier<Airplane>, Integer | undefined> = {}; aircraft.forEach(obj => { myMap[obj.$objectSpecifier] = obj.capacity; }); return myMap; } export default getObjectMap;
Copied!
1 2 3 4 5 6 7 8 9 10 11 from functions.api import function, Integer from ontology_sdk.ontology.objects import Airplane @function def get_object_map(aircraft: list[Airplane]) -> dict[Airplane, Integer | None]: my_map = {} for a in aircraft: my_map[a] = a.capacity return my_map

Set

Copied!
1 2 3 4 5 6 7 8 import { Function, Integer } from "@foundry/functions-api"; export class MyFunctions { @Function() public getSizeOfSet(mySet: Set<Integer>): Integer { return mySet.size; } }
Copied!
1 2 3 4 5 from functions.api import function, Integer @function def get_size_of_set(my_set: set[Integer]) -> Integer: return len(my_set)

Optional

  • TypeScript 함수에서 선택적 파라미터는 varName?: T 또는 varName: T | undefined로 선언합니다. 예를 들어 이름이 value인 선택적 정수 파라미터를 가진 함수는 value?: Integer 또는 value: Integer | undefined로 선언할 수 있습니다. TypeScript 함수는 타입을 T | undefined로 지정하여 선택적 반환 타입을 선언할 수도 있습니다. 예를 들어 Integer를 반환하거나 아무 값도 반환하지 않을 수 있는 함수의 반환 타입은 Integer | undefined입니다.
  • Python 함수에서 선택적 파라미터와 반환 값은 typing.Optional[T] 또는 T | None을 사용하여 선언할 수 있습니다. T | None 구문은 Python 3.10 이상이 필요합니다.
  • TypeScript 및 Python 함수 모두에서 파라미터화된 타입 T를 지정해야 하며, 해당 타입은 지원되는 다른 타입이어야 합니다.
Copied!
1 2 3 4 5 6 7 8 9 10 11 import { Function } from "@foundry/functions-api"; export class MyFunction { @Function() public greet(name?: string): string | undefined { if (name === undefined) { return undefined; } return `Hello, ${name}!`; } }
Copied!
1 2 3 4 5 6 7 8 function greet(name?: string): string | undefined { if (name === undefined) { return undefined; } return `Hello, ${name}!`; } export default greet;
Copied!
1 2 3 4 5 6 7 from functions.api import function @function def greet(name: str | None) -> str | None: if name is None: return None return f"Hello, {name}!"

함수는 함수 시그니처의 기본값도 지원합니다.

Copied!
1 2 3 4 5 6 7 8 9 import { Double, Function } from "@foundry/functions-api"; import { Customer } from "@foundry/ontology-api"; export class MyFunctions { @Function() public computeRiskFactor(customer: Customer, weight: Double = 0.75): Double { // ... } }
Copied!
1 2 3 4 5 6 7 8 9 import { Double } from "@osdk/functions"; import { Osdk } from "@osdk/client"; import { Customer } from "@ontology/sdk"; function computeRiskFactor(customer: Osdk.Instance<Customer>, weight: Double = 0.75): Double { // ... } export default computeRiskFactor;
Copied!
1 2 3 4 5 6 from functions.api import function, Double from ontology_sdk.ontology.objects import Customer @function def compute_risk_factor(customer: Customer, weight: Double = 0.75) -> Double: # ...

구조체/사용자 정의 타입

사용자 정의 타입은 지원되는 다른 타입(다른 사용자 정의 타입 포함)으로 구성되며 함수 시그니처에서 사용할 수 있습니다.

함수 시그니처에 사용되는 사용자 정의 타입은 온톨로지 구조체 속성에 사용되는 생성된 클래스와 다릅니다. Python 함수에서 온톨로지 구조체 속성을 편집하려면 구조체 속성 편집에 설명된 대로 생성된 구조체 속성 클래스를 사용하세요.

  • TypeScript 함수에서 사용자 정의 타입은 interface 키워드를 사용하는 사용자 정의 TypeScript 인터페이스입니다.

    • 선택적 필드는 ? 선택적 토큰 또는 undefined와의 유니온을 통해 지원됩니다.
  • Python 함수에서 사용자 정의 타입은 사용자 정의 Python 클래스입니다.

    • 유효한 사용자 정의 타입이 되려면 클래스가 다음 조건을 충족해야 합니다.
      • 클래스의 모든 필드에 타입 어노테이션이 있어야 합니다.
      • 필드 타입은 지원되는 타입이어야 합니다. 기본 API 타입 또는 네이티브 Python 타입(위 표에 정의된 타입)을 사용할 수 있습니다.
      • __init__ 메서드는 필드와 이름 및 타입 어노테이션이 동일한 명명된 인수만 받아야 합니다.
    • dataclasses.dataclass ↗ 데코레이터를 사용하면 이러한 요구 사항을 충족하는 __init__ 메서드를 자동으로 생성할 수 있습니다.
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import { Function, Integer } from "@foundry/functions-api"; import { Passenger } from "@foundry/ontology-api"; interface PassengerInfo { name?: string; age?: Integer; } export class MyFunctions { @Function() public getPassengerInfo(passenger: Passenger): PassengerInfo { return { name: passenger.name, age: passenger.age, }; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import { Osdk } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Passenger } from "@ontology/sdk"; interface PassengerInfo { name?: string; age?: Integer; } function getPassengerInfo(passenger: Osdk.Instance<Passenger>): PassengerInfo { return { name: passenger.name, age: passenger.age, }; } export default getPassengerInfo;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from dataclasses import dataclass from functions.api import function, Integer from ontology_sdk.ontology.objects import Passenger @dataclass class PassengerInfo: name: str | None age: Integer | None @function def get_passenger_info(passenger) -> PassengerInfo: return PassengerInfo( name=passenger.name, age=passenger.age )

집계 유형

집계 유형은 함수에서 반환되어 Workshop의 차트와 같은 플랫폼의 다른 부분에서 사용할 수 있습니다.

지원되는 집계 유형은 두 가지입니다.

  • 2차원 집계는 단일 버킷 키를 숫자 값에 매핑합니다. 예를 들어, 특정 직책을 가진 직원 수와 같은 집계를 나타내는 데 사용할 수 있습니다.
  • 3차원 집계는 두 개의 버킷 키를 숫자 값에 매핑합니다. 각 직원의 직책 및 소속 사무실별 직원 수와 같은 집계를 나타내는 데 사용할 수 있습니다.

집계의 키로는 여러 유형을 사용할 수 있습니다.

  • 불리언 버킷은 true 또는 false 값을 나타냅니다.
  • 스트링 버킷은 범주형 값을 나타내는 데 사용할 수 있습니다.
  • 범위 버킷은 버킷 키가 값의 범위인 집계를 나타냅니다. 차트의 히스토그램이나 날짜 축을 나타내는 데 사용할 수 있습니다.
    • 정수 및 더블을 포함하는 숫자 범위는 숫자 값을 버킷으로 나눈 집계를 나타냅니다.
    • 날짜 및 타임스탬프에 대한 범위를 포함하는 날짜 및 시간 범위는 날짜 범위를 버킷으로 나눈 집계를 나타냅니다.

범위

필드 이름은 버젼에 따라 다릅니다. TSv1의 IRange<T>와 Python의 Range[T]는 min과 max를 사용합니다. TSv2의 Range<T>는 startValue와 endValue를 사용하며, 한쪽 경계가 없는 범위에서는 둘 중 하나를 생략할 수 있습니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 import { Function, Integer, IRange } from "@foundry/functions-api"; export class MyFunctions { @Function() public getRange(min: Integer, max: Integer): IRange<Integer> { return { min, max, }; } }
Copied!
1 2 3 4 5 6 7 8 9 10 import { Integer, Range } from "@osdk/functions"; function getRange(min: Integer, max: Integer): Range<Integer> { return { startValue: min, endValue: max, }; } export default getRange;
Copied!
1 2 3 4 5 6 7 8 from functions.api import function, Integer, Range @function def get_range(min: Integer, max: Integer) -> Range[Integer]: return Range( min=min, max=max )

2차원 집계

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 import { Double, Function, TwoDimensionalAggregation } from "@foundry/functions-api"; export class MyFunctions { @Function() public myTwoDimensionalAggregation(): TwoDimensionalAggregation<string, Double> { return { buckets: [ { key: "bucket1", value: 5.0 }, { key: "bucket2", value: 6.0 }, ], }; } }
Copied!
1 2 3 4 5 6 7 8 9 10 import { Double, TwoDimensionalAggregation } from "@osdk/functions"; function myTwoDimensionalAggregationFunction(): TwoDimensionalAggregation<string, Double> { return [ { key: "bucket1", value: 5.0 }, { key: "bucket2", value: 6.0 }, ]; } export default myTwoDimensionalAggregationFunction;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from functions.api import ( function, Double, TwoDimensionalAggregation, SingleBucket ) @function def my_two_dimensional_aggregation_function() -> TwoDimensionalAggregation[str, Double]: return TwoDimensionalAggregation( buckets=[ SingleBucket(key="bucket1", value=Double(5.0)), SingleBucket(key="bucket2", value=Double(6.0)), ] )

3차원 집계

버킷 구조는 버젼에 따라 다릅니다. TSv1은 외부 버킷을 buckets 키 아래에 래핑하고 내부 수준의 키로 value를 사용합니다. TSv2는 내부 수준이 groups 아래에 있는 배열을 래핑 없이 반환하므로, ThreeDimensionalAggregation<T, U, V>는 { key: T; groups: { key: U; value: V }[] }[]로 해석됩니다. Python은 TSv1과 마찬가지로 외부 버킷을 래핑하며, NestedBucket 및 SingleBucket 클래스로 버킷을 구성합니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import { Double, Function, ThreeDimensionalAggregation } from "@foundry/functions-api"; export class MyFunctions { @Function() public myThreeDimensionalAggregation(): ThreeDimensionalAggregation<string, string, Double> { return { buckets: [ { key: "group-by-1", value: [ { key: "partition-by-1", value: 5.0 }, { key: "partition-by-2", value: 6.0 }, ], }, { key: "group-by-2", value: [ { key: "partition-by-1", value: 7.0 }, { key: "partition-by-2", value: 8.0 }, ], }, ] }; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import { Double, ThreeDimensionalAggregation } from "@osdk/functions"; function myThreeDimensionalAggregation(): ThreeDimensionalAggregation<string, string, Double> { return [ { key: "group-by-1", groups: [ { key: "partition-by-1", value: 5.0 }, { key: "partition-by-2", value: 6.0 }, ], }, { key: "group-by-2", groups: [ { key: "partition-by-1", value: 7.0 }, { key: "partition-by-2", value: 8.0 }, ], }, ]; } export default myThreeDimensionalAggregation;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from functions.api import ( function, Double, ThreeDimensionalAggregation, SingleBucket, NestedBucket, ) @function def my_three_dimensional_aggregation_function() -> ( ThreeDimensionalAggregation[str, str, Double] ): return ThreeDimensionalAggregation( buckets=[ NestedBucket(key="group-by-1", buckets=[ SingleBucket(key="partition-by-1", value=Double(5.0)), SingleBucket(key="partition-by-2", value=Double(6.0)), ]), NestedBucket(key="group-by-2", buckets=[ SingleBucket(key="partition-by-1", value=Double(7.0)), SingleBucket(key="partition-by-2", value=Double(8.0)), ]) ] )

온톨로지 유형

오브젝트 유형을 함수 시그니처에서 사용하려면 리포지토리로 가져와야 합니다. 온톨로지 가져오기에 대해 더 알아보세요.

오브젝트

온톨로지의 오브젝트 유형은 함수 시그니처에서 입력과 결과물로 모두 사용할 수 있습니다. 오브젝트 유형의 단일 인스턴스를 받거나 반환하려면 온톨로지 SDK에서 오브젝트 유형을 가져와 해당 유형으로 함수에 타입을 지정하세요.

Copied!
1 2 3 4 5 6 7 8 9 import { Function, Integer } from "@foundry/functions-api"; import { Airplane } from "@foundry/ontology-api"; export class MyFunctions { @Function() public getCapacity(airplane: Airplane): Integer { return airplane.capacity; } }
Copied!
1 2 3 4 5 6 7 8 9 import { Osdk } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Airplane } from "@ontology/sdk"; function getCapacity(airplane: Osdk.Instance<Airplane>): Integer { return airplane.capacity; } export default getCapacity;
Copied!
1 2 3 4 5 6 from functions.api import function, Integer from ontology_sdk.ontology.objects import Airplane @function def get_capacity(airplane: Airplane) -> Integer: return airplane.capacity

TypeScript v2에서는 오브젝트 유형에 대한 참조를 구조체 파라미터 필드로 사용할 수 있습니다. 오브젝트 유형 인스턴스가 포함된 구조체 또는 구조체 목록을 받으려면 온톨로지 SDK의 오브젝트 유형 필드가 있는 사용자 지정 유형 입력을 생성하세요. 이를 온톨로지 편집과 함께 사용하면 다른 오브젝트 유형에서 파생된 오브젝트 유형의 인스턴스를 여러 개 생성하는 등의 워크플로를 지원할 수 있습니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import { Osdk } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Airplane, Passenger, Ticket } from "@ontology/sdk"; type TicketEdit = Edits.Object<Ticket> interface TicketInfo { airplane?: Osdk.Instance<Airplane>; passenger?: Osdk.Instance<Passenger>; seat?: String; } function createTickets(ticketInfo: TicketInfo[]): TicketEdit[] { const batch = createEditBatch<TicketEdit>(client); ticketInfo.forEach(i => batch.create(TicketEdit, { flightNumber: i.airplane.flightNumber, passengerName: i.passenger.name, seat: i.seat})) return batch.getEdits(); } export default createTickets;

오브젝트 파라미터에 대해 로드되는 속성

함수에서 오브젝트 유형을 파라미터로 선언하면 플랫폼은 함수를 실행하기 전에 오브젝트를 로드합니다. 다음 버전에서는 온톨로지 정의 파생 속성을 포함한 모든 속성과 함께 오브젝트를 로드합니다.

  • TypeScript v2: TypeScript 함수 런타임(@foundry/functions-typescript-runtime) 0.367.0 이상.
  • Python: Python OSDK 생성기(foundry-sdk-generator) 2.246.0 이상으로 생성된 온톨로지 SDK.

이전 버전에서는 온톨로지 정의 파생 속성 없이 오브젝트를 로드하므로 해당 속성을 읽으면 값이 반환되지 않습니다. 오브젝트 파라미터에서 온톨로지 정의 파생 속성을 읽으려면 위에 나열된 버전으로 업그레이드하세요. 코드를 변경할 필요는 없습니다.

TypeScript v1 함수는 오브젝트를 파라미터로 전달하든 함수 내부에서 로드하든 온톨로지 정의 파생 속성을 로드하지 않습니다. 온톨로지 정의 파생 속성을 읽으려면 TypeScript v2 또는 Python 함수를 사용하세요.

온톨로지 정의 파생 속성은 쿼리 시점에 계산되므로 이를 로드하면 각 함수 호출의 지연 시간과 컴퓨팅 비용이 증가할 수 있습니다. 함수에서 일부 속성만 읽는 경우 기본 키를 파라미터로 받고, 함수 내부에서 속성을 명시적으로 선택하여 오브젝트를 로드하세요. 다음 예제에서 passengerCount(Python에서는 passenger_count)는 온톨로지 정의 파생 속성입니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 import { Client } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Airplane } from "@ontology/sdk"; async function getPassengerCount(client: Client, airplaneId: string): Promise<Integer> { const airplane = await client(Airplane).fetchOne(airplaneId, { $select: ["passengerCount"], }); return airplane.passengerCount; } export default getPassengerCount;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 from functions.api import function, Integer from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import Airplane @function def get_passenger_count(airplane_id: str) -> Integer: client = FoundryClient() airplane = client.ontology.objects.Airplane.get( airplane_id, properties=[Airplane.object_type.passenger_count], ) return airplane.passenger_count

함수 내부에서 로드하는 오브젝트에는 다른 온톨로지 SDK 요청과 동일한 선택 규칙이 적용됩니다. TypeScript OSDK 및 Python OSDK의 선택 규칙을 확인하세요.

오브젝트셋

오브젝트 컬렉션을 함수의 입력과 결과물로 전달하는 방법에는 배열과 같은 구체적인 오브젝트 컬렉션 또는 오브젝트셋을 사용하는 두 가지 방법이 있습니다.

오브젝트 배열을 함수에 전달하면 구체적인 오브젝트 목록에 대해 로직을 실행할 수 있지만, 오브젝트를 함수 실행 환경에 미리 로드해야 합니다. 반면 오브젝트셋을 사용하면 필터링, 주변 검색 및 집계 작업을 수행하고 요청할 때만 최종 결과를 로드할 수 있습니다.

오브젝트셋은 대체로 성능이 더 우수하고 10,000개가 넘는 오브젝트를 함수에 전달할 수 있으므로 배열 대신 오브젝트셋을 사용하는 것이 좋습니다.

아래 예제에서는 오브젝트를 메모리에 로드하지 않고 오브젝트셋을 필터링하여 필터링된 오브젝트셋을 애플리케이션의 다른 부분에 반환하는 방법을 보여줍니다.

Copied!
1 2 3 4 5 6 7 8 9 import { Function } from "@foundry/functions-api"; import { Airplane, ObjectSet } from "@foundry/ontology-api"; export class MyFunctions { @Function() public filterAircraft(aircraft: ObjectSet<Airplane>): ObjectSet<Airplane> { return aircraft.filter(a => a.capacity.range().gt(200)); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 import { ObjectSet } from "@osdk/client"; import { Airplane } from "@ontology/sdk"; function filterAircraft(aircraft: ObjectSet<Airplane>): ObjectSet<Airplane> { return aircraft .where({ capacity: { $gt: 200, } }); } export default filterAircraft;
Copied!
1 2 3 4 5 6 7 from functions.api import function from ontology_sdk.ontology.objects import Airplane from ontology_sdk.ontology.object_sets import AirplaneObjectSet @function def filter_aircraft(aircraft: AirplaneObjectSet) -> AirplaneObjectSet: return aircraft.where(Airplane.object_type.capacity > 200)

인터페이스

온톨로지의 인터페이스 유형은 TypeScript v2 함수 시그니처에서 입력과 결과물로 모두 사용할 수 있습니다. TypeScript v1 또는 Python에서는 지원되지 않습니다.

Copied!
1 2 3 4 5 6 7 8 9 import { Osdk } from "@osdk/client"; import { Integer } from "@osdk/functions"; import { Person } from "@ontology/sdk"; function getAge(person: Osdk.Instance<Person>): Integer { return person.age; } export default getAge;

인터페이스 오브젝트셋

인터페이스 오브젝트셋은 TypeScript v2 함수 시그니처에서 입력과 결과물로 모두 사용할 수 있습니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 import { ObjectSet } from "@osdk/client"; import { Person } from "@ontology/sdk"; function filterPeople(people: ObjectSet<Person>): ObjectSet<Person> { return people .where({ age: { $gt: 200, } }); } export default filterPeople;

온톨로지 편집

온톨로지에서 데이터를 읽는 함수뿐만 아니라 오브젝트를 생성하고 오브젝트의 속성 및 오브젝트 간 링크를 편집하는 함수도 작성할 수 있습니다. 편집 함수의 작동 방식에 대한 자세한 내용은 전체보기 페이지를 참조하세요.

TypeScript v1 함수를 편집 함수로 등록하려면 시그니처에 void 반환 유형이 필요합니다. 반면 TypeScript v2 및 Python 함수는 온톨로지 편집 목록을 명시적으로 반환해야 합니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { Edits, OntologyEditFunction } from "@foundry/functions-api"; import { Employee, LaptopRequest, Objects } from "@foundry/ontology-api"; export class MyFunctions { @Edits(Employee, LaptopRequest) @OntologyEditFunction() public assignEmployee(newEmployee: Employee, leadEmployee: Employee): void { const newLaptopRequest = Objects.create().laptopRequest(Date.now().toString()); newLaptopRequest.employeeName = newEmployee.name; newEmployee.lead.set(leadEmployee); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import { Client } from "@osdk/client"; import { createEditBatch, Edits } from "@osdk/functions"; import { Employee, LaptopRequest } from "@ontology/sdk"; type EmployeeEdit = | Edits.Object<Employee> | Edits.Object<LaptopRequest> | Edits.Link<Employee, "lead">; function assignEmployee( client: Client, newEmployee: Osdk.Instance<Employee>, leadEmployee: Osdk.Instance<Employee> ): EmployeeEdit[] { const batch = createEditBatch<EmployeeEdit>(client); batch.create(LaptopRequest, { id: Date.now().toString(), employeeName: newEmployee.name, }); batch.link(newEmployee, "lead", leadEmployee); return batch.getEdits(); } export default assignEmployee;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from functions.api import function, OntologyEdit from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import Employee, LaptopRequest from time import time @function def assign_employee(new_employee: Employee, lead_employee: Employee) -> list[OntologyEdit]: ontology_edits = FoundryClient().ontology.edits() new_laptop_request = ontology_edits.objects.LaptopRequest.create(str(int(time() * 1000))) new_laptop_request.employee_name = new_employee.name new_employee.lead.set(lead_employee) return ontology_edits.get_edits()

첨부 파일

Copied!
1 2 3 4 5 6 7 8 import { Attachment, Function } from "@foundry/functions-api"; export class MyFunctions { @Function() public loadAttachmentContents(attachment: Attachment): Promise<string> { return attachment.readAsync().then(blob => blob.text()); } }
Copied!
1 2 3 4 5 6 7 import { Attachment } from "@osdk/functions"; function loadAttachmentContents(attachment: Attachment): Promise<string> { return attachment.fetchContents().then(response => response.text()); } export default loadAttachmentContents;
Copied!
1 2 3 4 5 from functions.api import function, Attachment @function def load_attachment_contents(attachment: Attachment) -> str: return attachment.read().getvalue().decode('utf-8')

알림

함수에서 알림 유형을 반환하여 플랫폼에서 전송할 알림을 유연하게 구성할 수 있습니다. 예를 들어 User 및 오브젝트 유형과 같은 파라미터를 받아 메시지가 구성된 알림을 반환하는 함수를 작성할 수 있습니다.

  • Notification은 ShortNotification과 EmailNotificationContent라는 두 필드로 구성됩니다.
  • ShortNotification은 Foundry 플랫폼 내에 표시되는 알림의 요약 버전을 나타냅니다. 짧은 heading, content 및 Link 컬렉션을 포함합니다.
  • EmailNotificationContent는 이메일을 통해 외부로 전송할 수 있는 풍부한 형식의 알림을 나타냅니다. subject, 헤드 없는 HTML로 구성된 body 및 Link 컬렉션을 포함합니다.
  • Link에는 사용자에게 표시되는 label과 linkTarget이 있습니다. LinkTarget은 URL, OntologyObject 또는 Foundry 내 리소스의 rid일 수 있습니다.

Notifications API 사용 예제는 가이드를 확인하세요.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import { EmailNotificationContent, Function, Notification, ShortNotification, } from "@foundry/functions-api"; export class MyFunctions { @Function() public buildNotification(): Notification { return Notification.builder() .shortNotification(ShortNotification.builder() .heading("Issue reminder") .content("Investigate this issue.") .build()) .emailNotificationContent(EmailNotificationContent.builder() .subject("New issue") .body("hello") .build()) .build(); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import { Notification } from "@osdk/functions"; export default function buildNotification(): Notification { return { platformNotification: { heading: "Issue reminder", content: "Investigate this issue.", links: [] }, emailNotification: { subject: "New issue", body: "hello", links: [] } }; }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from functions.api import function, Notification, PlatformNotification, EmailNotification @function() def buildNotification() -> Notification: return Notification( platform_notification=PlatformNotification( heading="Issue reminder", content="Investigate this issue.", links=[] ), email_notification=EmailNotification( subject="New issue", body="hello", links=[] ), )

미디어 유형

미디어

함수는 미디어 항목을 받고 반환할 수 있습니다. TypeScript v1에서는 MediaItem 유형을 사용하세요. TypeScript v2 및 Python에서는 입력과 결과물 유형 모두에 Media를 사용하세요. 호출자는 오브젝트의 미디어 속성과 같은 기존 MediaReference를 함수에 전달할 수 있습니다. 다운스트림 소비자는 반환된 값을 사용하여 콘텐츠나 메타데이터를 가져오거나 다른 오브젝트에 첨부할 수 있습니다. 자세한 내용은 미디어 가이드를 확인하세요.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import { Function, MediaItem } from "@foundry/functions-api"; export class MyFunctions { @Function() public async echoMedia(media: MediaItem): Promise<string | undefined> { const mimeType: string = media.mimeType; // 유형별 메타데이터(페이지 수, 크기, 재생 시간 등)를 가져옵니다 const metadata = await media.getMetadataAsync(); // 바이너리 콘텐츠를 Blob으로 읽습니다 const contents: Blob = await media.readAsync(); // 유형별 메서드를 호출하기 위해 구체적인 세부 유형으로 좁힙니다 if (MediaItem.isDocument(media)) { const text = await media.extractTextAsync({ startPage: 0, endPage: 1 }); } else if (MediaItem.isAudio(media)) { const transcript = await media.transcribeAsync(); } return undefined; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 import type { Media } from "@osdk/client"; export default async function echoMedia(media: Media): Promise<Media> { // 기반 MediaReference를 가져옵니다 const mediaReference = media.getMediaReference(); // 간략한 메타데이터를 가져옵니다: path, sizeBytes, mediaType const metadata = await media.fetchMetadata(); // 콘텐츠를 Response로 가져옵니다. 바이트를 얻으려면 .blob() 또는 .arrayBuffer()를 호출합니다 const response = await media.fetchContents(); const contents = await response.blob(); return media; }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from foundry_sdk.v2.core.models import MediaReference from functions.api import function, Media @function def echo_media(media: Media) -> Media: # 기반 MediaReference를 가져옵니다 media_reference: MediaReference = media.get_media_reference() # 간략한 메타데이터를 가져옵니다: path, size_bytes, media_type metadata = media.get_media_metadata() # 유형별 메타데이터(페이지 수, 크기, 재생 시간 및 기타 유형별 정보)를 가져옵니다 full_metadata = media.get_media_full_metadata() # 바이너리 콘텐츠를 BytesIO 스트림으로 가져옵니다 contents = media.get_media_content() return media

사용자, 그룹 및 보안 주체

보안 주체는 Foundry 사용자 계정 또는 그룹을 나타냅니다. 이러한 유형을 함수에 전달하면 그룹 이름이나 사용자의 이름, 성 또는 이메일 주소와 같이 사용자 또는 그룹과 관련된 정보에 액세스할 수 있습니다. 모든 보안 주체 유형은 @foundry/functions-api 패키지에서 내보냅니다.

  • User에는 항상 사용자 이름이 있으며 firstName, lastName 또는 email이 있을 수 있습니다. 또한 Principal과 관련된 모든 필드를 포함합니다.
  • Group에는 이름이 있습니다. 또한 Principal과 관련된 모든 필드를 포함합니다.
  • Principal은 User 또는 Group일 수 있습니다. type 필드를 검사하여 주어진 Principal이 User인지 Group인지 확인할 수 있습니다. Principal에는 User 및 Group별 필드 외에도 id, realm 및 attributes 딕셔너리가 있습니다.

사용자

Copied!
1 2 3 4 5 6 7 8 import { Function, User } from "@foundry/functions-api"; export class MyFunctions { @Function() public getUserEmail(user: User): string { return user.email; } }
Copied!
1 2 3 4 5 6 7 8 import { UserId } from "@osdk/functions"; import { Users } from "@osdk/foundry.admin"; import { Client } from "@osdk/client"; export default function getUserEmail(client:Client, userId: UserId): string { const user = Users.get(client, userId) return user.email; }
Copied!
1 2 3 4 5 6 7 8 9 from functions.api import function, UserId from foundry_sdk import FoundryClient import foundry_sdk @function() def getUserEmail(user_id: UserId) -> string: client = FoundryClient(auth=foundry_sdk.UserTokenAuth(...), hostname="example.palantirfoundry.com") user = client.admin.User.get(user_id) return user.email

그룹

Copied!
1 2 3 4 5 6 7 8 import { Function, Group } from "@foundry/functions-api"; export class MyFunctions { @Function() public getGroupName(group: Group): string { return group.name; } }
Copied!
1 2 3 4 5 6 7 8 import { GroupId } from "@osdk/functions"; import { Groups } from "@osdk/foundry.admin"; import { Client } from "@osdk/client"; export default function getGroupName(client: Client, groupId: GroupId): string { const group = Groups.get(client, groupId) return group.name; }
Copied!
1 2 3 4 5 6 7 8 9 from functions.api import function, GroupId from foundry_sdk import FoundryClient import foundry_sdk @function() def getGroupName(group_id: GroupId) -> string: client = FoundryClient(auth=foundry_sdk.UserTokenAuth(...), hostname="example.palantirfoundry.com") group = client.admin.Group.get(group_id) return group.name

보안 주체

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { Function, Principal } from "@foundry/functions-api"; export class MyFunctions { @Function() public getPrincipalType(principal: Principal): string { switch (principal.type) { case "user": return "User"; case "group": return "Group"; default: return "Unknown"; } } }
Copied!
1 2 3 4 5 import { GroupId, Principal, UserId } from "@osdk/functions"; export default async function getPrincipals(client: Client, userId: UserId, groupId: GroupId): Principal[] { return [{type: "user", id: userId}, {type: "group", id: groupId}]; }
Copied!
1 2 3 4 5 from functions.api import Array, function, GroupId, Principal, UserId @function() def getPrincipals(user_id: UserId, group_id: GroupId) -> Array[Principal]: return [Principal.user(user_id), Principal.group(group_id)]

지오메트리 유형

지오메트리 유형은 Function에서 공간 데이터와 지리적 도형을 나타냅니다. 다음 두 가지 지오메트리 유형이 지원됩니다.

  • GeoPoint는 위도 및 경도 좌표가 있는 단일 지리적 지점을 나타냅니다.
  • GeoShape는 Point, Polygon, LineString 및 기타 도형을 포함한 모든 유효한 GeoJSON 지오메트리를 나타냅니다.

이러한 유형은 GeoJSON 사양 ↗을 따르며 공간 연산, 지도 작성 및 지리 분석에 사용할 수 있습니다. 위치 인수는 GeoJSON 사양에 따라 경도, 위도 순서를 따릅니다.

GeoPoint

다음 예제는 GeoPoint를 생성하고 반환하는 방법을 보여줍니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 import { Function, GeoPoint } from "@foundry/functions-api"; export class MyFunctions { @Function() public createPoint(): GeoPoint { return GeoPoint.fromCoordinates({ latitude: 37.7749, longitude: -22.4194 }); } }
Copied!
1 2 3 4 5 6 7 8 9 10 import { Point } from "@osdk/functions"; function createPoint(): Point { return { type: "Point", coordinates: [-22.4194, 37.7749] }; } export default createPoint;
Copied!
1 2 3 4 5 from functions.api import function, GeoPoint @function def create_point() -> GeoPoint: return GeoPoint(type="Point", coordinates=[-22.4194, 37.7749])

GeoShape

다음 예제는 Polygon을 생성하고 반환하는 방법을 보여줍니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { Function, Polygon, GeoPoint } from "@foundry/functions-api"; export class MyFunctions { @Function() public createPolygon(): Polygon { const ring: GeoPoint[] = [ GeoPoint.fromCoordinates({ latitude: 37.8, longitude: -22.4 }), GeoPoint.fromCoordinates({ latitude: 37.8, longitude: -22.5 }), GeoPoint.fromCoordinates({ latitude: 37.7, longitude: -22.5 }), GeoPoint.fromCoordinates({ latitude: 37.7, longitude: -22.4 }), GeoPoint.fromCoordinates({ latitude: 37.8, longitude: -22.4 }) ]; return Polygon.fromLinearRings([ring]); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { Geometry } from "@osdk/functions"; function createPolygon(): Geometry { return { type: "Polygon", coordinates: [[ [-22.4, 37.8], [-22.5, 37.8], [-22.5, 37.7], [-22.4, 37.7], [-22.4, 37.8] ]] }; } export default createPolygon;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 from functions.api import function, Polygon @function def create_polygon() -> Polygon: return Polygon( type="Polygon", coordinates=[[ [-22.4, 37.8], [-22.5, 37.8], [-22.5, 37.7], [-22.4, 37.7], [-22.4, 37.8] ]])

온톨로지 편집 Function은 GeoJSON 스트링에서 geoshape 속성을 설정할 수 있지만, 변환 단계는 언어에 따라 다릅니다.

  • TypeScript v1: GeoShape.fromGeoJson()은 파싱된 GeoJSON 지오메트리 또는 지오메트리 컬렉션을 받으므로, 스트링을 전달하기 전에 파싱해야 합니다.
  • TypeScript v2: Geometry는 일반 GeoJSON 오브젝트이므로 변환 함수가 필요하지 않습니다. 파싱된 값을 직접 할당하면 됩니다.
  • Python: Polygon이나 LineString과 같은 각 구체적인 지오메트리 클래스는 JSON 스트링 자체를 받는 from_geo_json() 메서드를 제공합니다. GeoShape 유형은 이 메서드를 제공하지 않으므로 예상하는 지오메트리에 맞는 클래스를 사용해야 합니다.

다음 예제는 JSON 스트링에서 Region 오브젝트의 geoshape 속성을 설정합니다.

Copied!
1 2 3 4 5 6 7 8 9 10 import { OntologyEditFunction, Edits, GeoShape } from "@foundry/functions-api"; import { Region } from "@foundry/ontology-api"; export class MyFunctions { @Edits(Region) @OntologyEditFunction() public updateBoundary(region: Region, boundary: string): void { region.boundary = GeoShape.fromGeoJson(JSON.parse(boundary)); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import { Region } from "@ontology/sdk"; import { Client, Osdk } from "@osdk/client"; import { createEditBatch, Edits, Geometry } from "@osdk/functions"; type RegionEdit = Edits.Object<Region>; function updateBoundary( client: Client, region: Osdk.Instance<Region>, boundary: string ): RegionEdit[] { const batch = createEditBatch<RegionEdit>(client); batch.update(region, { boundary: JSON.parse(boundary) as Geometry }); return batch.getEdits(); } export default updateBoundary;
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 from functions.api import function, OntologyEdit, Polygon from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import Region @function(edits=[Region]) def update_boundary(region: Region, boundary: str) -> list[OntologyEdit]: ontology_edits = FoundryClient().ontology.edits() editable_region = ontology_edits.objects.Region.edit(region) editable_region.boundary = Polygon.from_geo_json(boundary) return ontology_edits.get_edits()