如何使用 YCQL 查询返回特定平板电脑

问题描述

使用 YCQL,我需要在查询添加什么才能返回结果所在的特定平板电脑?

[免责声明]:这个问题最初是在 YugabyteDB 社区 Slack 频道上提出的。

解决方法

要确定一行落在哪个分区,您可以将分区列(在主键中)提供给 partition_hash 函数并取回哈希码。

ycqlsh:k> create table t(k text primary key,v text);
ycqlsh:k> insert into t(k,v) values ('a','1');
ycqlsh:k> insert into t(k,v) values ('b','2');
ycqlsh:k> insert into t(k,v) values ('c','3');
ycqlsh:k> select partition_hash(k),k,v from t;
partition_hash(k) | k | v
-------------------+---+---
            27916 | c | 3
            44389 | a | 1
            60372 | b | 2

这必须与 system.partitions 表中的信息相匹配,以确定特定哈希码将落在哪个分区/平板电脑中。[请参阅进一步的示例查询。] 这是多列主数据库的另一个示例键,其中只有 user_id 列是分区列。

ycqlsh:k> CREATE TABLE IF NOT EXISTS msgs(
          user_id     text,msg_id integer,msg    text,PRIMARY KEY((user_id),msg_id)
       );
ycqlsh:k> insert into msgs(user_id,msg_id,msg) VALUES ('A',1,'foo');
ycqlsh:k> insert into msgs(user_id,2,'bar');
ycqlsh:k> insert into msgs(user_id,3,'jar');
ycqlsh:k> insert into msgs(user_id,msg) VALUES ('B','jar');
ycqlsh:k> select partition_hash(user_id),user_id,msg from msgs;
partition_hash(user_id) | user_id | msg_id | msg
-------------------------+---------+--------+-----
                  44013 |       A |      1 | foo
                  44013 |       A |      2 | bar
                  44013 |       A |      3 | jar
                  52014 |       B |      1 | foo
                  52014 |       B |      2 | bar
                  52014 |       B |      3 | jar
(6 rows)

partition_hash 返回的值在 [0..64K) 空间中,为了将这些映射回平板电脑,可以查询 system.partitions 表。例如,

ycqlsh:k> select * from system.partitions where keyspace_name = 'k';
keyspace_name | table_name | start_key | end_key | id                                   | replica_addresses
---------------+------------+-----------+---------+--------------------------------------+-------------------------
            k |       msgs |        0x |  0x7fff | 58097f2e-967f-d785-3a42-f647b498ef08 | {'127.0.0.1': 'LEADER'}
            k |       msgs |    0x7fff |      0x | f7f2a64e-5bf2-fbba-554f-d26008c02bcc | {'127.0.0.1': 'LEADER'}
            k |          t |        0x |  0x7fff | 15363091-6577-9aa6-584c-64304cec7f6e | {'127.0.0.1': 'LEADER'}
            k |          t |    0x7fff |      0x | 0d4e2bcc-ac97-bd9e-8148-7bedb7c4bd86 | {'127.0.0.1': 'LEADER'}

当您使用 partition_hash 时,在您查询 system.partitions 后,您只需要找到 partition_hash 值落在 {{} 中开始和结束键范围内的位置1}} 响应。请记住,start_key 是包含的,end_key 是不包含的。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...