Example_cel_Collections showcases membership, indexing, search (exists), all, and filter on complex collections as documented in https://celbyexample.com/collections/
()
| 24 | // Example_cel_Collections showcases membership, indexing, search (exists), all, and filter |
| 25 | // on complex collections as documented in https://celbyexample.com/collections/ |
| 26 | func Example_cel_Collections() { |
| 27 | orderData := map[string]any{ |
| 28 | "id": "ord-123", |
| 29 | "customer": "alice@example.com", |
| 30 | "tags": []string{"express", "gift-wrapped"}, |
| 31 | "items": []map[string]any{ |
| 32 | {"name": "Laptop", "category": "electronics", "price": 999, "quantity": 1}, |
| 33 | {"name": "Cable", "category": "accessories", "price": 29, "quantity": 3}, |
| 34 | }, |
| 35 | "status": "pending", |
| 36 | } |
| 37 | |
| 38 | exprs := []string{ |
| 39 | `"express" in order.tags`, |
| 40 | `size(order.tags)`, |
| 41 | `size(order.items)`, |
| 42 | `order.tags[0]`, |
| 43 | `order.items[0].name`, |
| 44 | `order.items[0].price`, |
| 45 | `order.tags.exists(t, t.startsWith("ex"))`, |
| 46 | `order.items.exists(i, i.price > 500)`, |
| 47 | `order.items.exists(i, i.category == "electronics" && i.price > 100)`, |
| 48 | `order.tags.all(t, size(t) > 0)`, |
| 49 | `order.items.all(i, i.quantity > 0)`, |
| 50 | `order.items.all(i, i.price < 10000)`, |
| 51 | `order.tags.filter(t, t != "express")`, |
| 52 | `order.items.filter(i, i.price > 100)[0].name`, |
| 53 | `order.items.filter(i, i.category == "electronics")[0].name`, |
| 54 | } |
| 55 | |
| 56 | for _, expr := range exprs { |
| 57 | prg, err := cel.Compile(expr, cel.Variable("order", cel.DynType)) |
| 58 | if err != nil { |
| 59 | log.Fatalf("cel.Compile() error for %q: %v", expr, err) |
| 60 | } |
| 61 | out, _, err := prg.Eval(map[string]any{"order": orderData}) |
| 62 | if err != nil { |
| 63 | log.Fatalf("prg.Eval() error for %q: %v", expr, err) |
| 64 | } |
| 65 | fmt.Printf("%s -> %v\n", expr, out) |
| 66 | } |
| 67 | |
| 68 | // Output: |
| 69 | // "express" in order.tags -> true |
| 70 | // size(order.tags) -> 2 |
| 71 | // size(order.items) -> 2 |
| 72 | // order.tags[0] -> express |
| 73 | // order.items[0].name -> Laptop |
| 74 | // order.items[0].price -> 999 |
| 75 | // order.tags.exists(t, t.startsWith("ex")) -> true |
| 76 | // order.items.exists(i, i.price > 500) -> true |
| 77 | // order.items.exists(i, i.category == "electronics" && i.price > 100) -> true |
| 78 | // order.tags.all(t, size(t) > 0) -> true |
| 79 | // order.items.all(i, i.quantity > 0) -> true |
| 80 | // order.items.all(i, i.price < 10000) -> true |
| 81 | // order.tags.filter(t, t != "express") -> [gift-wrapped] |
| 82 | // order.items.filter(i, i.price > 100)[0].name -> Laptop |
| 83 | // order.items.filter(i, i.category == "electronics")[0].name -> Laptop |