如何使用CQL语句查询指定表主键/Clustering列名,适配CassandraRepository?
Cassandra查询表主键/集群键的可行方案
你之前的写法不可行:DESCRIBE是cqlsh客户端的专属辅助命令,不属于标准原生CQL语法,Spring Data Cassandra的@Query注解执行CQL时不支持该指令,就算能执行返回的也是非结构化文本,无法直接解析字段。
方案1:基于Spring Data Cassandra元数据API获取(最推荐)
Spring Data Cassandra本身已经加载了所有实体的表结构元数据,直接通过CassandraMappingContext即可读取,不需要额外发查询请求:
@Autowired private CassandraMappingContext cassandraMappingContext; // 传入你要查询的实体类即可获取对应表的键信息 public void getTableKeys(Class<?> entityClass) { CassandraPersistentEntity<?> entity = cassandraMappingContext.getRequiredPersistentEntity(entityClass); // 仅分区键字段 List<CassandraPersistentProperty> partitionKeyProperties = entity.getPartitionKeyProperties(); // 仅集群键字段 List<CassandraPersistentProperty> clusteringKeyProperties = entity.getClusteringKeyProperties(); // 所有主键字段(分区键+集群键的集合) List<CassandraPersistentProperty> primaryKeyProperties = entity.getPrimaryKeyProperties(); // 示例:遍历拿集群键的实际表列名 for (CassandraPersistentProperty prop : clusteringKeyProperties) { String columnName = prop.getColumnName().toCql(); System.out.println("集群键列名:" + columnName); } }
方案2:查询system_schema系统表获取
如果需要查询非当前项目映射实体的第三方表结构,可以直接查询Cassandra内置的system_schema.columns系统表,该查询是标准CQL,所有版本都支持。
对应Repository写法如下:
@Query(value = "SELECT column_name, kind FROM system_schema.columns WHERE keyspace_name = ?0 AND table_name = ?1", nativeQuery = true) List<Map<String, Object>> getTableColumnsMetadata(String keyspace, String tableName);
返回结果中kind字段的取值对应关系:
partition_key:分区键clustering:集群键regular:普通非主键字段
遍历返回的List即可筛选出你需要的列名。
内容的提问来源于stack exchange,提问作者Soumav
相关产品推荐
相关产品推荐

