0
votes

I have several non-primitive columns in my cassandra tables. Some of them are user-defined-types UDTs.

While querying them through datastax driver, I want to convert such UDTs into JSON values. More specifically, I want to get JSON string for the value object below:

        Row row = itr.next();
        ColumnDefinitions cds = row.getColumnDefinitions();
        cds.asList().forEach((ColumnDefinitions.Definition cd) -> {
            String name = cd.getName();
            Object value = row.getObject(name);
      }

I have gone through http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/

But I do not want to add a codec for every UDT I have.

Looking at Using Datastax Java Driver to query a row as a JSON, I tried this too:

row.getString(name)

But it gives me an error: Codec not found for requested operation: [set<date> <-> java.lang.String]

Can the driver somehow return me direct JSON without explicit meddling with codecs and all?

1

1 Answers

2
votes

Use toJson method

Starting with version 2.2 of Apache Cassandraâ„¢, toJson method return json representation of an object.

Example :

CREATE TYPE fullname (
    firstname text,
    lastname text
);

CREATE TABLE users (
    id uuid PRIMARY KEY,
    direct_reports set<frozen<fullname>>,
    name frozen<fullname>
);

Now you can select direct_reports and name as json

SELECT id,toJson(direct_reports) as direct_reports,toJson(name) as name FROM users ;

Here i have rename toJson(direct_reports) as direct_reports and toJson(name) as name so you can use row.getString("direct_reports") and row.getString("name") to get the direct_reports json and name json.

Output :

 id                  | 62c36092-82a1-3a00-93d1-46196ee77204
 direct_reports      | [{"firstname": "Naoko", "lastname": "Murai"}, {"firstname": "Sompom", "lastname": "Peh"}]
 name                | {"firstname": "Marie-Claude", "lastname": "Josset"}