注: 以下の翻訳の正確性は検証されていません。AIPを利用して英語版の原文から機械的に翻訳されたものです。
レジストリに公開するには、TypeScript 関数のすべての入力パラメーターに明示的な型注釈を付け、戻り値の型を明示的に指定する必要があります。現在対応している関数レジストリのデータ型と、それぞれに対応する言語のデータ型の全一覧を以下に示します。
Pipeline Builder で Python 関数をユーザー定義関数(UDF)として使用していますか?以下のスカラー型(str や int など)は、UDF が返す値のデータ型です。関数は行ごとに1回実行され、その戻り値が新しい列になるためです。DataFrame は返しません。詳細は、Pipeline Builder で Python 関数がデータを処理する仕組みを参照してください。
| 関数レジストリのデータ型 | TypeScript v1 のデータ型 | TypeScript v2 のデータ型 | Python のデータ型 | |
|---|---|---|---|---|
| 添付ファイル | Attachment | Attachment | Attachment | 例 |
| ブール値 | boolean | boolean | bool | 例 |
| バイナリ | 利用できません | 利用できません | bytes | 例 |
| Byte | 利用できません | 利用できません | int* | 例 |
| 機密情報区分マーキング | ClassificationMarking | ClassificationMarking | ClassificationMarking | 例 |
| 日付 | LocalDate | DateISOString | datetime.date | 例 |
| Decimal | 利用できません | 利用できません | decimal.Decimal | 例 |
| Double | Double | Double | float* | 例 |
| Float | Float | Float | float | 例 |
| Geopoint | GeoPoint | Point | GeoPoint | 例 |
| Geoshape | GeoShape | Geometry | GeoShape | 例 |
| グループ | Group | GroupId | GroupId | 例 |
| Integer | Integer | Integer | int | 例 |
| インターフェース | 利用できません | Osdk.Instance<MyInterface> | 利用できません | 例 |
| インターフェースオブジェクトセット | 利用できません | ObjectSet<MyInterface> | 利用できません | 例 |
| リスト | T[] または Array<T> | T[] または Array<T> | list[T] | 例 |
| Long | Long | Long | int* | 例 |
| 必須マーキング | MandatoryMarking | MandatoryMarking | MandatoryMarking | 例 |
| マップ | FunctionsMap<K, V> | Record<K, V> | dict[K, V] | 例 |
| Media Reference | MediaItem | Media | Media | 例 |
| 通知 | Notification | Notification | Notification | 例 |
| オブジェクト | MyObjectType | Osdk.Instance<MyObjectType> | MyObjectType | 例 |
| オブジェクトセット | ObjectSet<MyObjectType> | ObjectSet<MyObjectType> | MyObjectTypeObjectSet | 例 |
| オントロジー編集 | void | Edits | OntologyEdit | 例 |
| 任意 | T | undefined | T | undefined | typing.Optional または T | None | 例 |
| プリンシパル | Principal | Principal | Principal | 例 |
| 範囲 | IRange<T> | Range<T> | Range[T] | 例 |
| セット | Set<T> | 利用できません | set[T] | 例 |
| Short | 利用できません | 利用できません | int* | 例 |
| 文字列 | string | string | str | 例 |
| 構造体/カスタム型 | interface | interface | dataclasses.dataclass | 例 |
| タイムスタンプ | Timestamp | TimestampISOString | datetime.datetime | 例 |
| 2次元集計 | TwoDimensionalAggregation<K, V> | TwoDimensionalAggregation<K, V> | TwoDimensionalAggregation[K, V] | 例 |
| 3次元集計 | ThreeDimensionalAggregation<K, S, V> | ThreeDimensionalAggregation<K, S, V> | ThreeDimensionalAggregation[K, S, V] | 例 |
| ユーザー | User | UserId | UserId | 例 |
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 モジュールからエクスポートされる型エイリアスを使用することを推奨します。
Copied!1 2 3 4 5 6 7 8import { 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 7import { Integer } from "@osdk/functions"; function isEven(num: Integer): boolean { return num % 2 === 0; } export default isEven;
Copied!1 2 3 4 5from functions.api import function, Integer @function def is_even(num: Integer) -> bool: return n % 2 == 0
Copied!1 2 3 4 5 6 7 8import { Function } from "@foundry/functions-api"; export class MyFunctions { @Function() public greet(name: string): string { return `Hello, ${name}!`; } }
Copied!1 2 3 4 5function greet(name: string): string { return `Hello, ${name}!`; } export default greet;
Copied!1 2 3 4 5from functions.api import function @function def greet(name: str) -> str: return f"Hello, {name}!"
-32,768から32,767までの整数値を表します。
Python 関数では、Short 型は組み込みの int 型のエイリアスです。
Copied!1 2 3 4 5from functions.api import function, Short @function def increment(num: Short) -> Short: return num + 1
(-231) から (231 - 1) までの整数値を表します。
Integer 型は組み込みの number 型のエイリアスです。Integer 型は組み込みの int 型のエイリアスです。Copied!1 2 3 4 5 6 7 8import { 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 7import { Integer } from "@osdk/functions"; function sum(a: Integer, b: Integer): Integer { return a + b; } export default sum;
Copied!1 2 3 4 5from functions.api import function, Integer @function def sum(a: Integer, b: Integer) -> Integer: return a + b
-(253 - 1) から (253 - 1) までの整数値を表します。これらの境界値は JavaScript の Number.MIN_SAFE_INTEGER および Number.MAX_SAFE_INTEGER と等しく、ブラウザーのコンテキストから関数が呼び出される際の精度の損失を防ぎます。
Long 型は組み込みの number 型のエイリアスです。TypeScript v2 関数では、Long 型は組み込みの string 型のエイリアスです。Long 型は組み込みの int 型のエイリアスです。Copied!1 2 3 4 5 6 7 8import { 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 7import { 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 5from functions.api import function, Long @function def subtract(a: Long, b: Long) -> str: return str(a - b)
32ビット浮動小数点数を表します。
Float 型は組み込みの number 型のエイリアスです。Float 型は組み込みの float 型のエイリアスです。Copied!1 2 3 4 5 6 7 8import { 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 7import { Float } from "@osdk/functions"; function multiply(a: Float, b: Float): Float { return a * b; } export default multiply;
Copied!1 2 3 4 5from functions.api import function, Float @function def multiply(a: Float, b: Float) -> Float: return a * b
64ビット浮動小数点数を表します。
Double 型は組み込みの number 型のエイリアスです。Double 型は組み込みの float 型のエイリアスです。Copied!1 2 3 4 5 6 7 8import { 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 7import { Double } from "@osdk/functions"; function divide(a: Double, b: Double): Double { return a / b; } export default divide;
Copied!1 2 3 4 5from functions.api import function, Double @function def divide(a: Double, b: Double) -> Double: return a / b
Copied!1 2 3 4 5 6from 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 8import { 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 7import { DateISOString } from "@osdk/functions"; function returnDate(): DateISOString { return "1999-10-17"; } export default returnDate;
Copied!1 2 3 4 5 6from 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 8import { Function, Timestamp } from "@foundry/functions-api"; export class MyFunctions { @Function() public getCurrentTimestamp(): Timestamp { return Timestamp.now(); } }
Copied!1 2 3 4 5 6 7 8import { TimestampISOString } from "@osdk/functions"; function getCurrentTimestamp(): TimestampISOString { const now = new Date(); return now.toISOString(); } export default getCurrentTimestamp;
Copied!1 2 3 4 5 6from datetime import datetime from functions.api import function, Timestamp @function def get_current_timestamp() -> Timestamp: return datetime.now()
Python 関数では、Binary 型は組み込みの bytes 型のエイリアスです。
Copied!1 2 3 4 5from functions.api import function @function def encode_utf8(param: str) -> bytes: return param.encode('utf-8')
Python 関数では、Byte 型は組み込みの int 型のエイリアスです。
Copied!1 2 3 4 5 6 7from 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 11import { 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 16import { 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 18from 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 11import { 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 16import { 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 18from 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] は文字列のキーと整数値を持つ辞書です。パラメーターとして使用するデータ型は必ず指定する必要があり、サポートされている別のデータ型でなければなりません。マップのキーには、スカラー型またはオントロジーのオブジェクトタイプのみを使用できます。
Copied!1 2 3 4 5 6 7 8import { 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 7import { Integer } from "@osdk/functions"; function filterForEvenIntegers(nums: Integer[]): Integer[] { return nums.filter(num => num % 2 === 0); } export default filterForEvenIntegers;
Copied!1 2 3 4 5from 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]
マップは一般に、スカラー型をキーとして、関連付けられた値にアクセスするために使用されます。この値には、関数レジストリのほかの任意のデータ型を使用できます。
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13import { 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 10function 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 10from 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 15import { 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 15import { 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 11from 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
Copied!1 2 3 4 5 6 7 8import { Function, Integer } from "@foundry/functions-api"; export class MyFunctions { @Function() public getSizeOfSet(mySet: Set<Integer>): Integer { return mySet.size; } }
Copied!1 2 3 4 5from functions.api import function, Integer @function def get_size_of_set(my_set: set[Integer]) -> Integer: return len(my_set)
varName?: T または varName: T | undefined として宣言します。たとえば、value という名前の任意の Integer パラメーターを持つ関数は、value?: Integer または value: Integer | undefined のいずれかで宣言できます。TypeScript 関数では、T | undefined 型を指定することで、任意の戻り値の型も宣言できます。たとえば、Integer を返す場合と値を返さない場合がある関数の戻り値の型は、Integer | undefined になります。typing.Optional[T] または T | None を使用して宣言できます。T | None 構文には Python 3.10 以降が必要です。T を必ず指定する必要があり、サポートされている別のデータ型でなければなりません。Copied!1 2 3 4 5 6 7 8 9 10 11import { 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 8function greet(name?: string): string | undefined { if (name === undefined) { return undefined; } return `Hello, ${name}!`; } export default greet;
Copied!1 2 3 4 5 6 7from 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 9import { 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 9import { 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 6from 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 クラスです。
__init__ メソッドは、フィールドと同じ名前および型注釈を持つ名前付き引数のみを受け取る必要があります。dataclasses.dataclass ↗ デコレーターを使用すると、これらの要件に準拠した __init__ メソッドを自動生成できます。Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17import { 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 17import { 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 15from 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つあります。
集計のキーには、いくつかのデータ型を使用できます。
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 11import { 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 10import { 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 8from functions.api import function, Integer, Range @function def get_range(min: Integer, max: Integer) -> Range[Integer]: return Range( min=min, max=max )
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13import { 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 10import { 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 15from 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)), ] )
バケット構造はバージョンによって異なります。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 25import { 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 22import { 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 24from 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 9import { 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 9import { 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 6from 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 24import { 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;
オブジェクトの集合を関数に渡す、または関数から返す方法は2つあります。配列などの具体的なオブジェクトの集合と、オブジェクトセットです。
オブジェクトの配列を関数に渡すと、具体的なオブジェクトのリストに対してロジックを実行できますが、あらかじめオブジェクトを関数の実行環境に読み込む必要があります。一方、オブジェクトセットでは、絞り込み、周辺検索、集計の操作を実行し、最終結果を要求したときにのみ読み込めます。
オブジェクトセットは、多くの場合、より優れたパフォーマンスを実現し、10,000個を超えるオブジェクトを関数に渡せるため、配列ではなくオブジェクトセットの使用を推奨します。
以下の例は、オブジェクトをメモリーに読み込まずにオブジェクトセットを絞り込む方法を示しています。これにより、絞り込んだオブジェクトセットをアプリケーションの別の部分に返すことができます。
Copied!1 2 3 4 5 6 7 8 9import { 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 13import { 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 7from 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 9import { 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 13import { 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 15import { 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 27import { 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 16from 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 8import { 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 7import { 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 5from functions.api import function, Attachment @function def load_attachment_contents(attachment: Attachment) -> str: return attachment.read().getvalue().decode('utf-8')
通知のデータ型を関数から返すことで、プラットフォームで送信する通知を柔軟に設定できます。たとえば、User やオブジェクトタイプなどのパラメーターを受け取り、メッセージが設定された Notification を返す関数を作成できます。
Notification は、ShortNotification と EmailNotificationContent の2つのフィールドで構成されます。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 22import { 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 18import { 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 16from 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 19import { 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 12import 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 14from 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 8import { 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 8import { 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 9from 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 8import { 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 8import { 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 9from 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 16import { 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 5import { 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 5from 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)]
ジオメトリのデータ型は、関数内で空間データと地理的な形状を表します。2つのジオメトリのデータ型がサポートされています。
これらのデータ型は GeoJSON 仕様 ↗に準拠しており、空間操作、地図作成、地理的分析に使用できます。位置引数は、GeoJSON 仕様に従って経度、緯度の順になります。
次の例では、Geopoint を作成して返す方法を示します。
Copied!1 2 3 4 5 6 7 8 9 10 11import { 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 10import { Point } from "@osdk/functions"; function createPoint(): Point { return { type: "Point", coordinates: [-22.4194, 37.7749] }; } export default createPoint;
Copied!1 2 3 4 5from functions.api import function, GeoPoint @function def create_point() -> GeoPoint: return GeoPoint(type="Point", coordinates=[-22.4194, 37.7749])
次の例では、Polygon を作成して返す方法を示します。
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import { 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 16import { 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 13from 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] ]])
オントロジー編集関数では、GeoJSON 文字列から geoshape プロパティを設定できますが、変換手順は言語によって異なります。
GeoShape.fromGeoJson() は、パース済みの GeoJSON ジオメトリまたはジオメトリコレクションを受け取るため、渡す前に文字列をパースします。Geometry は通常の GeoJSON オブジェクトなので、変換関数は不要です。パース済みの値を直接代入します。Polygon や LineString などの各具象ジオメトリクラスには、JSON 文字列そのものを受け取る from_geo_json() メソッドがあります。GeoShape データ型にはこのメソッドがないため、想定するジオメトリに一致するクラスを使用します。次の例では、JSON 文字列から Region オブジェクトの geoshape プロパティを設定します。
Copied!1 2 3 4 5 6 7 8 9 10import { 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 19import { 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 12from 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()