我在Couchbase集群中创建了具有 where
条件的全局二级索引:
CREATE INDEX commentAuthorSecondaryIndex ON Bucket(author) WHERE (_class = "com.company.Comment") USING GSI;
然后我尝试通过N1QL(REST API)执行两个类似的查询:
curl --header "Content-Type:application/json" http://localhost:8093/query/service -d '
{
"$class" : "com.company.Comment",
"statement" : "select count(*) from Bucket WHERE _class = $class and author = $author",
"$author" : "author455",
"scan_consistency" : "statement_plus"
}'
并且:
curl --header "Content-Type:application/json" http://localhost:8093/query/service -d '
{
"statement" : "select count(*) from Bucket WHERE _class = \"com.company.Comment\" and author = $author",
"$author" : "author455",
"scan_consistency" : "statement_plus"
}
第一次查询快速执行4秒,而第二次查询只需20毫秒 . 当我使用 explain
关键字时,我意识到在第一个查询中Couchbase不使用索引 .
我想Couchbase首先创建查询执行计划,然后才用参数评估查询 . 因此,当创建查询计划时,Couchbase不知道可以使用索引 commentAuthorSecondaryIndex
.
有办法解决这个问题吗?
1 回答
两个选项 - 从索引中删除过滤器,或者不要在查询中使_class成为参数 . 见https://forums.couchbase.com/t/whats-the-best-approach-to-prevent-sql-injection-with-n1ql/11636/8