0
  • Histories

    • Places
      • ChIJ-REgsXyPwTARJh1vn16yZBc (placeID)
        • name: "Tokyo Tower"
        • userInfo
          • M1nlb7iEg9ZU6cr28DOwJOqrlKA2 (userID)
            • Lxqcl6Zys2cjmYSzcWU (autoID)
              • dateAdded: "2020-01-05"
              • interactionType: "placeTap"
let historiesPlacesRef = Database.database().reference().child("Histories").child("Places")

When I fetch the place with the name "Tokyo Tower" using the following, it works.

historiesPlacesRef
    .queryOrdered(byChild: "name")
    .queryEqual(toValue: "Tokyo Tower")
    .observe(.value) { (dataSnapshot) in
        print(dataSnapshot)
    }

What I want to query is places that the current user visited. I tried the following. But it does not work.

historiesPlacesRef
    .queryOrdered(byChild: "userInfo")
    .queryEqual(toValue: Auth.auth().currentUser!.uid)
    .observe(.value) { (dataSnapshot) in
        print(dataSnapshot)
    }
Kumar KL
  • 15,315
  • 9
  • 38
  • 60
NkaBall
  • 71
  • 7

1 Answers1

0

Firebase queries can only check for values that are at a known location under each child node of the location that you query. So in your current structure you can find all places with a specific name, or al the times a specific user went to Tokyo Tower in 2020. But you can't find all users across all cities, nor search all visits for a city (thanks to the Auto ID).

In other words: your current data structure makes it easy to find all users who went to a city you queries for, but it doesn't allow you to easily query for all cities a user went to. To allow this use-case, you'll need to add an additional data structure.

UserPlaces: {
  UID1: {
    placeID1: {
      dateAdded: "2020-01-05",
      interactionType: "placeTap"
    }
    placeID2: {
      dateAdded: "2020-01-04",
      interactionType: "somethingElse"
    }
  }
  UID2: {
    placeID1: {
      dateAdded: "2020-01-05",
      interactionType: "somethingElseAgain"
    }
  }
}

With this additional structure (often called an inverted index), you can then look up (or query) data for a specific user. You may need to change this data structure for your specific use-cases, or even add multiple such structures to meet all use-cases.

Also see my answers here:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807