Skip to content

Commit cc1256c

Browse files
committed
Merge branch '31-restructure-examples-folder' into 'dev'
Resolve "Restructure examples folder" Closes #31 See merge request objectbox/objectbox-python!19
2 parents 33821c3 + 241be5f commit cc1256c

File tree

9 files changed

+427
-2
lines changed

9 files changed

+427
-2
lines changed

download-c-lib.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
# Script used to download objectbox-c shared libraries for all supported platforms. Execute by running `make get-lib`
77
# on first checkout of this repo and any time after changing the objectbox-c lib version.
88

9-
version = "v0.21.0" # see objectbox/c.py required_version
9+
version = "v0.21.1-alpha0" # see objectbox/c.py required_version
1010
variant = 'objectbox' # or 'objectbox-sync'
1111

1212
base_url = "https://github.com/objectbox/objectbox-c/releases/download/"
@@ -49,6 +49,7 @@ def download(rel_path: str):
4949

5050
# Download the file from `url`, save it in a temporary directory and get the path to it (e.g. '/tmp/tmpb48zma')
5151
source_url = url_for(rel_path);
52+
print(f"URL {source_url}")
5253
tmp_file, headers = urllib.request.urlretrieve(source_url)
5354

5455
# extract the file

example/README.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# ObjectBox-Python Examples
2+
3+
The following examples are available from this repository.
4+
5+
## Application Example: Tasks
6+
7+
This is our classic Tasks application using a CLI.
8+
9+
```
10+
cd example
11+
python -m tasks
12+
13+
Welcome to the ObjectBox tasks-list app example. Type help or ? for a list of commands.
14+
> new buy oat
15+
> new buy yeast
16+
> new bake bread
17+
> ls
18+
ID Created Finished Text
19+
1 Mon Apr 22 11:02:27 2024 buy oat
20+
2 Mon Apr 22 11:02:30 2024 buy yeast
21+
3 Mon Apr 22 11:02:34 2024 bake bread
22+
> done 1
23+
> done 2
24+
> ls
25+
> ls
26+
ID Created Finished Text
27+
1 Mon Apr 22 11:02:27 2024 Mon Apr 22 11:03:02 2024 buy oat
28+
2 Mon Apr 22 11:02:30 2024 Mon Apr 22 11:03:18 2024 buy yeast
29+
3 Mon Apr 22 11:02:34 2024 bake bread
30+
> exit
31+
```
32+
33+
## Vector-Search Example: Cities
34+
35+
This example application starts with a pre-defined set of capital cities and their geo coordinates.
36+
It allows to search for nearest neighbors of a city (`city_neighbors`) or by coordinates (`neighbors`) as well as adding more locations (`add`).
37+
38+
```
39+
python -m vectorsearch-cities
40+
Welcome to the ObjectBox vectorsearch-cities example. Type help or ? for a list of commands.
41+
> ls
42+
ID Name Latitude Longitude
43+
1 Abuja 9.08 7.40
44+
2 Accra 5.60 -0.19
45+
[..]
46+
212 Yerevan 40.19 44.52
47+
213 Zagreb 45.81 15.98
48+
> ls Ber
49+
ID Name Latitude Longitude
50+
28 Berlin 52.52 13.40
51+
29 Bern 46.95 7.45
52+
> city_neighbors Berlin
53+
ID Name Latitude Longitude Score
54+
147 Prague 50.08 14.44 7.04
55+
49 Copenhagen 55.68 12.57 10.66
56+
200 Vienna 48.21 16.37 27.41
57+
34 Bratislava 48.15 17.11 32.82
58+
89 Ljubljana 46.06 14.51 42.98
59+
> neighbors 6,52.52,13.405
60+
ID Name Latitude Longitude Score
61+
28 Berlin 52.52 13.40 0.00
62+
147 Prague 50.08 14.44 7.04
63+
49 Copenhagen 55.68 12.57 10.66
64+
200 Vienna 48.21 16.37 27.41
65+
34 Bratislava 48.15 17.11 32.82
66+
89 Ljubljana 46.06 14.51 42.98
67+
> add Area51, 37.23, -115.81
68+
> city_neighbors Area51
69+
ID Name Latitude Longitude Score
70+
107 Mexico City 19.43 -99.13 594.86
71+
27 Belmopan 17.25 -88.76 1130.92
72+
64 Guatemala City 14.63 -90.51 1150.79
73+
164 San Salvador 13.69 -89.22 1261.12
74+
67 Havana 23.11 -82.37 1317.73
75+
```

example/tasks/__init__.py

Whitespace-only changes.

example/__main__.py renamed to example/tasks/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from cmd import Cmd
22
import objectbox
33
import time
4-
from example.model import *
4+
from .model import *
55

66

77
# objectbox expects date timestamp in milliseconds since UNIX epoch
File renamed without changes.

example/vectorsearch-cities/__init__.py

Whitespace-only changes.
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
from cmd import Cmd
2+
import objectbox
3+
import time
4+
from .model import *
5+
import csv
6+
import os
7+
8+
def list_cities(cities):
9+
print("{:3s} {:25s} {:>9s} {:>9s}".format("ID", "Name", "Latitude", "Longitude"))
10+
for city in cities:
11+
print("{:3d} {:25s} {:>9.2f} {:>9.2f}".format(
12+
city.id, city.name, city.location[0], city.location[1]))
13+
14+
def list_cities_with_scores(city_score_tuples):
15+
print("{:3s} {:25s} {:>9s} {:>9s} {:>5s}".format("ID", "Name", "Latitude", "Longitude", "Score"))
16+
for (city,score) in city_score_tuples:
17+
print("{:3d} {:25s} {:>9.2f} {:>9.2f} {:>5.2f}".format(
18+
city.id, city.name, city.location[0], city.location[1], score))
19+
20+
class VectorSearchCitiesCmd(Cmd):
21+
prompt = "> "
22+
def __init__(self, *args):
23+
Cmd.__init__(self, *args)
24+
dbdir = "cities-db"
25+
new_db = not os.path.exists(dbdir)
26+
self._ob = objectbox.Builder().model(get_objectbox_model()).directory(dbdir).build()
27+
self._box = objectbox.Box(self._ob, City)
28+
self._name_prop: Property = City.get_property("name")
29+
self._location_prop: Property = City.get_property("location")
30+
if new_db:
31+
with open(os.path.join(os.path.dirname(__file__), 'cities.csv')) as f:
32+
r = csv.reader(f)
33+
cities = []
34+
for row in r:
35+
city = City()
36+
city.name = row[0]
37+
city.location = [ row[1], row[2] ]
38+
cities.append(city)
39+
self._box.put(*cities)
40+
41+
def do_ls(self, name: str = ""):
42+
"""list all cities or starting with <prefix>\nusage: ls [<prefix>]"""
43+
qb = self._box.query()
44+
qb.starts_with_string(self._name_prop, name)
45+
query = qb.build()
46+
list_cities(query.find())
47+
48+
def do_city_neighbors(self, args: str):
49+
"""find <num> (default: 5) next neighbors to city <name>\nusage: city_neighbors <name> [,<num>]"""
50+
try:
51+
args = args.split(',')
52+
if len(args) > 2:
53+
raise ValueError()
54+
city = args[0]
55+
if len(city) == 0:
56+
raise ValueError()
57+
num = 5
58+
if len(args) == 2:
59+
num = int(args[1])
60+
qb = self._box.query()
61+
qb.equals_string(self._name_prop, city)
62+
query = qb.build()
63+
cities = query.find()
64+
if len(cities) == 1:
65+
location = cities[0].location
66+
qb = self._box.query()
67+
qb.nearest_neighbors_f32(self._location_prop, location, num+1) # +1 for the city
68+
qb.not_equals_string(self._name_prop, city)
69+
neighbors = qb.build().find_with_scores()
70+
list_cities_with_scores(neighbors)
71+
else:
72+
print(f"no city found named '{city}'")
73+
except ValueError:
74+
print("usage: city_neighbors <name>[,<num: default 5>]")
75+
76+
def do_neighbors(self, args):
77+
"""find <num> neighbors next to geo-coord <lat> <long>.\nusage: neighbors <num>,<latitude>,<longitude>"""
78+
try:
79+
args = args.split(',')
80+
if len(args) != 3:
81+
raise ValueError()
82+
num = int(args[0])
83+
geocoord = [ float(args[1]), float(args[2]) ]
84+
qb = self._box.query()
85+
qb.nearest_neighbors_f32(self._location_prop, geocoord, num)
86+
neighbors = qb.build().find_with_scores()
87+
list_cities_with_scores(neighbors)
88+
except ValueError:
89+
print("usage: neighbors <num>,<latitude>,<longitude>")
90+
91+
def do_add(self, args: str):
92+
"""add new location\nusage: add <name>,<lat>,<long>"""
93+
try:
94+
args = args.split(',')
95+
if len(args) != 3:
96+
raise ValueError()
97+
name = str(args[0])
98+
lat = float(args[1])
99+
long = float(args[2])
100+
city = City()
101+
city.name = name
102+
city.location = [lat,long]
103+
self._box.put(city)
104+
except ValueError:
105+
print("usage: add <name>,<latitude>,<longitude>")
106+
107+
def do_exit(self, _):
108+
"""close the program"""
109+
raise SystemExit()
110+
111+
112+
if __name__ == '__main__':
113+
app = VectorSearchCitiesCmd()
114+
app.cmdloop('Welcome to the ObjectBox vectorsearch-cities example. Type help or ? for a list of commands.')

0 commit comments

Comments
 (0)