2
votes

I am using map type column in Cassandra 2.1.7. My requirement is that I have to preserve the order of values which I am inserting in Cassandra for later retrieval. For that I have used LinkedHashMap in Java which serves its purpose.

Now, while debugging I found the order is preserved till Java is handling the key-value pairs but while executing "insert into" CQL command, Cassandra rearranges the map keys in ascending order without asking me, which I don't like :-)

I have searched for providing sort options while defining map types in Cassandra but got nothing as map types got limited flexibility in Cassandra.

Could you please suggest any workaround to meet the above expectations !

2

2 Answers

2
votes

You are correct that the Cassandra Map (and Set) type does not preserve order.

aploetz@cqlsh:stackoverflow2> CREATE TABLE maptest 
    (key text PRIMARY KEY, values map<text,text>);
aploetz@cqlsh:stackoverflow2> INSERT INTO maptest (key, values) 
    VALUES ('key1',{'4':'Four','1':'One','2':'Two'});
aploetz@cqlsh:stackoverflow2> SELECT * FROM maptest ;

 key  | values
------+---------------------------------------
 key1 | {'1': 'One', '2': 'Two', '4': 'Four'}

(1 rows)

The List type however, handles this just fine:

aploetz@cqlsh:stackoverflow2> CREATE TABLE listtest 
    (key text PRIMARY KEY, values list<text>);
aploetz@cqlsh:stackoverflow2> INSERT INTO listtest (key, values) 
    VALUES ('key2',['4','1','2']);
aploetz@cqlsh:stackoverflow2> SELECT * FROM listtest ;

 key  | values
------+-----------------
 key2 | ['4', '1', '2']

(1 rows)

Perhaps (as a workaround) something you could try would be to include a column of the List type along with your Map. You could store the keys in the List in the order of your choosing. When you read your row back out, you could iterate through the List (which would be in your chosen order), and use the List values to determine which key/value pairs to pull from the Map.

1
votes

Cassandra returns results in an order based on the type of the elements in the collection. For example, a set of text elements is returned in "alphabetical order". If you want elements of the collection returned in insertion order, use a list.

You can find more details from Datastax's Docs Page