Querying
Being able to store and access data based on a key is great, but sometimes you need more than that. Coherence allows you to query on any data attribute present in your data model, and even allows you to define your own query filter if one of the built-in ones doesn’t fit the bill. If you defined an index for a given query attribute, it will be used to optimize the query execution and avoid unnecessary deserialization.
See the utility class Filters for the filters supported out-of-the-box by this client.
The following example demonstrates various querying operations against a NamedMap:
1# Copyright (c) 2023, Oracle and/or its affiliates.
2# Licensed under the Universal Permissive License v 1.0 as shown at
3# https://oss.oracle.com/licenses/upl.
4
5import asyncio
6from dataclasses import dataclass
7from typing import List
8
9from coherence import Filters, NamedMap, Session
10from coherence.filter import Filter
11
12
13@dataclass
14class Hobbit:
15 """
16 A simple class representing a Hobbit.
17 """
18
19 id: int
20 name: str
21 age: int
22 home: str
23
24
25async def do_run() -> None:
26 """
27 Demonstrates various Filter operations against a NamedMap.
28
29 :return: None
30 """
31 session: Session = await Session.create()
32 try:
33 homes: List[str] = ["Hobbiton", "Buckland", "Frogmorton", "Stock"]
34 named_map: NamedMap[int, Hobbit] = await session.get_map("hobbits")
35
36 await named_map.clear()
37
38 num_hobbits: int = 20
39 print("Adding", num_hobbits, "random Hobbits ...")
40 for i in range(num_hobbits):
41 await named_map.put(i, Hobbit(i, "Hobbit-" + str(i), 15 + i, homes[i % 4]))
42
43 print("NamedMap size is :", await named_map.size())
44
45 print("Retrieve the Hobbits between the ages of 17 and 21 ...")
46 async for entry in named_map.entries(Filters.between("age", 17, 21)):
47 print("Key :", entry.key, ", Value :", entry.value)
48
49 print("Retrieve the Hobbits between the ages of 17 and 30 and live in Hobbiton ...")
50 query_filter: Filter = Filters.between("age", 17, 30).And(Filters.equals("home", "Hobbiton"))
51 async for entry in named_map.entries(query_filter):
52 print("Key :", entry.key, ", Value :", entry.value)
53
54 print("Retrieve the Hobbits between the ages of 17 and 25 who live in Hobbiton or Frogmorton")
55 query_filter = Filters.between("age", 17, 25).And(Filters.is_in("home", {"Hobbiton", "Frogmorton"}))
56 async for entry in named_map.entries(query_filter):
57 print("Key :", entry.key, ", Value :", entry.value)
58
59 finally:
60 await session.close()
61
62
63asyncio.run(do_run())
Lines 40-41 - insert twenty random Hobbits
Line 46 - find all Hobbits, including their associated key, between the age of 17 and 21
Line 50 - find all Hobbits, including their associated key, between the age of 17 and 30 that live in Hobbiton
Line 55 - find all Hobbits, including their associated key, between the age of 17 and 25 that live in Hobbiton or Frogmorton