Essay · No. 009··9 min read

Backend engineering · Search

Building Neighbourhood Search from Supplier Hotel Data

Contents
  1. 1. Model an area as a place with a parent
  2. 2. Write the matching rule as a small pure function
  3. 3. Check the rule on a map before you trust it
  4. 4. Decide which areas to create, and record why
  5. 5. Make the build idempotent
  6. 6. Give each area one stable search entry
  7. 7. Apply the same rule when a hotel arrives
  8. 8. Test the rule with awkward hotels
  9. 9. Keep every copy in step

9 min readPublished 28 Nov 2026

A traveller can type the name of a beach, district or market street and expect to see hotels in that area. If your hotel data comes from suppliers, those areas often do not exist as data: some suppliers send area lists, and many send only an address and coordinates. This essay shows how to build areas from that data, and the rules that keep them correct after the first build.

Everything below is a general pattern, not a description of any one codebase. The place names, coordinates and thresholds are example values, and the TypeScript is a small sketch written for this essay. It runs, and it shows the decisions that matter.

1. Model an area as a place with a parent

Most travel search already understands one kind of destination: a city with a list of hotels. Autocomplete, the search index and the hotel search all read it. The cheapest way to add areas is to reuse that shape and add one field that points to the parent city.

Figure 1
place: Demo Bay            kind: city   parent: none
place: North Beach         kind: city   parent: Demo Bay
place: Old Market          kind: city   parent: Demo Bay

Every reader of places can then show an area without a change. A brand-new place type would need work in each of those readers first. When some part of the system must tell a city and an area apart, it checks the parent field.

A minimal model for the sketch looks like this. The important part is that the rule which built the area is saved with it.

Figure 2
{
  "id": "area-north-beach",
  "name": "North Beach",
  "parentId": "city-demo-bay",
  "hotelIds": ["h-101", "h-102", "h-107"],
  "rule": {
    "mode": "either",
    "center": [0.512, 0.348],
    "radiusKm": 1.5,
    "addressWords": ["north beach"]
  }
}

One trap is worth naming early. GeoJSON and most geo indexes put longitude first and latitude second, and supplier files often send them the other way round. A swapped pair still looks like a valid coordinate, so check a sample of pins on a map whenever a new supplier file arrives.

2. Write the matching rule as a small pure function

A hotel can match an area in two ways: its coordinates fall inside a circle around a centre point, or its address contains one of the area's words. The rule says which of the two counts.

Figure 3
type LngLat = [number, number];
type Hotel = { id: string; location: LngLat; address: string };
type AreaRule = {
  mode: "location" | "address" | "either";
  center: LngLat;
  radiusKm: number;
  addressWords: string[];
};

const EARTH_RADIUS_KM = 6371;

function distanceKm([lng1, lat1]: LngLat, [lng2, lat2]: LngLat): number {
  const rad = Math.PI / 180;
  const dLat = (lat2 - lat1) * rad;
  const dLng = (lng2 - lng1) * rad;
  const a = Math.sin(dLat / 2) ** 2 +
    Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(dLng / 2) ** 2;
  return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(a));
}

function normalise(text: string): string {
  return text.normalize("NFKD").replace(/[̀-ͯ]/g, "")
    .toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
}

function addressMatches(address: string, words: string[]): boolean {
  const padded = ` ${normalise(address)} `;
  return words.some((word) => padded.includes(` ${normalise(word)} `));
}

export function matchesArea(hotel: Hotel, rule: AreaRule): boolean {
  const byLocation = distanceKm(hotel.location, rule.center) <= rule.radiusKm;
  const byAddress = addressMatches(hotel.address, rule.addressWords);
  if (rule.mode === "location") return byLocation;
  if (rule.mode === "address") return byAddress;
  return byLocation || byAddress;
}

Two details in that sketch prevent real bugs. The address check compares whole words after normalising, so "Bay" does not match "Baywatch Street", and "Café Row" matches "cafe row". And the function touches no database, so you can test it with a list of hotels and nothing else.

If your database has a geo index, the location half can run there instead. In MongoDB, for example, a $geoWithin query with $centerSphere finds the same circle. Its radius is in radians, so you divide the kilometres by the Earth's radius. The MongoDB documentation uses 6,378.1 km, and the sketch uses the mean radius of 6,371 km. For a 1.5 km circle, that difference is under two metres.

Figure 4
db.hotels.find({
  location: { $geoWithin: { $centerSphere: [[0.512, 0.348], 1.5 / 6378.1] } }
})

3. Check the rule on a map before you trust it

Plot an area's hotels on a map before you build it. The map shows where the rule takes in or leaves out hotels in ways the numbers hide.

Figure 5
North Beach   centre + 1.5 km   tight cluster, keep the radius
Coast Road    address only      hotels spread along a long road
Cliff Point   location only     address text names the wrong place

A circle suits a tight cluster, but a circle centred on a long road misses the hotels at both ends, so an area like that matches on the address. Address text can be wrong too. A hotel's address can name a nearby, better-known area while its pin sits in the next one. For an area like that, match on location alone.

That is why the mode belongs in the stored rule. The map decides the mode, and the code only applies it.

4. Decide which areas to create, and record why

An area gets its own suggestion in autocomplete. If someone picks it and finds three hotels, they also miss the hotels just outside it that a city search would have shown. So skip an area below a minimum hotel count.

Also check what share of the parent city's hotels the area would hold. If the area is nearly the whole city, a separate suggestion adds nothing.

Figure 6
type Decision = { area: string; action: "create" | "skip"; reason: string };

export function decide(area: string, areaHotels: Set<string>, cityHotels: Set<string>,
                       minHotels = 20, maxShare = 0.35): Decision {
  const share = areaHotels.size / cityHotels.size;
  if (areaHotels.size < minHotels)
    return { area, action: "skip", reason: `${areaHotels.size} hotels, minimum ${minHotels}` };
  if (share >= maxShare)
    return { area, action: "skip", reason: `${Math.round(share * 100)}% of the city, limit ${Math.round(maxShare * 100)}%` };
  return { area, action: "create", reason: `${areaHotels.size} hotels, ${Math.round(share * 100)}% of the city` };
}

Every decision carries a reason, and that is what a dry run should print. When someone asks why an area is missing, the answer is one line in a report, not an afternoon of reading code.

Keep each threshold tied to one job. A number you use to shortlist candidate areas is not the number that decides what travellers see, and two similar numbers are easy to mix up in a discussion. Thresholds like these usually come from judgement, not measurement, so write down which one applies before you argue about an area.

Some areas are destinations in their own right, and travellers search for them by name. A single share limit can block exactly the result people ask for. That is why maxShare is a parameter: let an area override it.

5. Make the build idempotent

A hotel in North Beach is still in Demo Bay. Add it to the area and keep it in the parent city, so the traveller reaches it through either search.

Figure 7
search "North Beach"   --> hotels in North Beach
search "Demo Bay"      --> hotels in Demo Bay, including North Beach

Do not edit membership lists in place. Compute the list each area should have, compare it with the list it has, and apply only the difference. Then a second run gives the same result as the first.

Figure 8
export function membershipDiff(current: Set<string>, desired: Set<string>) {
  return {
    add: [...desired].filter((id) => !current.has(id)),
    remove: [...current].filter((id) => !desired.has(id)),
  };
}

export function notInParent(areaHotels: Set<string>, cityHotels: Set<string>): string[] {
  return [...areaHotels].filter((id) => !cityHotels.has(id));
}

The second function is a check to run after every build. Every hotel in an area must also be in its parent city, so the result must be empty.

Watch the order of jobs, too. If another job rebuilds city hotel lists from supplier data, it can overwrite what the area build expects. Run the area step after that job, against the lists it has just produced, rather than on its own schedule.

6. Give each area one stable search entry

When a city and one of its areas both match what someone types, the city should come first. Give the area a ranking value below its parent's.

The search entry also needs a stable identifier. If the entry's ID comes from the area's ID, a second build updates the same entry. If it is random, or built from the area's name, a rebuild or a rename creates a second entry, and travellers see a duplicate suggestion.

Figure 9
const entry = {
  id: area.id,
  name: area.name,
  parentName: city.name,
  rank: Math.min(area.rank, city.rank - 1),
};

Write the entry with an upsert, and after the build, check that each area has exactly one entry in the index.

7. Apply the same rule when a hotel arrives

Areas built only by a script fall behind as suppliers add hotels. The fix is to run the same rule at import time, at the point where a new hotel joins its city.

Figure 10
import hotel
  --> add to its city
  --> load the city's areas (once per city, per import batch)
  --> for each area, run matchesArea with the stored rule
  --> add the hotel to each area it matches

This is where storing the rule with the area pays off. The import needs only the area itself, not the build script's configuration. And because the build and the import call the same matchesArea with the same inputs, they cannot disagree about a hotel.

8. Test the rule with awkward hotels

A pure matcher makes the most useful tests cheap. Keep a small set of synthetic hotels that each break one assumption.

Figure 11
inside the radius, no address words      location: yes   address: no
just outside the radius                  location: no    address: no
address names the area, pin is far away  location: no    address: yes
address with accents and odd spacing     address: yes after normalising
area word inside a longer word           address: no
latitude and longitude swapped           location: no

Run each case against all three modes. The swapped pin does not prove your data is right, but it shows what one bad file does to the result, which makes the case for the map check in section 1.

9. Keep every copy in step

Place data rarely lives in one store. There is the main catalogue, the search index, and sometimes a second database for another product. If an area reaches one copy and not the others, travellers see different destinations depending on where they search.

  1. Run a dry run against each copy and compare the reports, including the reasons.
  2. Save the current places to a rollback file.
  3. Apply the change to each store in a fixed order.
  4. Upsert the search entries.
  5. Check hotel counts and parent membership in every store, and one entry per area in the index.

A neighbourhood looks like a small feature to the traveller. Behind it sit a few rules that are easy to state and easy to break: a minimum size, a maximum share, membership in the parent city, one stable search entry, and the same data in every copy. Writing them as small functions, and saving the rule with the place, is what keeps them true after the first build.

Keep scrolling for the next pageKeep scrolling… Abdullah Sarwar Following One Request Through Logs with Grafana and Loki