2017-08-29 72 views
0

我正在通過learn.coucbase.com上提供的N1QL免費CB110課程。Couchbase DISTINCT非常慢

在課程的隨行工作簿下面的查詢需要1分鐘:

SELECT DISTINCT address.countryCode 
FROM couchmusic2 
WHERE email LIKE "%hotmail.com"; 

我有電子郵件的GSI。

下面的查詢需要毫秒:

SELECT COUNT(*) 
FROM couchmusic2 
WHERE email LIKE "%hotmail.com"; 

其中有我相信,DISTINCT的問題。

EXPLAIN揭示了這一點:

[ 
    { 
    "plan": { 
     "#operator": "Sequence", 
     "~children": [ 
     { 
      "#operator": "IndexScan", 
      "index": "idx_email", 
      "index_id": "c2e612a0d697d8b6", 
      "keyspace": "couchmusic2", 
      "namespace": "default", 
      "spans": [ 
      { 
       "Range": { 
       "High": [ 
        "[]" 
       ], 
       "Inclusion": 1, 
       "Low": [ 
        "\"\"" 
       ] 
       } 
      } 
      ], 
      "using": "gsi" 
     }, 
     { 
      "#operator": "Fetch", 
      "keyspace": "couchmusic2", 
      "namespace": "default" 
     }, 
     { 
      "#operator": "Parallel", 
      "~child": { 
      "#operator": "Sequence", 
      "~children": [ 
       { 
       "#operator": "Filter", 
       "condition": "((`couchmusic2`.`email`) like \"%hotmail.com\")" 
       }, 
       { 
       "#operator": "InitialProject", 
       "distinct": true, 
       "result_terms": [ 
        { 
        "expr": "((`couchmusic2`.`address`).`countryCode`)" 
        } 
       ] 
       }, 
       { 
       "#operator": "Distinct" 
       }, 
       { 
       "#operator": "FinalProject" 
       } 
      ] 
      } 
     }, 
     { 
      "#operator": "Distinct" 
     } 
     ] 
    }, 
    "text": "\nSELECT DISTINCT address.countryCode \nFROM couchmusic2 \nWHERE email LIKE \"%hotmail.com\";" 
    } 
] 

爲什麼查詢這麼慢?我如何加快查詢速度?

回答

0

對於模式的所有字符串與hotmail.com結尾匹配,做到以下幾點:

CREATE INDEX ON第九couchmusic2(SUBSTR(電子郵件,-11,11),address.countryCode);

將LIKE謂詞修改爲:WHERE SUBSTR(email,-11,11)=「hotmail.com」; 顯然,這僅適用於hotmail.com,您需要另一個索引。

Checkout TOKENS()函數以更靈活的方式對此進行索引。爲了得到不同的值(當你有很大數量的項目與不同值的數量進行比較時),嘗試MIN()優化以及它。 https://dzone.com/articles/count-amp-group-faster-using-n1ql