python訪問Hbase雖然有很多庫,目前最好用的還是happybase。happybase文檔上手容易,但是很多高級查詢沒有一個詳盡的文檔。因此要玩轉(zhuǎn)高級查詢,還需要自己去翻閱Hbase的thrift api文檔
首先創(chuàng)建鏈接:
import happybase
conn = happybase.Connection('localhost')
table = conn.table('table_xxx')
簡單的scan查詢:
query = table.scan()
result = next(query)
scan查詢返回一個迭代器,理論上會返回一個表里面所有的結(jié)果。如果需要做限制,則需要加上limit參數(shù):
query = table.scan(limit=10)
result = list(query)
如果要查找指定列簇某個列內(nèi)容的匹配,則需要用到filter:
query_str = "SingleColumnValueFilter ('a', 'aa', =, 'substring:test')"
query = table.scan(filter=query_str, limit=10)
這里查詢列簇a的列aa的內(nèi)容是否包含'test'。
但是實際查看結(jié)果,發(fā)現(xiàn)某些不包含'aa'這個列的row也被返回了,這是因為api就是這么規(guī)定的:
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'的內(nèi)容時,需要添加過濾的參數(shù):
query_str = "SingleColumnValueFilter ('a', 'aa', =, 'substring:test', true, false)"
參數(shù)定義如下:
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大同小異。