Giving the following index:
CREATE INDEX idx_event_type_join ON DATA (ifmissingornull(eventTypeId, configurableMetadataId)) WHERE (type = "EVENT")
I have a complexe query using this index that I will simplify here for the purpose of the example:
SELECT DISTINCT RAW event.visitId FROM DATA event
WHERE event.`type` = 'EVENT'
AND IFMISSINGORNULL(event.eventTypeId, event.configurableMetadataId) IN ['ET_CONSULTATION_EXT', 'ET_CONSULTATION_NUTRITION', 'ET_CONSULTATION_KINE', 'ET_CONSULTATION_OPHT']
Running this query is ok but if I replace the last line by this:
AND IFMISSINGORNULL(event.eventTypeId, event.configurableMetadataId) IN
ARRAY_FLATTEN(
(
SELECT RAW ARRAY_ADD(IFMISSINGORNULL(vdo.options, []), META().id)
FROM METADATA vdo USE KEYS ['ALL_CONSULT']
),
2
)
The query execution time is then ~20x slower.
The subquery is returning the exact same thing as if I was using the hardcoded version of the query:
SELECT RAW ARRAY_FLATTEN((SELECT RAW ARRAY_ADD(IFMISSINGORNULL(vdo.options, []), META().id) FROM METADATA vdo USE KEYS ['SNIS_ALL_CONSULT']), 2)
I saw that the both queries are using the index idx_event_type_join
but the second one has spans with an inclusion
of 0 and low
to null.
Here is te comparaison between the first and the second query plan (extracting only what is relevant here, if you need more please tell me):
First query plan (without subquery)
{
"#operator": "IndexScan2",
"index": "idx_event_type_join",
"index_id": "9e35a46cfe282ef2",
"index_projection": {
"primary_key": true
},
"keyspace": "DATA",
"namespace": "default",
"spans": [
{
"exact": true,
"range": [
{
"high": "\"ET_CONSULTATION_EXT\"",
"inclusion": 3,
"low": "\"ET_CONSULTATION_EXT\""
}
]
},
{
"exact": true,
"range": [
{
"high": "\"ET_CONSULTATION_KINE\"",
"inclusion": 3,
"low": "\"ET_CONSULTATION_KINE\""
}
]
},
{
"exact": true,
"range": [
{
"high": "\"ET_CONSULTATION_NUTRITION\"",
"inclusion": 3,
"low": "\"ET_CONSULTATION_NUTRITION\""
}
]
},
{
"exact": true,
"range": [
{
"high": "\"ET_CONSULTATION_OPHT\"",
"inclusion": 3,
"low": "\"ET_CONSULTATION_OPHT\""
}
]
}
],
"using": "gsi"
}
Second query plan (with subquery)
{
"#operator": "IndexScan2",
"index": "idx_event_type_join",
"index_id": "9e35a46cfe282ef2",
"index_projection": {
"primary_key": true
},
"keyspace": "DATA",
"namespace": "default",
"spans": [
{
"range": [
{
"inclusion": 0,
"low": "null"
}
]
}
],
"using": "gsi"
}
I’m using Couchbase Server Community Edition 5.1.1 build 5723
Thanks for the help.