![](/img/trans.png)
[英]How to insert in Cassandra into Composite Columns using Astyanax client?
[英]How to retrieve selected columns given a rowkey using Astyanax/Netflix client?
我在本地設置了一個節點集群。 現在我正在嘗試從Cassandra讀取數據。 我是Astyanax(Cassandra的Netflix客戶)的新手。
目前我所看到的是 - 你可以在rowkey上請求數據。 rowkey的含義基礎我可以檢索不是我想要的所有列。
但我正在尋找的是 - 我將擁有rowkey和幾個columnsNames。 因此,基於該rowkey,我只需要檢索這些列。 像這樣的東西 -
SELECT colA, colB from table1 where rowkey = "222";
下面是我在rowkey上檢索所有列名稱的方法。 如何在給定行鍵的情況下僅檢索選定的列?
public void read(final String userId, final Collection<String> columnNames) {
OperationResult<ColumnList<String>> result;
try {
result = CassandraConnection.getInstance().getKeyspace().prepareQuery(CassandraConnection.getInstance().getEmp_cf())
.getKey(userId)
.execute();
ColumnList<String> cols = result.getResult();
for(Iterator<Column<String>> i = cols.iterator(); i.hasNext(); ) {
Column<String> c = i.next();
Object v = null;
if(c.getName().endsWith("id")) // type induction hack
v = c.getIntegerValue();
else
v = c.getStringValue();
System.out.println("- col: '"+c.getName()+"': "+v);
}
} catch (ConnectionException e) {
System.out.println("failed to read from C*" +e);
throw new RuntimeException("failed to read from C*", e);
}
}
在上面的代碼中, Collection<String> columnNames
將有幾個我想要請求的列名。
誰能告訴我在上面的方法中我需要做些什么改變?
要檢索astyanax中的選定列,我們必須使用列切片。
List<String> columns = Arrays.asList(new String[]{"col1","col2","col3"});
OperationResult<ColumnList<String>> result = CassandraConnection.getInstance().getKeyspace()
.prepareQuery(CassandraConnection.getInstance().getEmp_cf())
.getKey(userId).withColumnSlice(columns)
.execute();
ColumnList<String> columnList= result.getResult();
for(String col : columns ){
System.out.println(columnList.getColumnByName(col).getStringValue());
}
我假設所有列都是文本類型,因此使用getStringValue()
,您可以根據cf元數據獲取它。
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.