|
1 | 1 | """ |
2 | | -Example 3: Querying Entities with Filters |
| 2 | +Example 5: Querying Entities with Filters |
3 | 3 |
|
4 | 4 | This example demonstrates: |
5 | 5 | - Creating multiple entities |
6 | | -- Querying with filters (owner, content type) |
| 6 | +- Querying with the fluent query builder |
| 7 | +- Filtering with typed attributes |
7 | 8 | - Sorting results |
8 | | -- Pagination |
9 | 9 |
|
10 | | -Run this example: uv run python -m arkiv_starter.03_queries |
| 10 | +Run this example: uv run python -m arkiv_starter.05_queries |
11 | 11 | """ |
12 | 12 |
|
13 | | -from arkiv.provider import ProviderBuilder |
14 | | -from arkiv import Arkiv, NamedAccount |
15 | | -from arkiv.node import ArkivNode |
16 | | -from arkiv.types import OrderByAttribute, QueryOptions, INT, DESC, Attributes |
| 13 | +from arkiv import Arkiv, IntAttr, IntSort, StrAttr |
| 14 | +from arkiv.types import DESC, Attributes |
17 | 15 |
|
18 | 16 | # Setup: Start node and create client |
19 | 17 | print("π Starting local Arkiv node and client ...") |
|
50 | 48 | entities.append(entity_key) |
51 | 49 | print(f" Created JSON entity: {entity_key}") |
52 | 50 |
|
| 51 | +# Query 1: Retrieve all entities with details |
| 52 | +# Define typed attributes |
| 53 | +owner = StrAttr("$owner") |
| 54 | +idx = IntAttr("idx") |
| 55 | + |
53 | 56 | print(f"\nπ Query 1: Retrieving all entities with details...") |
54 | | -all_with_details = list(client.arkiv.query_entities(f'$owner = "{account}"')) |
| 57 | +all_with_details = list(client.arkiv.select().where(owner == account).fetch()) |
55 | 58 | print(f"β
Found {len(all_with_details)} entities:") |
56 | 59 | for entity in all_with_details: |
57 | 60 | if entity.payload: |
58 | 61 | content = entity.payload.decode('utf-8') |
59 | 62 | print(f" Type: {entity.content_type:20} | {content:30} | {entity.attributes}") |
60 | 63 |
|
| 64 | +# Query 2: Retrieve entities filtered by idx and sorted by idx descending |
| 65 | +idx_desc = IntSort("idx", DESC) |
| 66 | + |
61 | 67 | print("\nπ Query 2: Retrieving filtered (idx > 1 and idx < 5) and sorted (idx desc) entities") |
62 | | -sort = OrderByAttribute("idx", INT, DESC) |
63 | | -options = QueryOptions(order_by=[sort]) |
64 | | -filtered_and_sorted = list(client.arkiv.query_entities(f"idx > 1 and idx < 5", options=options)) |
| 68 | +filtered_and_sorted = list(client.arkiv.select().where((idx > 1) & (idx < 5)).order_by(idx_desc).fetch()) |
65 | 69 | print(f"β
Found {len(filtered_and_sorted)} entities:") |
66 | 70 | for entity in filtered_and_sorted: |
67 | 71 | if entity.payload: |
68 | 72 | content = entity.payload.decode('utf-8') |
69 | 73 | print(f" Type: {entity.content_type:20} | {content:30} | {entity.attributes}") |
| 74 | + |
| 75 | +# Cleanup |
| 76 | +client.node.stop() |
| 77 | +print("\nβ
Node stopped.") |
0 commit comments