Ronnie Smith
Ronnie Smith

Reputation: 18575

Firebase Database: Search for Particular Item

I'm building out an ordering tool. Each order has an id, a unique identifier that I get from Firebase using the push method. My question is: let's say I put a text field labeled "Order" in my page with a button next to it titled "Find".

What's the best way to retrieve (and maybe even structure) that data? I am familiar with indexing on the Firebase database. Basically, I want to enable searching for a particular order. There could be thousands of them. Is the below proper?

var wantedOrder = firebase.database().ref('orders').equalTo("My Input Text");

  "orders": {
    "abc123456": {
      "name": "My First Fake Order",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      },
    "abc123457": {
      "name": "My Second Fake Order",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }

Firebase Rules

{
  "rules": {
    "orders": {
      ".indexOn": ["name"]
    }
  }
}

Upvotes: 0

Views: 2093

Answers (2)

Kushan
Kushan

Reputation: 5984

You need an orderBy*() type of function before equalTo(), startAt() and endAt().

In your particular case, I would use

var wantedOrder = firebase.database().ref('orders').orderByChild('name').equalTo('yourText').on(listener you want.....)

This will return the exact match of your search....

If you want to have a more flexible way, use startAt() and endAt().

Upvotes: 2

Deepesh
Deepesh

Reputation: 533

I can suggest you two way to achieve what you are looking for.

  1. (Not very efficient if you have huge data) You can get entire data through ValueEventListener of "Orders" node and then loop over every set of data for search keyword.

  2. Have a look at this link they have similar dataset as yours. Querying firebase through substring

Upvotes: 0

Related Questions