Я не могу создать супер столбец с Гектором в Java

Я совершенно новичок в Кассандре и Гекторе и пытаюсь создать супер колонку. Я уже провел много исследований, но так или иначе, пока ничего не работает. Во время моего исследования в стеке потока я нашел этот вопрос, который мне показался полезным. Поэтому я попытался вставить код для моего примера, но я получаю исключение.

Это мой код (должен быть копируемым / вставляемым, если у вас есть гектор) - извините, если он может быть не совсем читабельным, я сделал много проб и ошибок, прежде чем спросить здесь:

import java.util.Arrays;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.ThriftKsDef;
import me.prettyprint.cassandra.service.template.SuperCfTemplate;
import me.prettyprint.cassandra.service.template.SuperCfUpdater;
import me.prettyprint.cassandra.service.template.ThriftSuperCfTemplate;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
import me.prettyprint.hector.api.factory.HFactory;

public class DatabaseDataImporter {

    private Cluster myCluster;
    private KeyspaceDefinition keyspaceDefinition;
    private Keyspace keyspace;
    private SuperCfTemplate<String, String, String> template;

    final static StringSerializer ss = StringSerializer.get();

    public DatabaseDataImporter() {

        initializeCluster();

        SuperCfTemplate<String, String, String> template = new ThriftSuperCfTemplate<String, String, String>(
                keyspace, "Nodes", ss, ss, ss);
        SuperCfUpdater<String, String, String> updater = template
                .createUpdater("key", "newcf");
        updater.setString("subname", "1");
        template.update(updater);
    }

    private void initializeCluster() {
        // get Cluster
        myCluster = HFactory.getOrCreateCluster("Test Cluster",
                "localhost:9160");

        keyspaceDefinition = myCluster.describeKeyspace("Graphs");
        // If keyspace does not exist, the CFs don't exist either. => create
        // them.
        if (keyspaceDefinition == null) {
            createSchema();
        }

        keyspace = HFactory.createKeyspace("Graphs", myCluster);
    }

    private void createSchema() {
        // get Cluster
        Cluster myCluster = HFactory.getOrCreateCluster("Test Cluster",
                "localhost:9160");

        // add Schema
        int replicationFactor = 1;

        ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(
                "Graphs", "Nodes", ComparatorType.BYTESTYPE);

        KeyspaceDefinition newKeyspace = HFactory.createKeyspaceDefinition(
                "Graphs", ThriftKsDef.DEF_STRATEGY_CLASS, replicationFactor,
                Arrays.asList(cfDef));
        // Add the schema to the cluster.
        // "true" as the second param means that Hector will block until all
        // nodes see the change.
        myCluster.addKeyspace(newKeyspace, true);
    }

    public static void main(String[] args) {
        new DatabaseDataImporter();
    }

}

Исключение, которое я получаю:

Exception in thread "main" me.prettyprint.hector.api.exceptions.HInvalidRequestException: InvalidRequestException(why:supercolumn parameter is invalid for standard CF Nodes)
    at me.prettyprint.cassandra.service.ExceptionsTranslatorImpl.translate(ExceptionsTranslatorImpl.java:52)
    at me.prettyprint.cassandra.connection.HConnectionManager.operateWithFailover(HConnectionManager.java:260)
    at me.prettyprint.cassandra.model.ExecutingKeyspace.doExecuteOperation(ExecutingKeyspace.java:113)
    at me.prettyprint.cassandra.model.MutatorImpl.execute(MutatorImpl.java:243)
    at me.prettyprint.cassandra.service.template.AbstractColumnFamilyTemplate.executeBatch(AbstractColumnFamilyTemplate.java:115)
    at me.prettyprint.cassandra.service.template.AbstractColumnFamilyTemplate.executeIfNotBatched(AbstractColumnFamilyTemplate.java:159)
    at me.prettyprint.cassandra.service.template.SuperCfTemplate.update(SuperCfTemplate.java:203)
    at algorithms.DatabaseDataImporter.<init>(DatabaseDataImporter.java:43)
    at algorithms.DatabaseDataImporter.main(DatabaseDataImporter.java:87)
Caused by: InvalidRequestException(why:supercolumn parameter is invalid for standard CF Nodes)
    at org.apache.cassandra.thrift.Cassandra$batch_mutate_result.read(Cassandra.java:20833)
    at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
    at org.apache.cassandra.thrift.Cassandra$Client.recv_batch_mutate(Cassandra.java:964)
    at org.apache.cassandra.thrift.Cassandra$Client.batch_mutate(Cassandra.java:950)
    at me.prettyprint.cassandra.model.MutatorImpl$3.execute(MutatorImpl.java:246)
    at me.prettyprint.cassandra.model.MutatorImpl$3.execute(MutatorImpl.java:243)
    at me.prettyprint.cassandra.service.Operation.executeAndSetResult(Operation.java:104)
    at me.prettyprint.cassandra.connection.HConnectionManager.operateWithFailover(HConnectionManager.java:253)
    ... 7 more

Я могу понять, что я как-то плохо поступаю, потому что пытаюсь вставить суперколонку в стандартную семью колонок. (Источник для этого здесь). Так что, возможно, это код, в котором все нарушается при создании:

ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(
        "Graphs", "Nodes", ComparatorType.BYTESTYPE);

И это тот момент, когда я не знаю, как поступить. Я пытался найти класс "SuperColumnFamilyDefinition", но не смог его найти. У вас есть идеи или предложения, что мне нужно изменить, чтобы исправить мой код? Я был бы очень рад.

Большое спасибо за каждую мысль, которую вы поделитесь со мной.

1 ответ

Решение

Я нашел ответ на свою проблему и хотел бы поделиться (возможно, это поможет кому-то в будущем). Как я и думал, решение было довольно простым.

ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(
                "Graphs", "Nodes", ComparatorType.BYTESTYPE);

необходимо расширить до

ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(
        "Graphs", "Nodes", ComparatorType.BYTESTYPE);
// defines it as super column
((ThriftCfDef) cfDef).setColumnType(ColumnType.SUPER);
Другие вопросы по тегам