I have a database that has documents with a Version property and Tier property
example:
{
id: "1055984d-01bd-4fbf-877f-0c18ce91552e",
Version: 1,
Tier: "basic"
},
{
id: "1055984d-01bd-4fbf-877f-0c18ce91552e",
Version: 2,
Tier: "standard"
}
I want to be able to query my documents to find which ids have a Version=1 and Tier=basic and also have a Version=2 and Tier=standard.
I’ve tried to write a query like this:
select c.id from c
where (c.Version = 1 and c.TierId = "basic")
AND (c.Version = 2 and c.TierId = "standard")
I don’t get any results back though. I think it’s looking for a specific doc that has both version 1 and version 2. Is there a way I can update my query where it doesn’t use the AND
?
2
Answers
First, note that you cannot have duplicate
id
values, as every document must have a uniqueid
(the exception being when the sameid
is used in different partitions, meaning you have a partition key other than/id
). So the sample data you gave above isn’t really valid. You’d need a different guid for each.Now for the query. You’ve created an impossible situation, where a document has two different sets of values. Rather than using
AND
, combine your checks withOR
. Something like:This will result in a set of
id
for documents that meet either of the conditions.As David’s answer says your example is bad as
id
is unique within a partition and you haven’t given us any reason to think that different "versions" will be in different partitions.I assume that it is "docid" below.
The below gets kind of close (If
Condition1Met
andCondition2Met
are both1
then documents meeting both of the conditions were present for adocid
)But in practice unless the collection and result set are small this is unlikely to be suitable as "You can’t use continuation tokens for queries with GROUP BY".
(maybe you could use a home made keyset pagination approach though and tack on an
ORDER BY c.docid
and add a condition to theWHERE
that the next batch should be>
than the highest seen in the previous batch)I think the best options are.
WHERE
clause with allOR
-ed conditions, ordered bydocid
, and projecting thedocid
,Version
, andTier
properties. And have client code process this and keep track whilst iterating through this for eachdocid
seen which condition(s) they matched – and use this to find thedocid
matching both conditions.