如何优化Couchbase NQ1L ORDER BY

时间:2017-03-07 14:08:31

标签: couchbase

考虑以下用例:

索引

CREATE INDEX `type-index`ON bucket( type, createdAt) WHERE type='someType';

查询(表现相当不错)

SELECT a.*
FROM `bucket` a
WHERE a.tyoe='someType'
LIMIT 10 OFFSET 10

执行:14.51ms

查询(执行非常糟糕)

SELECT a.*
FROM `bucket` a
WHERE a.tyoe='someType'
ORDER BY a.createdAt DESC
LIMIT 10 OFFSET 10

执行:1米

这是EXPLAIN

[
  {
    "plan": {
      "#operator": "Sequence",
      "~children": [
        {
          "#operator": "Sequence",
          "~children": [
            {
              "#operator": "IndexScan",
              "index": "type-index",
              "index_id": "ee6b75813c26795c",
              "keyspace": "bucket",
              "namespace": "default",
              "spans": [
                {
                  "Range": {
                    "High": [
                      "successor(\"someType\")"
                    ],
                    "Inclusion": 1,
                    "Low": [
                      "\"someType\""
                    ]
                  }
                }
              ],
              "using": "gsi"
            },
            {
              "#operator": "Parallel",
              "~child": {
                "#operator": "Sequence",
                "~children": [
                  {
                    "#operator": "Fetch",
                    "as": "a",
                    "keyspace": "bucket",
                    "namespace": "default"
                  },
                  {
                    "#operator": "Filter",
                    "condition": "((`a`.`_type`) = \"someType\")"
                  },
                  {
                    "#operator": "InitialProject",
                    "result_terms": [
                      {
                        "expr": "`a`",
                        "star": true
                      }
                    ]
                  }
                ]
              }
            }
          ]
        },
        {
          "#operator": "Order",
          "limit": "10",
          "offset": "10",
          "sort_terms": [
            {
              "desc": true,
              "expr": "(`a`.`createdAt`)"
            }
          ]
        },
        {
          "#operator": "Offset",
          "expr": "10"
        },
        {
          "#operator": "Limit",
          "expr": "10"
        },
        {
          "#operator": "FinalProject"
        }
      ]
    },
    "text": "SELECT a.* FROM `bucket` a WHERE a.type='someType' ORDER BY a.createdAt DESC IMIT 10 OFFSET 10"
  }
]

该存储桶包含1.7M文档。有没有办法如何提高ORDER BY的性能?值createdAt是unix时间戳(数字)

1 个答案:

答案 0 :(得分:0)

解决方案是创建一个这样的索引:

CREATE INDEX `type-index` ON bucket ( -createdAt ) WHERE type='sometType';

和查询

SELECT a.*
FROM `bucket` a
WHERE type='someType'
AND -createdAt IS NOT NULL
ORDER BY -createdAt
LIMIT 10 OFFSET 10;