How to create a secondary index in the Cassandra Hector API programmatically

I am trying to create indexing using the rowset below.

 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 can’t do it. In fact, I dynamically store data in columns, and also dynamically create these columns, and then for a better query, I try to put the index on some specific columns. Any suggestion please how to do this.

+3
source share
1 answer

In the end, it's pretty simple. You just need to create a secondary index by defining your column. In the above code, all manipulations are performed at the index of the object, which should be created only when defined. Steps for adding an index:

    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

Helper Method Code: 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;
    }       

, .

+5

All Articles