Cassandra 中的 InvalidRequestException [英] InvalidRequestException in Cassandra

查看:23
本文介绍了Cassandra 中的 InvalidRequestException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Two days ago i started learning Cassandra in my internship, they gave me a learning about Cassandra and i found some codes from the net.There is no errors on the code syntatically but when i run the code i get errors like :

无效请求异常(为什么:键空间此架构中不存在博客.)在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)在 Authors.main(Authors.java:59)

InvalidRequestException(why:Keyspace Blog does not exist in this schema.) at org.apache.cassandra.thrift.Cassandra$remove_result.read(Cassandra.java:14354) at org.apache.cassandra.thrift.Cassandra$Client.recv_remove(Cassandra.java:755) at org.apache.cassandra.thrift.Cassandra$Client.remove(Cassandra.java:729) at Authors.removeAuthor(Authors.java:141) at Authors.main(Authors.java:59)

我也在控制台使用 ./cassandra -f 命令运行 cassandra.我想我需要先建立一个 cassandra 数据库,但我真的找不到如何用 java 来做.请帮我解决这个话题.非常感谢.

I am also running cassandra from the console with the ./cassandra -f command. I think i need to build up a cassandra database first but i really couldn't find how to do it with java. Please help me about this topic. Thank you very much.

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

if it will be helpful the code i am trying is here.

/**
 * 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.
");
        removeAuthor(client, "Eric Long");
        removeAuthor(client, "Ronald Mathies");
        removeAuthor(client, "John Steward");

        System.out.println("Create the authors.
");
        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.
");
        selectSingleAuthorWithAllColumns(client, "Eric Long");

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

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

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

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

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

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

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

        System.out.println("Select John Steward.
");
        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();
        }
    }

}

推荐答案

Keyspace X 不存在"意味着……键空间不存在.键空间在您的 storage-conf.xml 中配置.

"Keyspace X does not exist" means ... the keyspace doesn't exist. Keyspaces are configured in your storage-conf.xml.

除此之外,手动创建 KeySpace 并通过 thrift 客户端与 cassandra 连接.cassandra wiki 网页中给出了它的示例.

In addition to this, create KeySpace manually be connecting with cassandra with thrift client. example of it is given in cassandra wiki webpage.

这篇关于Cassandra 中的 InvalidRequestException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆