You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Firebase Database技术求助:加尔各答公交查询应用数据存储方案优化

Firebase Data Structure for Kolkata Bus Route Query App

Great question! Building a bus route finder for a city like Kolkata—with its sprawling, complex transit network—requires a Firebase data structure that prioritizes fast queries and clean, maintainable code. Here’s a battle-tested approach I’ve used for similar transit apps that should fit your needs perfectly:

Core Data Structure (Realtime Database)

We’ll split data into 3 focused nodes to avoid overfetching and simplify query logic:

1. routes - Store Route Metadata

This node holds all static details for each bus route. Use a prefixed route ID (like route_12A) as the key to avoid conflicts and enable quick lookups.

"routes": {
  "route_12A": {
    "routeNumber": "12A",
    "operator": "WBTC",
    "startStop": "Howrah Station",
    "endStop": "Salt Lake Sector 5",
    "timings": "6:00 AM - 10:00 PM",
    "fareRange": "₹10 - ₹30"
  },
  "route_23": {
    "routeNumber": "23",
    "operator": "WBTC",
    "startStop": "Howrah Station",
    "endStop": "Gariahat",
    "timings": "5:30 AM - 10:30 PM",
    "fareRange": "₹8 - ₹25"
  }
}

2. stop_to_routes - Reverse Index for Fast Queries

This is the most critical node for your search functionality. It maps each bus stop to all routes that pass through it. Using boolean values (true) ensures efficient existence checks and minimal data footprint.

"stop_to_routes": {
  "Howrah Station": {
    "route_12A": true,
    "route_23": true,
    "route_47": true
  },
  "Salt Lake Sector 5": {
    "route_12A": true,
    "route_36": true
  },
  "Park Street": {
    "route_23": true,
    "route_36": true,
    "route_47": true
  }
}

3. route_stop_sequence - Track Stop Order

Store the sequential list of stops for each route to validate direction (e.g., ensure the user’s start stop comes before the end stop on the route) and display route paths to users.

"route_stop_sequence": {
  "route_12A": [
    "Howrah Station",
    "Esplanade",
    "Park Street",
    "Salt Lake Sector 5"
  ],
  "route_23": [
    "Howrah Station",
    "Park Street",
    "New Market",
    "Gariahat"
  ]
}

Simplified Query Logic (JavaScript)

Here’s how you’d implement the search functionality with this structure—clean, efficient, and easy to maintain:

const db = firebase.database();

// User input: startStop and endStop
const searchRoutes = async (startStop, endStop) => {
  try {
    // Fetch routes for both stops in parallel
    const [startRouteSnapshot, endRouteSnapshot] = await Promise.all([
      db.ref(`stop_to_routes/${startStop}`).once('value'),
      db.ref(`stop_to_routes/${endStop}`).once('value')
    ]);

    if (!startRouteSnapshot.exists() || !endRouteSnapshot.exists()) {
      console.log("No direct routes found between these stops");
      return [];
    }

    // Extract route IDs from snapshots
    const startRoutes = Object.keys(startRouteSnapshot.val());
    const endRoutes = Object.keys(endRouteSnapshot.val());

    // Find common routes (intersection of both lists)
    const commonRouteIds = startRoutes.filter(routeId => endRoutes.includes(routeId));

    if (commonRouteIds.length === 0) {
      console.log("No direct routes found between these stops");
      return [];
    }

    // Fetch full details for each common route
    const routeDetails = await Promise.all(
      commonRouteIds.map(routeId => db.ref(`routes/${routeId}`).once('value'))
    );

    // Format data for UI display
    return routeDetails.map(snap => snap.val());
  } catch (error) {
    console.error("Error fetching routes:", error);
    return [];
  }
};

// Example usage:
searchRoutes("Howrah Station", "Park Street").then(routes => {
  console.log("Available Routes:", routes);
  // Render routes in your app's UI here
});

Key Optimizations for Kolkata’s Network

  • Standardize Stop Names: Kolkata’s stops often have English and Bengali names. Add a stops node to map standardized IDs to both names (and coordinates for future map integration):

    "stops": {
      "stop_001": {
        "englishName": "Howrah Station",
        "bengaliName": "হাওড়া স্টেশন",
        "latitude": 22.5804,
        "longitude": 88.3130
      }
    }
    

    Update stop_to_routes to use these IDs instead of raw names to avoid mismatches from user input.

  • Handle Reverse Routes: For routes that run both ways with the same number, split them into separate entries (e.g., route_12A_forward and route_12A_backward) in all nodes to ensure accurate direction checks.

  • Cache Popular Queries: For high-traffic stop pairs (like Howrah to Esplanade), cache the results in a cached_queries node to reduce redundant database reads and speed up responses.

内容的提问来源于stack exchange,提问作者Farhan Saikh

火山引擎 最新活动