Connessione al server di query Spark utilizzando il driver Spark JDBC
Si applica a: Motore a scintilla
È possibile connettersi al server di query Spark nei seguenti modi ed eseguire query per analizzare i dati.
- Utilizzo di DBeaver(client JDBC)
- Utilizzando il codice di Java(JDBC Client)
- Utilizzo di Python(PyHive JDBC Client)
Prima di iniziare
- Installare watsonx.data.
- Predisporre il motore Spark nativo in watsonx.data.
- Scaricare il client JDBC:
queryserver-jdbc-SNAPSHOT-standalone.jardal link di download. - Eseguire Spark Query Server nel motore Spark. Per creare un nuovo Query Server, vedere Creare un query server Spark.
- Proprietà di connessione - Fare clic sul menu a tre punti per Query Server, fare clic su Dettagli connessione e copiare i seguenti dettagli di connessione:
- Host
- URI
- Istanza
- Nome utente
- La chiave API IAM di IBM.
Connessione al server di query Spark utilizzando DBeaver (client JDBC )
Per connettersi al server di query Spark usando un client JDBC, come DBeaver, impostare il driver watsonx.data in DBeaver.
-
Aprite DBeaver e nella barra dei menu fate clic su Database > Driver Manager.
-
Ricerca di Hive. È possibile trovare il driver Apache Hive 4+ sotto Hadoop categoria.
-
Fare clic su Copia.
-
Cambiare il nome in Spark watsonx.data.
-
Modificare le seguenti impostazioni :
-
Nella scheda Impostazioni,
-
Nella scheda Librerie, aggiungere il file JAR del server di query Spark JDBC.
-
Selezionate Database Navigator, fate clic su Nuova connessione e completate i seguenti passaggi:
- Selezionare il driver appena creato.
- Fare clic su Connetti con e selezionare URL.
- Fornire l'indirizzo JDBC URL utilizzando il seguente formato:
jdbc:hive2://<HOST>:443/default;instance=<INSTANCE>;httpPath=<URI>. - Selezionate Autenticazione, fornite Nome utente come nome utente e la vostra chiave API IAM come password.
- Salvare e collegarsi alla connessione facendo doppio clic.
Connettersi al server di query Spark utilizzando il codice Java ( JDBC Client)
Assicurarsi che il CLASSPATH di Java includa il driver JDBC scaricato. Ad esempio:
java -cp queryserver-jdbc-SNAPSHOT-standalone.jar App.java
È possibile specificare i valori dei parametri e utilizzare il seguente codice Java per connettersi al server di query Spark. Quando si usa l'API v2, impostare il parametro <api_version> su v2; per l'API v3, impostarlo su
v3.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class App {
public static void main(String[] args) throws Exception {
// Set the below configurations from Connection Details of QueryS Server
// Exclude having https/http/www, just domain
String host = "example.com";
String Instance = "CRN/OR/INSTANCE-ID";
String uri = "/lakehouse/api/<api_version>/spark_engines/.../query_servers/.../connect/cliservice";
String user = "EMAIL-ID/OR/USER-ID";
String apikey = "API-KEY";
String jdbcUrl = String.format("jdbc:hive2://%s/default;instance=%s;httpPath=%s;", host, Instance, uri);
// Required if your domain requires SSL certificates
// This is not required for SaaS, hence comment the below line for SaaS
// Else, we need provide trust-store path which has the SSL certificates for the host
jdbcUrl += "sslTrustStore=tech_trust.jks;trustStorePassword=Test@123";
try {
// Load the Hive JDBC driver
Class.forName("com.ibm.wxd.spark.jdbc.QueryServerDriver");
// Connect to Hive
Connection con = DriverManager.getConnection(jdbcUrl, user, apikey);
Statement stmt = con.createStatement();
System.out.println("Connected to watsonx.data Spark Query Server");
// Sample query
String sql = "show databases";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
System.out.println(rsmd.getColumnName(i));
}
// Print result
while (rs.next()) {
System.out.println(rs.getString(1)); // Or loop through columns
}
// Clean up
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Connettersi al server di query Spark utilizzando Python ( PyHive JDBC Client)
Per collegarsi al server di query Spark utilizzando un programma Python, procedere come segue:
-
Assicuratevi di avere Python versione 3.12 o inferiore.
-
Installare pyHive utilizzando
pip install thrift "PyHive[hive_pure_sasl]==0.7.0". -
Salvare il seguito in un file come
connect.py.import ssl import thrift import base64 from pyhive import hive import requests import thrift.transport import thrift.transport.THttpClient import logging import contextlib from http.client import HTTPConnection # Change the following inputs. When using the v2 API, set the <api_version> parameter to `v2`; for the v3 API, set it to `v3`. class Credentials: host = "https://example.ibm.com" uri = "/lakehouse/api/<api_version>/spark_engines/.../query_servers/.../connect/cliservice" instance_id = "CRN/OR/INSTANCE-ID" username = "EMAIL-ID/OR/USER-ID" apikey = "API-KEY" creds = Credentials() def disable_ssl(ctx): ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE ssl.SSLContext.verify_mode = property(lambda self: ssl.CERT_NONE, lambda self, newval: None) def get_access_token(apikey): try: headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', } data = { 'grant_type': 'urn:ibm:params:oauth:grant-type:apikey', 'apikey': apikey, } response = requests.post('https://iam.cloud.ibm.com/identity/token', headers=headers, data=data) return response.json()['access_token'] except Exception as inst: print('Error in getting access token') print(inst) exit ctx = ssl.create_default_context() ## If you require to disable SSL, uncomment the below line # disable_ssl(ctx) transport = thrift.transport.THttpClient.THttpClient( uri_or_host="{host}:{port}{uri}".format( host=creds.host, uri= creds.uri, port=443, ), ssl_context=ctx, ) headers = { "AuthInstanceId": creds.instance_id } if creds.instance_id.isdigit(): # Software installation headers["Authorization"] = "ZenApiKey " + base64.b64encode(f"{creds.username}:{creds.apikey}".encode('utf-8')).decode('utf-8') else: # Cloud installation headers["Authorization"] = "Bearer {}".format(get_access_token(creds.apikey)) transport.setCustomHeaders(headers) cursor = hive.connect(thrift_transport=transport).cursor() print("Connected to Spark Query Server") cursor.execute('show databases') print(cursor.fetchall()) cursor.close() -
Eseguire con
python connect.py.