Home > Java > javaTutorial > How to Efficiently Select Random Products from a Large Firebase Database in Node?

How to Efficiently Select Random Products from a Large Firebase Database in Node?

Barbara Streisand
Release: 2024-10-29 06:12:31
Original
353 people have browsed it

How to Efficiently Select Random Products from a Large Firebase Database in Node?

Getting Unique Random Products in Node Firebase

To retrieve a single random product from a node database over 1000 records, consider two approaches: the classic solution and a denormalized approach.

Classic Solution

<br>ListView listView = (ListView) findViewById(R.id.list_view);<br>ArrayAdapter arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, randomProductList);<br>listView.setAdapter(arrayAdapter);<br>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();<br>DatabaseReference productsRef = rootRef.child("products"); //Added call to .child("products")<br>ValueEventListener valueEventListener = new ValueEventListener() {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    List<String> productList = new ArrayList<>();
    for(DataSnapshot ds : dataSnapshot.getChildren()) {
        String name = ds.child("name").getValue(String.class);
        productList.add(name);
    }

    int productListSize = productList.size();
    List<String> randomProductList = new ArrayList<>();

    randomProductList.add(new Random().nextInt(productListSize)); //Add the random product to list
    arrayAdapter.notifyDatasetChanged();
}

@Override
public void onCancelled(DatabaseError databaseError) {
    Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors!
}
Copy after login

};
productsRef.addListenerForSingleValueEvent(valueEventListener);

This approach loops through all product nodes, adds their names to a list, and randomly selects one.

Denormalized Approach

Create a separate "productIds" node to avoid downloading large amounts of data:

<br>Firebase-root<br>   |<br>   --- products<br>   |     |<br>   |     --- productIdOne<br>   |     |      |<br>   |     |      --- //details<br>   |     |<br>   |     --- productIdTwo<br>   |            |<br>   |            --- //details<br>   |      <br>   --- productIds</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">      |
      --- productIdOne: true
      |
      --- productIdTwo: true
      |
      --- //And so on
Copy after login

<br>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();<br>DatabaseReference productIdsRef = rootRef.child("productIds");<br>ValueEventListener valueEventListener = new ValueEventListener() {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    List<String> productIdsList = new ArrayList<>();
    for(DataSnapshot ds : dataSnapshot.getChildren()) {
        String productId = ds.getKey();
        productIdsList.add(productId);
    }

    int productListSize = productList.size();
    List<String> randomProductList = new ArrayList<>();

    DatabaseReference productIdRef = rootRef.child("products").child(productIdsList.get(new Random().nextInt(int productListSize));
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String name = dataSnapshot.child("name").getValue(String.class);
            Log.d("TAG", name);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors!
        }
    };
    productIdRef.addListenerForSingleValueEvent(eventListener);
}

@Override
public void onCancelled(DatabaseError databaseError) {
    Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors!
}
Copy after login

};
productIdsRef.addListenerForSingleValueEvent(valueEventListener);

This approach queries the "productIds" node to get a random product ID, then queries the "products" node for specific details.

The above is the detailed content of How to Efficiently Select Random Products from a Large Firebase Database in Node?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:Why does Java throw an \"out of range\" error for a long literal despite the variable being declared as long? Next article:Should You Version Control Your Eclipse Project Configuration Files?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template