CosmosDB: string array e WHERE condition

Sapevate che anche in CosmosDB e’ possibile effettuare delle query cercando dentro un array del nostro documento? In questo articolo andremo a vedere il modo “pulito” indicato nella documentazione e non eventuali workaround trovati in rete.

Template documento

Per farvi capire meglio la situazione di partenza, vi illustro come e’ rappresentato il modello all’interno del container in CosmosDB.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
    "Id": "390448f3-589b-411f-b806-6bc59595eb80",
    "Items": [
        {
            "id": "dc0025f1-11ad-4978-bec4-a57c275ba64c"
        },
        {
            "id": "5afc575c-2e58-4210-9f7b-719ed4bcbc78"
        },
        {
            "id": "876267a2-b2c5-4ba8-b6fb-f388d341d91d"
        }
    ]
}

ARRAY_CONTAINS

Il nostro obiettivo e’ quello di trovare il documento (oppure i documenti) dove (per dirla alla simil-linq) Items.Id == VALORE. Come fare? In questo caso viene in nostro aiuto ARRAY_CONTAINS

Returns a Boolean indicating whether the array contains the specified value. You can check for a partial or full match of an object by using a boolean expression within the command.

La sua sintassi di base e’ la seguente

1
ARRAY_CONTAINS (<arr_expr>, <expr> [, bool_expr])  
  • arr_expr: Is the array expression to be searched.

  • expr: Is the expression to be found.

  • bool_expr: Is a boolean expression. If it evaluates to ‘true’ and if the specified search value is an object, the command checks for a partial match (the search object is a subset of one of the objects). If it evaluates to ‘false’, the command checks for a full match of all objects within the array. The default value if not specified is false.

Esempio pratico

Per risolvere il nostro problema iniziale ci bastera’ effettuare la seguente query

1
2
3
4
SELECT * 
    FROM c
    WHERE 
        ARRAY_CONTAINS(c.Items, {id: 'dc0025f1-11ad-4978-bec4-a57c275ba64c'})

A questo punto come elementi di ritorno troverete tutti gli Items che al loro interno hanno Id pari al valore indicati.