Cassandra 中的 InvalidRequestException

2023-12-09

两天前,我在实习中开始学习 Cassandra,他们给了我一个关于 Cassandra 的学习,我从网上找到了一些代码。代码语法上没有错误,但是当我运行代码时,我收到如下错误:

InvalidRequestException(为什么:Keyspace 此架构中不存在博客。) 在 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)

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

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


/**
 * 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), "[email protected]".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();
        }
    }

}

“键空间 X 不存在”意味着......键空间不存在。键空间在 storage-conf.xml 中配置。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Cassandra 中的 InvalidRequestException 的相关文章

  • 按键时关闭 ModalWindow

    我希望能够在用户按下某个键 在我的例子中是 ESC 时关闭 ModalWindow 我有一个用于按键的 Javascript 侦听器 它调用取消按钮 ID 的单击事件 jQuery modalWindowInfo closeButtonId
  • 如何让 BlazeDS 忽略属性?

    我有一个 java 类 它有一个带有 getter 和 setter 的字段 以及第二对 getter 和 setter 它们以另一种方式访问 该字段 public class NullAbleId private static final
  • 不同帐户上的 Spring Boot、JmsListener 和 SQS 队列

    我正在尝试开发一个 Spring Boot 1 5 应用程序 该应用程序需要侦听来自两个不同 AWS 帐户的 SQS 队列 是否可以使用 JmsListener 注解创建监听器 我已检查权限是否正确 我可以使用 getQueueUrl 获取
  • 序列的排列?

    我有具体数量的数字 现在我想以某种方式显示这个序列的所有可能的排列 例如 如果数字数量为3 我想显示 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 0 2 1 0 2 2 1 0 0 1 0 1 1 0
  • 动态选择端口号?

    在 Java 中 我需要获取端口号以在同一程序的多个实例之间进行通信 现在 我可以简单地选择一些固定的数字并使用它 但我想知道是否有一种方法可以动态选择端口号 这样我就不必打扰我的用户设置端口号 这是我的一个想法 其工作原理如下 有一个固定
  • HSQL - 识别打开连接的数量

    我正在使用嵌入式 HSQL 数据库服务器 有什么方法可以识别活动打开连接的数量吗 Yes SELECT COUNT FROM INFORMATION SCHEMA SYSTEM SESSIONS
  • 如何在 Spring 中禁用使用 @Component 注释创建 bean?

    我的项目中有一些用于重构逻辑的通用接口 它看起来大约是这样的 public interface RefactorAwareEntryPoint default boolean doRefactor if EventLogService wa
  • 将流转换为 IntStream

    我有一种感觉 我在这里错过了一些东西 我发现自己做了以下事情 private static int getHighestValue Map
  • 检测并缩短字符串中的所有网址

    假设我有一条字符串消息 您应该将 file zip 上传到http google com extremelylonglink zip http google com extremelylonglink zip not https stack
  • java.lang.IllegalStateException:提交响应后无法调用 sendRedirect()

    这两天我一直在尝试找出问题所在 我在这里读到我应该在代码中添加一个返回 我做到了 但我仍然得到 java lang IllegalStateException Cannot call sendRedirect after the respo
  • MongoEngine 查询具有以列表中指定的前缀开头的属性的对象的列表

    我需要在 Mongo 数据库中查询具有以列表中任何前缀开头的特定属性的元素 现在我有一段这样的代码 query mymodel terms term in query terms 并且这会匹配在列表 term 上有一个项目的对象 该列表中的
  • Java ResultSet 如何检查是否有结果

    结果集 http java sun com j2se 1 4 2 docs api java sql ResultSet html没有 hasNext 方法 我想检查 resultSet 是否有任何值 这是正确的方法吗 if resultS
  • Java 和 Python 可以在同一个应用程序中共存吗?

    我需要一个 Java 实例直接从 Python 实例数据存储中获取数据 我不知道这是否可能 数据存储是否透明 唯一 或者每个实例 如果它们确实可以共存 都有其单独的数据存储 总结一下 Java 应用程序如何从 Python 应用程序的数据存
  • logcat 中 mSecurityInputMethodService 为 null

    我写了一点android应显示智能手机当前位置 最后已知位置 的应用程序 尽管我复制了示例代码 并尝试了其他几种解决方案 但似乎每次都有相同的错误 我的应用程序由一个按钮组成 按下按钮应该log经度和纬度 但仅对数 mSecurityInp
  • Cucumber 0.4.3 (cuke4duke) 与 java + maven gem 问题

    我最近开始为 Cucumber 安装一个示例项目 并尝试使用 maven java 运行它 我遵循了这个指南 http www goodercode com wp using cucumber tests with maven and ja
  • 干净构建 Java 命令行

    我正在使用命令行编译使用 eclipse 编写的项目 如下所示 javac file java 然后运行 java file args here 我将如何运行干净的构建或编译 每当我重新编译时 除非删除所有内容 否则更改不会受到影响 cla
  • 找不到符号 NOTIFICATION_SERVICE?

    package com test app import android app Notification import android app NotificationManager import android app PendingIn
  • 长轮询会冻结浏览器并阻止其他 ajax 请求

    我正在尝试在我的中实现长轮询Spring MVC Web 应用程序 http static springsource org spring docs 2 0 x reference mvc html但在 4 5 个连续 AJAX 请求后它会
  • CamcorderProfile.videoCodec 返回错误值

    根据docs https developer android com reference android media CamcorderProfile html 您可以使用CamcorderProfile获取设备默认视频编解码格式 然后将其
  • Spring Rest 和 Jsonp

    我正在尝试让我的 Spring Rest 控制器返回jsonp但我没有快乐 如果我想返回 json 但我有返回的要求 完全相同的代码可以正常工作jsonp我添加了一个转换器 我在网上找到了用于执行 jsonp 转换的源代码 我正在使用 Sp

随机推荐