Skip to content

Commit

Permalink
fix: Fixed the convex function and table so that they don't take too …
Browse files Browse the repository at this point in the history
…much space to exceed our spending limits.
  • Loading branch information
FleetAdmiralJakob committed Mar 26, 2024
1 parent b64e644 commit 5807b75
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
12 changes: 7 additions & 5 deletions packages/city-data/convex/getCity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,19 +92,21 @@ export const findCityById = query({
},
});

// This is not the fastest way of doing this stuff,
// FIRST: We should use an index for both of the coord fields.
// I did this first, but because of the big size these indexes took, our convex db storage limit exceeded.
// In the future, if we have more storage, we should use indexes for coord fields.
// SECOND: Instead of a bounding box search, we could use something like geohashes to find all nearby cities more efficiently and quickly.
export const findNearestCityByCoord = mutation({
args: { coord: v.object({ lat: v.number(), lng: v.number() }) },
handler: async (ctx, args) => {
// This is a simple query that finds cities within a 0.1-degree square; this optimization is to avoid scanning the whole table with havy calculations.
const cities = await ctx.db
.query("search")
.withIndex("by_lon", (q) =>
q
.gt("coord.lon", args.coord.lng - 0.1)
.lt("coord.lon", args.coord.lng + 0.1),
)
.filter((q) =>
q.and(
q.gt(q.field("coord.lon"), args.coord.lng - 0.1),
q.lt(q.field("coord.lon"), args.coord.lng + 0.1),
q.gt(q.field("coord.lat"), args.coord.lat - 0.1),
q.lt(q.field("coord.lat"), args.coord.lat + 0.1),
),
Expand Down
3 changes: 1 addition & 2 deletions packages/city-data/convex/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,5 @@ export default defineSchema({
.searchIndex("search_body", {
searchField: "name",
})
.index("by_city_id", ["id"])
.index("by_lon", ["coord.lon"]),
.index("by_city_id", ["id"]),
});

0 comments on commit 5807b75

Please sign in to comment.