用python對Hbase進行高級查詢

python訪問Hbase雖然有很多庫,目前最好用的還是happybase。happybase文檔上手容易,但是很多高級查詢沒有一個詳盡的文檔。因此要玩轉高級查詢,還需要自己去翻閱Hbase的thrift api文檔

首先創建鏈接:

import happybase
conn = happybase.Connection('localhost')
table = conn.table('table_xxx')

簡單的scan查詢:

query = table.scan()
result = next(query)

scan查詢返回一個迭代器,理論上會返回一個表里面所有的結果。如果需要做限制,則需要加上limit參數:

query = table.scan(limit=10)
result = list(query)

如果要查找指定列簇某個列內容的匹配,則需要用到filter:

query_str = "SingleColumnValueFilter ('a', 'aa', =, 'substring:test')"
query = table.scan(filter=query_str, limit=10)

這里查詢列簇a的列aa的內容是否包含'test'。

但是實際查看結果,發現某些不包含'aa'這個列的row也被返回了,這是因為api就是這么規定的:

This filter takes a column family, a qualifier, a compare operator and a comparator. If the specified column is not found – all the columns of that row will be emitted. If the column is found and the comparison with the comparator returns true, all the columns of the row will be emitted. If the condition fails, the row will not be emitted.

所以在需要過濾掉這些不包含'aa'的內容時,需要添加過濾的參數:

query_str = "SingleColumnValueFilter ('a', 'aa', =, 'substring:test', true, false)"

參數定義如下:

SingleColumnValueFilter('<family>', '<qualifier>', <compare operator>, '<comparator>', <filterIfColumnMissing_boolean>, <latest_version_boolean>)

這個在Hbase的thrift api里面沒有直接提及,但是在例子里有。感覺真是坑。。。

多個filter的邏輯組合:

query_str = "SingleColumnValueFilter ('a', 'aa', =, 'substring:test', true,false) OR SingleColumnValueFilter ('a', 'aa', =, 'substring:check', true, false)"

這樣能查詢出a.aa這個列里面包含test或者check的row。

上面的邏輯還可以通過一個正則來搞定:

query_str = "SingleColumnValueFilter ('a', 'aa', =, 'regexstring:(test|check).com', true, false)"

filter匹配方式還有binary,binaryprefix。而filter還有RowFilter, ValueFilter等,這里就需要自己參考thrift文檔來搞了,基本上和SingleColumnValueFilter大同小異。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容