Java Cassandra中的InvalidRequestException

Java Cassandra中的InvalidRequestException,java,nosql,cassandra,Java,Nosql,Cassandra,两天前,我在实习期间开始学习Cassandra,他们让我了解了Cassandra,我从网上找到了一些代码。代码在语法上没有错误,但当我运行代码时,会出现如下错误: InvalidRequestException(原因:键空间 此架构中不存在博客。) 在 org.apache.cassandra.thrift.cassandra$remove_result.read(cassandra.java:14354) 在 org.apache.cassandra.thrift.cassandra$Clie

两天前,我在实习期间开始学习Cassandra,他们让我了解了Cassandra,我从网上找到了一些代码。代码在语法上没有错误,但当我运行代码时,会出现如下错误:

InvalidRequestException(原因:键空间 此架构中不存在博客。) 在 org.apache.cassandra.thrift.cassandra$remove_result.read(cassandra.java:14354) 在 org.apache.cassandra.thrift.cassandra$Client.recv_remove(cassandra.java:755) 在 org.apache.cassandra.thrift.cassandra$Client.remove(cassandra.java:729) 在 Authors.removeAuthor(Authors.java:141) at Authors.main(Authors.java:59)

我还使用./cassandra-f命令从控制台运行cassandra。 我想我需要先建立一个cassandra数据库,但我真的找不到如何用java实现它。 请帮助我了解这个话题。 多谢各位

如果有帮助的话,我正在尝试的代码就在这里


/**
*博客发布的示例代码:
* 
*通过Java第4部分(Thrift客户端)安装和使用Apache Cassandra
* http://www.sodeso.nl/?p=251
* 
*请报告您可能发现的任何差异,
*如果您对此处未提及的示例有任何要求
*但是也在博客发帖的范围之内
*请让我知道,以便我可以添加它们。。
*/
导入java.io.UnsupportedEncodingException;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入org.apache.cassandra.thrift.cassandra;
导入org.apache.cassandra.thrift.Column;
导入org.apache.cassandra.thrift.column或SuperColumn;
导入org.apache.cassandra.thrift.ColumnParent;
导入org.apache.cassandra.thrift.ColumnPath;
导入org.apache.cassandra.thrift.consistentylevel;
导入org.apache.cassandra.thrift.Deletion;
导入org.apache.cassandra.thrift.InvalidRequestException;
导入org.apache.cassandra.thrift.KeyRange;
导入org.apache.cassandra.thrift.KeySlice;
导入org.apache.cassandra.thrift.Mutation;
导入org.apache.cassandra.thrift.NotFoundException;
导入org.apache.cassandra.thrift.SlicePredicate;
导入org.apache.cassandra.thrift.SliceRange;
导入org.apache.cassandra.thrift.TimedOutException;
导入org.apache.cassandra.thrift.UnavailableException;
导入org.apache.thrift.TException;
导入org.apache.thrift.protocol.TBinaryProtocol;
导入org.apache.thrift.protocol.TProtocol;
导入org.apache.thrift.transport.TSocket;
导入org.apache.thrift.transport.tttransport;
导入org.apache.thrift.transport.ttTransportException;
/**
*@作者罗纳德·马蒂斯
*/
公共类作者{
私有静态最终字符串KEYSPACE=“Blog”;
私有静态最终字符串列\u FAMILY=“Authors”;
公共静态最终字符串编码=“utf-8”;
私有静态tttransport tr=null;
公共静态void main(字符串[]args)引发TexException、InvalidRequestException、UnavailableException、UnsupportedEncodingException、NotFoundException、TimeDoutexException{
Client=setupConnection();
System.out.println(“删除我们以前可能创建的所有作者。\n”);
removeAuthor(客户,“Eric Long”);
removeAuthor(客户,“Ronald Mathis”);
removeAuthor(客户,“John Steward”);
System.out.println(“创建作者。\n”);
createAuthor(客户,“Eric Long”,“Eric(at)Long.com”,“英国”,“2002年1月1日”);
createAuthor(客户,“Ronald Mathies”,“Ronald(at)sodeso.nl”,“荷兰,The”,“01/01/2010”);
createAuthor(客户,“John Steward”,“John.Steward(在)somedomain.com”,“澳大利亚”,“2009年1月1日”);
System.out.println(“选择Eric Long.\n”);
选择SingleAuthorWithAllColumns(客户端,“Eric Long”);
System.out.println(“选择Ronald Mathies.\n”);
选择SingleAuthor和AllColumns(客户端,“Ronald Mathis”);
System.out.println(“选择John Steward.\n”);
选择SingleAuthor和AllColumns(客户端,“John Steward”);
System.out.println(“选择所有列的所有作者。\n”);
选择AllAuthor和AllColumns(客户端);
System.out.println(“选择仅包含电子邮件列的所有作者。\n”);
选择AllAuthor(仅限电子邮件列)(客户端);
System.out.println(“更新John Steward.\n”);
更新软件作者(客户端);
System.out.println(“选择John Steward.\n”);
选择SingleAuthor和AllColumns(客户端,“John Steward”);
System.out.println(“删除约翰·斯图尔特的电子邮件地址和生日。\n”);
删除JohnSteward(客户)的电子邮件和生日;
System.out.println(“选择John Steward.\n”);
选择SingleAuthor和AllColumns(客户端,“John Steward”);
closeConnection();
}
/**
*打开与Cassandra数据库的新连接。
* 
*@返回Cassandra客户端
*/
私有静态Cassandra.Client setupConnection()抛出TTTransportException{
试一试{
tr=新的TSocket(“本地主机”,9160);
TProtocol proto=新的TBinaryProtocol(tr);
Cassandra.Client Client=新的Cassandra.Client(proto);
tr.open();
返回客户;
}捕获(TTTransportException异常){
异常。printStackTrace();
}
返回null;
}
/**
*关闭与Cassandra数据库的连接。
*/
私有静态void closeConnection(){
试一试{
tr.flush();
tr.close();
}捕获(TTTransportException异常){
异常。printStackTrace();
}
}
/**
*从“作者”列族中删除作者。
*中交
*@param客户端Corg.apache.thrift;
导入桑德拉客户端
*@param authorKey作者的密钥
*/
私有静态void removeAuthor(Cassandra.Client客户端,字符串身份验证){
试一试{
ColumnPath ColumnPath=新的ColumnPath(COLUMN_族);
/**
 * Sample code for the blog posting:
 * 
 * Installing and using Apache Cassandra With Java Part 4 (Thrift Client)
 * http://www.sodeso.nl/?p=251
 * 
 * Please report any discrepancies that you may find,
 * if you have any requests for examples not mentioned here
 * but are within the scope of the blog posting then also
 * please let me know so i can add them..
 */


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.Deletion;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

/**
 * @author Ronald Mathies
 */
public class Authors {

    private static final String KEYSPACE = "Blog";
    private static final String COLUMN_FAMILY = "Authors";

    public static final String ENCODING = "utf-8";

    private static TTransport tr = null;

    public static void main(String[] args) throws TException, InvalidRequestException, UnavailableException, UnsupportedEncodingException, NotFoundException, TimedOutException {
        Cassandra.Client client = setupConnection();

        System.out.println("Remove all the authors we might have created before.\n");
        removeAuthor(client, "Eric Long");
        removeAuthor(client, "Ronald Mathies");
        removeAuthor(client, "John Steward");

        System.out.println("Create the authors.\n");
        createAuthor(client, "Eric Long", "eric (at) long.com", "United Kingdom", "01/01/2002");
        createAuthor(client, "Ronald Mathies", "ronald (at) sodeso.nl", "Netherlands, The", "01/01/2010");
        createAuthor(client, "John Steward", "john.steward (at) somedomain.com", "Australia", "01/01/2009");

        System.out.println("Select Eric Long.\n");
        selectSingleAuthorWithAllColumns(client, "Eric Long");

        System.out.println("Select Ronald Mathies.\n");
        selectSingleAuthorWithAllColumns(client, "Ronald Mathies");

        System.out.println("Select John Steward.\n");
        selectSingleAuthorWithAllColumns(client, "John Steward");

        System.out.println("Select all authors with all columns.\n");
        selectAllAuthorsWithAllColumns(client);

        System.out.println("Select all authors with only the email column.\n");
        selectAllAuthorsWithOnlyTheEmailColumn(client);

        System.out.println("Update John Steward.\n");
        updateJohnStewardAuthor(client);

        System.out.println("Select John Steward.\n");
        selectSingleAuthorWithAllColumns(client, "John Steward");

        System.out.println("Remove email address and birthday from John Steward.\n");
        deleteEmailAndBirthdayFromJohnSteward(client);

        System.out.println("Select John Steward.\n");
        selectSingleAuthorWithAllColumns(client, "John Steward");

        closeConnection();
    }

    /**
     * Open up a new connection to the Cassandra Database.
     * 
     * @return the Cassandra Client
     */
    private static Cassandra.Client setupConnection() throws TTransportException {
        try {
            tr = new TSocket("localhost", 9160);
            TProtocol proto = new TBinaryProtocol(tr);
            Cassandra.Client client = new Cassandra.Client(proto);
            tr.open();

            return client;
        } catch (TTransportException exception) {
            exception.printStackTrace();
        }

        return null;
    }

    /**
     * Close the connection to the Cassandra Database.
     */
    private static void closeConnection() {
        try {
            tr.flush();
            tr.close();
        } catch (TTransportException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Removes an Author from the Authors ColumnFamily.
     * cccc
     * @param client the Corg.apache.thrift;

importassandra Client
     * @param authorKey The key of the Author
     */
    private static void removeAuthor(Cassandra.Client client, String authorKey) {
        try {
            ColumnPath columnPath = new ColumnPath(COLUMN_FAMILY);
            client.remove(KEYSPACE, authorKey, columnPath, System.currentTimeMillis(), ConsistencyLevel.ALL);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Creates and stores an Author in the Cassandra Database.
     * 
     * @param client the Cassandra Client
     * @param authorKey The key of the Author
     * @param email the email address
     * @param country the country
     * @param registeredSince the registration date
     */
    private static void createAuthor(Cassandra.Client client, String authorKey, String email, String country, String registeredSince) {
        try {
            long timestamp = System.currentTimeMillis();
            Map<String, List<ColumnOrSuperColumn>> job = new HashMap<String, List<ColumnOrSuperColumn>>();

            List<ColumnOrSuperColumn> columns = new ArrayList<ColumnOrSuperColumn>();
            Column column = new Column("email".getBytes(ENCODING), email.getBytes(ENCODING), timestamp);
            ColumnOrSuperColumn columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);
            columns.add(columnOrSuperColumn);

            column = new Column("country".getBytes(ENCODING), country.getBytes(ENCODING), timestamp);
            columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);
            columns.add(columnOrSuperColumn);

            column = new Column("country".getBytes(ENCODING), country.getBytes(ENCODING), timestamp);
            columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);
            columns.add(columnOrSuperColumn);

            column = new Column("registeredSince".getBytes(ENCODING), registeredSince.getBytes(ENCODING), timestamp);
            columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);
            columns.add(columnOrSuperColumn);

            job.put(COLUMN_FAMILY, columns);

            client.batch_insert(KEYSPACE, authorKey, job, ConsistencyLevel.ALL);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Selects a single author with all the columns from the Cassandra database
     * and display it in the console.
     * 
     * @param client the Cassandra client
     * @param authorKey The key of the Author
     */
    private static void selectSingleAuthorWithAllColumns(Cassandra.Client client, String authorKey) {
        try {
            SlicePredicate slicePredicate = new SlicePredicate();
            SliceRange sliceRange = new SliceRange();
            sliceRange.setStart(new byte[] {});
            sliceRange.setFinish(new byte[] {});
            slicePredicate.setSlice_range(sliceRange);

            ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
            List<ColumnOrSuperColumn> result = client.get_slice(KEYSPACE, authorKey, columnParent, slicePredicate, ConsistencyLevel.ONE);

            printToConsole(authorKey, result);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Selects all the authors with all the columns from the Cassandra database.
     * 
     * @param client the Cassandra client
     */
    private static void selectAllAuthorsWithAllColumns(Cassandra.Client client) {
        try {
            KeyRange keyRange = new KeyRange(3);
            keyRange.setStart_key("");
            keyRange.setEnd_key("");

            SliceRange sliceRange = new SliceRange();
            sliceRange.setStart(new byte[] {});
            sliceRange.setFinish(new byte[] {});

            SlicePredicate slicePredicate = new SlicePredicate();
            slicePredicate.setSlice_range(sliceRange);

            ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
            List<KeySlice> keySlices = client.get_range_slices(KEYSPACE, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE);

            for (KeySlice keySlice : keySlices) {
                printToConsole(keySlice.getKey(), keySlice.getColumns());
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Selects all the authors with only the email column from the Cassandra
     * database.
     * 
     * @param client the Cassandra client
     */
    private static void selectAllAuthorsWithOnlyTheEmailColumn(Cassandra.Client client) {
        try {
            KeyRange keyRange = new KeyRange(3);
            keyRange.setStart_key("");
            keyRange.setEnd_key("");

            List<byte[]> columns = new ArrayList<byte[]>();
            columns.add("email".getBytes(ENCODING));

            SlicePredicate slicePredicate = new SlicePredicate();
            slicePredicate.setColumn_names(columns);

            ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
            List<KeySlice> keySlices = client.get_range_slices(KEYSPACE, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE);

            for (KeySlice keySlice : keySlices) {
                printToConsole(keySlice.getKey(), keySlice.getColumns());
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Update the John Steward author with a new email address and a new field, the birthday.
     * 
     * @param client the Cassandra client
     */
    private static void updateJohnStewardAuthor(Cassandra.Client client) {
        try {
            long timestamp = System.currentTimeMillis();

            Map<String, Map<String, List<Mutation>>> job = new HashMap<String, Map<String, List<Mutation>>>();
            List<Mutation> mutations = new ArrayList<Mutation>();

            // Change the email address
            Column column = new Column("email".getBytes(ENCODING), "john@steward.nl".getBytes(ENCODING), timestamp);
            ColumnOrSuperColumn columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);

            Mutation mutation = new Mutation();
            mutation.setColumn_or_supercolumn(columnOrSuperColumn);
            mutations.add(mutation);

            // Add a new column
            column = new Column("birthday".getBytes(ENCODING), "05-04-1978".getBytes(ENCODING), timestamp);
            columnOrSuperColumn = new ColumnOrSuperColumn();
            columnOrSuperColumn.setColumn(column);

            mutation = new Mutation();
            mutation.setColumn_or_supercolumn(columnOrSuperColumn);
            mutations.add(mutation);

            Map<String, List<Mutation>> mutationsForColumnFamily = new HashMap<String, List<Mutation>>();
            mutationsForColumnFamily.put(COLUMN_FAMILY, mutations);

            job.put("John Steward", mutationsForColumnFamily);

            client.batch_mutate(KEYSPACE, job, ConsistencyLevel.ALL);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Delete the email address and birthday from John Steward.
     * 
     * @param client the Cassandra client
     */
    private static void deleteEmailAndBirthdayFromJohnSteward(Cassandra.Client client) {
        try {
            long timestamp = System.currentTimeMillis();

            // The columns we want to remove
            List<byte[]> columns = new ArrayList<byte[]>();
            columns.add("email".getBytes(ENCODING));
            columns.add("birthday".getBytes(ENCODING));

            // Add the columns to a SlicePredicate
            SlicePredicate slicePredicate = new SlicePredicate();
            slicePredicate.setColumn_names(columns);

            Deletion deletion = new Deletion(timestamp);
            deletion.setPredicate(slicePredicate);

            Mutation mutation = new Mutation();
            mutation.setDeletion(deletion);

            List<Mutation> mutations = new ArrayList<Mutation>();
            mutations.add(mutation);

            Map<String, List<Mutation>> mutationsForColumnFamily = new HashMap<String, List<Mutation>>();
            mutationsForColumnFamily.put(COLUMN_FAMILY, mutations);

            Map<String, Map<String, List<Mutation>>> batch = new HashMap<String, Map<String, List<Mutation>>>();
            batch.put("John Steward", mutationsForColumnFamily);

            client.batch_mutate(KEYSPACE, batch, ConsistencyLevel.ALL);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * Prints out the information to the console.
     * 
     * @param key the key of the Author
     * @param result the result to print out
     */
    private static void printToConsole(String key, List<ColumnOrSuperColumn> result) {
        try {
            System.out.println("Key: '" + key + "'");
            for (ColumnOrSuperColumn c : result) {
                if (c.getColumn() != null) {
                    String name = new String(c.getColumn().getName(), ENCODING);
                    String value = new String(c.getColumn().getValue(), ENCODING);
                    long timestamp = c.getColumn().getTimestamp();
                    System.out.println("  name: '" + name + "', value: '" + value + "', timestamp: " + timestamp);
                } else {

                }
            }
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }
    }

}