Query data with SQL

Updated at:

Use Tablestore SDK for Java to execute SELECT statements and query data and field schemas from mapping tables.

Prerequisites

Description

Call the sqlQuery method to execute a SELECT statement and query data from a mapping table. The result contains the field schema and the rows that match the query conditions.

SQLQueryResponse sqlQuery(SQLQueryRequest request)

The following example queries rows whose tenant_id value is 1 from the example_table mapping table and returns up to 10 rows.

String query = "SELECT tenant_id, pk, name, score FROM example_table "
        + "WHERE tenant_id = 1 LIMIT 10";
SQLQueryRequest request = new SQLQueryRequest(query);

SQLQueryResponse response = client.sqlQuery(request);
SQLResultSet resultSet = response.getSQLResultSet();
System.out.println("Schema: " + resultSet.getSQLTableMeta().getSchema());

while (resultSet.hasNext()) {
    SQLRow row = resultSet.next();
    System.out.println(
            row.getLong("tenant_id") + ", "
                    + row.getString("pk") + ", "
                    + row.getString("name") + ", "
                    + row.getLong("score"));
}

Parameters

SQLQueryRequest contains the following parameter.

Name

Type

Description

query (required)

String

The SELECT statement to execute.

Response

SQLQueryResponse contains the following fields related to the query result.

Field

Type

Description

type

SQLStatementType

Call getSQLStatementType() to obtain the SQL statement type. SQL_SELECT is returned for a SELECT statement.

rows

ByteString

The serialized SQL query result. Call getSQLResultSet() to obtain the parsed SQLResultSet. Then, call getSQLTableMeta() to obtain the field schema and iterate over the rows.

consumedCapacityByTable

Map<String, ConsumedCapacity>

Call getConsumedCapacity() to obtain the read CUs consumed by each data table.