Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create secondary index in Cassandra Hector API programmatically

I have been trying to create indexing using below set of lines.

 KeyspaceDefinition fromCluster = cluster.describeKeyspace(KEYSPACE);
 ColumnFamilyDefinition cfDef = fromCluster.getCfDefs().get(0);
 BasicColumnFamilyDefinition columnFamilyDefinition = newBasicColumnFamilyDefinition(cfDef); 
 BasicColumnDefinition columnDefinition = new BasicColumnDefinition();
 columnDefinition.setName(StringSerializer.get().toByteBuffer("A_NO"));    
 columnDefinition.setIndexName("A_NO_idx");
 columnDefinition.setIndexType(ColumnIndexType.KEYS);   
 columnDefinition.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
 columnFamilyDefinition.addColumnDefinition(columnDefinition);

But i am unable to do so. Actually i am storing the data in the columns dynamically as well as creating those columns dynamically and after that for better query purpose i am trying to put index on some particular columns. Any suggestion please how to do that.

like image 264
abhi Avatar asked Dec 03 '25 19:12

abhi


1 Answers

Its eventually quite simple. You just have to create the secondary index while defining your columnfamily. In the above code, all the manipulation are done on the object index which has to be created while defining only. The steps for adding index are

    List<ColumnDef> columns = new ArrayList<ColumnDef>();
    columns.add(newIndexedColumnDef("columnName", "UTF8Type"));
    List<ColumnDefinition> columnMetadata = ThriftColumnDef
            .fromThriftList(columns);
    cdefs.add(cf_def);    //cf_def is your columnfamily definition

The helper method code is from KeyspaceCreationTest

    public ColumnDef newIndexedColumnDef(String     column_name, String     comparer){
        ColumnDef cd = new ColumnDef(se.toByteBuffer(column_name), comparer);
        cd.setIndex_name(column_name);
        cd.setIndex_type(IndexType.KEYS);
        return cd;
    }       

References for comparer can be found here

I hope it will help you.

like image 194
abhi Avatar answered Dec 05 '25 14:12

abhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!