Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Typically I know what data types to expect in my application particularly if I'm using <a href="http://www.datastax.com/docs/1.1/ddl/column_family#static-column-families" rel="nofollow">static column families</a>; but if I am using dynamic column families, or if I just want to keep my code generic, I tend to set my columns to <code>BytesType</code> and serialize/deserialize them as <code>Object</code> types.</p> <p>e.g. consider the following column family:</p> <pre><code>create column family album with key_validation_class = 'UTF8Type' and comparator = 'UTF8Type' and default_validation_class = 'BytesType'; </code></pre> <p>Using Hector's <code>ObjectSerializer</code> you can read and write your column values as <code>Object</code> types. The values will actually be serialized objects in your column family, and when deserialized in Java code the values will become usable Java objects. The following is what my client code would look like:</p> <pre><code>/* some code left out for brevity */ String columnFamily = "album"; ThriftColumnFamilyTemplate&lt;String, String&gt; template; public void write(String key, Map&lt;String, ?&gt; album) Mutator&lt;String&gt; mutator = template.createMutator(); for (Entry&lt;String, ?&gt; entry : album.entrySet()) { mutator.addInsertion(key, columnFamily, HFactory.createColumn(entry.getKey(), entry.getValue(), StringSerializer.get(), ObjectSerializer.get())); } mutator.execute(); } public Map&lt;String, ?&gt; read(String key) { ColumnFamilyResult&lt;String, String&gt; result = template.queryColumns(key); Map&lt;String, Object&gt; album = new HashMap&lt;String, Object&gt;(); for (String name : result.getColumnNames()) { HColumn&lt;String, ByteBuffer&gt; column = result.getColumn(name); album.put(name, ObjectSerializer.get().fromByteBuffer(column.getValue())); } } </code></pre> <p>Here's a simple test to show you that the column values retain their <code>Object</code> types after deserialization from the column family:</p> <pre><code>public static void main(String[] args) { Map&lt;String, Object&gt; album = new HashMap&lt;String, Object&gt;(); album.put("name", "Up The Bracket"); album.put("release", 2002); album.put("in_stock", true); /* write into column family and read it back out */ client.write("up_the_bracket", album); Map&lt;String, ?&gt; result = client.read("up_the_bracket"); /* the column values are deserialized back into their original types */ assert result.get("name") instanceof String; assert result.get("release") instanceof Integer; assert result.get("in_stock") instanceof Boolean; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload