Search code examples
dynamicindexingcassandrahector

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.


Solution

  • 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.