R에서 Flight service 에 수동으로 연결하기
이 오픈 소스 R arrow 라이브러리는 Apache Arrow Flight 프로토콜을 기본적으로 지원하지 않습니다. 권장되는 방법은 R reticulate 라이브러리와 오픈 소스 pyarrowPython 라이브러리를 사용하여 R 환경에서 Flight service 를 호출하는 것입니다. R arrow 라이브러리에는 Flight 서버를 호출하는 함수가 존재하지만, 이 함수들도 를 사용하며 reticulate, 문서화가 충분하지 않을 뿐만 아니라 매개변수 및 인증 측면에서도 그다지 유연하지 않습니다.
노트북에서 ` Flight service `를 호출하는 방법을 알아보려면, Python 노트북에서 ` Flight service ` 사용을 참조하세요.
노트북의 ‘코드 스니펫’ 창에서 파일이나 연결을 통해 데이터를 불러오기 위해 생성된 코드를 사용하는 경우, 해당 코드는 ` Flight service `를 호출하기 위해 pyarrow `and` 및 reticulate ``를 사용하며, 망상 구조의 itc_utils ` Python ` 라이브러리도 함께 사용합니다.
Flight service 용 코드를 직접 작성하려면, 노트북을 사용할 때 가장 좋은 방법은 시스템에서 자동으로 생성된 코드를 기반으로 시작하고, 필요에 따라, pyarrow itc_utils및 기능을 reticulate활용하여 이 코드를 수정하는 것입니다. 다음과 같은 상황에서는 직접 코드를 작성해야 합니다:
- 생성된 코드는, 예를 들어 운영 환경에서 사용하기 위해 수정이 필요합니다
- 이 에셋에는 생성된 코드를 추가하는 기능이 제공되지 않습니다
- 이 도구는 생성된 코드를 추가하는 기능을 지원하지 않습니다. 예를 들어 RStudio
Flight service 의 기본 상호작용
기본 단계를 설명하고 이해를 돕기 위해, 이 섹션의 코드 예제에서는 IBM 에서 제공하는 Pythonitc_utils 라이브러리를 활용합니다. 이 라이브러리는 Flight service 와 연동할 수 있는 함수들을 제공합니다.
데이터 읽기
데이터 소스에서 데이터를 읽어오는 단계는 다음과 같습니다:
- 데이터 소스에 액세스하기 위한 메타데이터를 포함한 플라이트 디스크립터 생성
- 비행 클라이언트 인스턴스 생성
- Flight service 에 비행 정보 설명자를 전송하여 비행 정보 객체를 가져옵니다
- 데이터 소스에서 데이터를 읽습니다. 이 코드 조각은 데이터를
pyarrow.Table읽어온 다음 데이터 프레임으로 변환하는 과정을 보여줍니다.
데이터를 읽는 코드 예시:
# use reticulate library to invoke Python code
library(reticulate)
# use open source R arrow library
library(arrow)
# load Python utility library provided by IBM with reticulate
itcfs <- import("itc_utils.flight_service")
# create a flight descriptor from a data request
data_request = dict(
"asset_id" = "<asset_id>",
"project_id" = "<project_id>",
"interaction_properties" = dict(
"row_limit" = 5000,
"schema_name" = "<schema>",
"table_name" = "<table>"
)
)
flightDescriptor = itcfs$get_flight_descriptor(data_request=data_request)
# create an instance of a flight client
flightClient <- itcfs$get_flight_client()
# obtain a FlightInfo object which provides information for reading data from one or more endpoints.
flightInfo <- itcfs$get_flight_info(flightClient, flight_descriptor=flightDescriptor)
# read data into a vector of pyarrow.Table objects
tables <- itcfs$read_tables(flightClient, flightInfo, timeout=240)
# convert a pyarrow.Table to an R dataframe
df <- as.data.frame(tables[[1]])
데이터 쓰기
데이터 소스에 데이터를 기록하는 단계는 다음과 같습니다:
- 데이터 소스에 액세스하기 위한 메타데이터를 포함한 플라이트 디스크립터 생성
- 비행 클라이언트 인스턴스 생성
- Flight service 를 통한 인증
- 비행 쓰기 스트림 가져오기
- 데이터 대상에 데이터 쓰기
데이터를 기록하는 코드 예시:
# use reticulate library to invoke Python code
library("reticulate")
# use open source R arrow library
library("arrow")
# load Python utility library provided by IBM with reticulate
itcfs <- import("itc_utils.flight_service")
# create a flight descriptor
nb_data_request = dict (
"asset_id" = "<asset_id>",
"project_id" = "<project_id>",
"interaction_properties" = dict (
"schema_name" = "<schema>",
"table_name" = "<table>",
"existing_table_action" = 'truncate',
)
)
flightDescriptor = itcfs$get_flight_descriptor(data_request=data_request)
# create an instance of a flight client
flightClient <- itcfs$get_flight_client()
# write a data to a data target
itcfs$write_table(as_arrow_table(data_df_2),flightDescriptor,flightClient)
항공편 정보
Flight service 와의 상호작용에서 핵심적인 요소는 데이터 소스 접근 방식을 지정하는 플라이트 디스크립터입니다. 여기에는 호스트, 포트 등과 같은 연결 속성 형태의 데이터 소스 사양과 테이블 이름이나 SQL 문과 같은 상호작용 속성이 포함됩니다. 연결 속성 대신, 자산의 ID와 프로젝트 또는 배포 공간의 ID를 지정할 수도 있습니다.
엄밀히 말하면, ` Flight service `는 JSON 문자열 형식의 비행 정보(flight descriptor)를 입력으로 받습니다. R 노트북에서 권장되는 방법은 ` Python `를 reticulate 사용하여 요청 속성을 포함한 사전(dictionary)을 생성하고, `flightDescriptor()` itc_utils 함수를 get_flight_descriptor 사용하여 항공편 설명자를 생성하는 것입니다:
data_request = dict(
"asset_id" = "<asset_id>",
"project_id" = "<project_id>",
"interaction_properties" = dict(
"row_limit" = 5000,
"schema_name" = "",
"table_name" = ""
)
)
flightDescriptor = itcfs$get_flight_descriptor(data_request=data_request)
데이터 읽기 또는 쓰기를 위한 플라이트 설명자는. interaction_properties에 관해서는 약간만 차이가 있습니다. 읽기 요청에는 일반적으로 'sql_statement', 'file_name' 또는 'table_name'과 같은 상호작용 속성이 있는 반면, 쓰기 요청에는 'existing_table_action'이나 'file_format'과 같은 추가적인 상호작용 속성이 있습니다.
데이터 요청 구문에 대한 자세한 내용은 ‘비행 데이터 요청’을 참조하십시오.
Flight Server를 통한 인증
유효한 베어러 토큰을 사용하여 Flight service 에 인증해야 합니다. 이를 위해 다음 코드 스니펫을 사용하여 사용자 정의 인증 핸들러 클래스를 작성하고 이 클래스의 인스턴스를 생성할 수 있습니다.
R 노트북에서는 ` Flight service `에 ` Python `로 작성된 망상 pyarrow 함수를 통해 접근하기 때문에, 이 코드 예제는 사용자 정의 인증 핸들러를 생성하는 한 가지 가능한 방법이자 실제로 작동하는 방식을 보여줍니다. R 노트북에서 권장되는 방법은 reticulated itc_utils 함수를 TokenClientAuthHandler() 사용하거나, 더 get_flight_client() 나은 방법을 사용하는 것입니다.
library("reticulate")
flight <- import("pyarrow.flight")
TokenClientAuthHandler <- PyClass(
"TokenClientAuthHandler",
list(
bearer_token = NULL,
outgoing = NULL,
incoming = NULL,
`__init__` = function(self, bearer_token){
super()$`__init__`()
self$token <- charToRaw(bearer_token)
NULL
},
authenticate = function(self, outgoing, incoming){
outgoing$write(self$token)
self$token <- incoming$read()
},
get_token = function(self){
return(self$token)
}
),
inherit = flight$ClientAuthHandler
)
library(ibmWatsonStudioLib)
wslib <- access_project_or_space()
token <- paste("Bearer ", wslib$auth$get_current_token(), sep = "")
authHandler <- TokenClientAuthHandler(token)