Bug: index on an array field gives `acl = x` two answers (count 1, rows none), and `CONTAINS`/`CONTAINSANY` never use it
What component does this affect?
SurrealDB Server
Describe the bug
With a standard index on an array<string> field, the same equality predicate returns different answers depending on the plan:
SELECT count() … WHERE acl = 'a' GROUP ALLis planned asIndexCountScanand returns 1. The index holds one entry per element, so it counts the record whose array contains'a'.SELECT … WHERE acl = 'a'is planned asIndexScanon the same index and returns no rows, which matches comparing the whole array with a string.- Without the index, the count is 0.
So adding an index changes a query's result, and the count and the rows it counts disagree. acl = 'a' OR acl = 'c' behaves like the row query (UnionIndexScan, no rows).
Separately, the membership operators that match what the index stores, CONTAINS and CONTAINSANY, are always planned as a TableScan and never use the index. In practice, an index on an array field can't speed up membership queries, but it can change what an equality or count returns.
Seen on 3.2.4 and unchanged on 3.3.0.
Steps to reproduce
DEFINE TABLE r SCHEMAFULL;
DEFINE FIELD acl ON r TYPE array<string>;
DEFINE INDEX r_acl ON r FIELDS acl;
CREATE r:1 SET acl = ['a', 'b'];
CREATE r:2 SET acl = ['c'];
SELECT count() FROM r WHERE acl = 'a' GROUP ALL; -- [{ count: 1 }] IndexCountScan
SELECT VALUE id FROM r WHERE acl = 'a'; -- [] IndexScan r_acl = 'a'
SELECT VALUE id FROM r WHERE acl = 'a' OR acl = 'c'; -- [] UnionIndexScan + Filter
SELECT VALUE id FROM r WHERE acl CONTAINS 'a'; -- [r:1] TableScan
SELECT VALUE id FROM r WHERE acl CONTAINSANY ['a', 'c']; -- [r:1, r:2] TableScan
REMOVE INDEX r_acl ON r;
SELECT count() FROM r WHERE acl = 'a' GROUP ALL; -- [{ count: 0 }](Plans from EXPLAIN of each statement.)
Expected behaviour
A predicate returns the same result whichever plan runs it, and with or without an index. acl = 'a' on an array is either always false (count 0), or consistently means membership. And CONTAINS / CONTAINSANY on an indexed array field use the index, since its per-element entries answer exactly that.
SurrealDB version
3.3.0 for macos on aarch64 (also surrealdb/surrealdb:v3.3.0, 3.3.0 for linux on aarch64; first seen on 3.2.4)
Contact Details
No response
Could this be a bug with your application?
- I confirm this is a bug with SurrealDB, not with my own application
Is there an existing issue for this?
- I confirm that I have searched the existing issues
Code of Conduct
- I agree to follow this project's Code of Conduct
Source: surrealdb/surrealdb