# hscan

### 1. 基本語法

#### hsca&#x6E;**(`hkey`,  `cursor`, `['MATCH', pattern]`, `['COUNT', count]`,`callback`)**&#x20;

針&#x5C0D;**`hkey`**&#x8CC7;料進行漸進式的[遍歷(**Traversal**)](https://zh.wikipedia.org/wiki/%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86)取值，透&#x904E;**`MATCH`**&#x53C3;數篩選欄位(Sub-Key)資料，該指令**不保證**回傳的鍵值對(Sub-Key : Value)數量，但可透&#x904E;**`COUNT`**&#x5236;定最少的回傳數目，並透過新&#x7684;**`cursor`**&#x4F86;取得下一群資料內容，&#x7576;**`cursor`**&#x7B49;&#x65BC;**'0'**&#x6642;，代表遍歷已結束。

| Parameter     | Default  |
| ------------- | -------- |
| **`pattern`** | **'\*'** |
| **`count`**   | **'10'** |

{% hint style="info" %}
以下兩者任一成立時，**`COUNT`**&#x53C3;數才會發會作用。

* &#x7576;**`hkey`**&#x4E2D;的鍵值對(**Sub-Key** : **Value**)數量超過512的時候。
* &#x7576;**`hkey`**&#x4E2D;任意一個欄位(**Sub-Key**)對應的資料(**Value**)長度超過64。
  {% endhint %}

### 2. 範例

#### (1) 預設參數會試圖取得所&#x6709;**`hkey`**&#x8CC7;料

&#x82E5;**`hkey`**&#x5C0D;應欄位(**Sub-Key**)過多，則先回傳部分資料及非零**cursor**，並得以透過新**cursor**取得下一&#x7D44;**`hkey`**&#x8CC7;料

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const dict = { 
    name: 'John Miller', 
    gender: 'M', 
    age: '34',
    hobby1 : 'Whistle',
    hobby2 : 'War',
    hobby3 : 'Walk'
};

client.hmset('user:5', dict);

let cursor = '0';
client.hscan('user:5', cursor , (err, scanner) => {
    cursor = scanner[0];
    let kv_list = scanner[1];
    console.log('Cursor:', cursor);
    console.log('Data:', kv_list);
});
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output-TS" %}

```
Cursor: 0
Data: [
  'name',   'John Miller',
  'gender', 'M',
  'age',    '34',
  'hobby1', 'Whistle',
  'hobby2', 'War',
  'hobby3', 'Walk'
]
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
注意回傳結果為Array形式
{% endhint %}

#### (2) 模糊篩選subkey

{% tabs %}
{% tab title="TypeScript" %}

```typescript
let cursor = '0';
client.hscan('user:5', cursor, 'MATCH', 'hobby*', 'COUNT', '10', 
    (err, scanner) => {
        let cursor = scanner[0];
        let kv_list = scanner[1];
        console.log('Next Cursor:', cursor);
        console.log('Cuurent Data:', kv_list);
    }
);
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output-TS" %}

```
Cursor: 0
Data: [ 'hobby1', 'Whistle', 'hobby2', 'War', 'hobby3', 'Walk' ]
```

{% endtab %}
{% endtabs %}
