0

Say I have these 3 documents in a DocumentDB collection:

[
    {
        "name": "tiger",
        "keywords": [
            "animal",
            "cat",
            "stripes"
        ]
    },
    {
        "name": "cat"
    },
    {
        "keywords": [
            "panther",
            "black"
        ]
    }
]

How would I structure a single SQL query to return all documents where the 'name' matches "cat" OR a 'keyword' matches "cat" when 'keywords' and 'name' are optional elements in the document?

1 Answer 1

1

Try this query:

SELECT * FROM root r WHERE r.name = 'cat' OR ARRAY_CONTAINS(r.keywords, 'cat')

Sign up to request clarification or add additional context in comments.

2 Comments

Works great. Do you know how to modify the query so that ARRAY_CONTAINS matches partial strings in the same way as CONTAINS? At the moment ARRAY_CONTAINS must match the string exactly. For example the string "ca": SELECT * FROM root r WHERE CONTAINS(r.name,'ca') OR ARRAY_CONTAINS(r.keywords, 'ca')
ARRAY_CONTAINS performs a strict equality comparison of the search item against each item in the array. Mind you that the search item could be of any type. An alternative approach here is to do SELECT VALUE r FROM root r JOIN k IN r.keywords WHERE CONTAINS(r.name, 'ca') OR CONTAINS(k, 'ca') Please keep in mind that JOIN will flatten the keywords array and the result set is the cross product of the input documents with each item in the array. For instance, this query will return the second document twice since r.name satisfies the condition for both array items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.