DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Reducing Network Latency and Improving Read Performance With CockroachDB and PolyScale.ai
  • JavaFX Goes Mobile
  • Conditional Breakpoints: A Guide to Effective Debugging
  • Google Becomes A Java Developer's Best Friend: Instantiations Developer Tools Relaunched For Free
  1. DZone
  2. Data Engineering
  3. Databases
  4. Selecting a Random Record from an IndexedDB Object Store

Selecting a Random Record from an IndexedDB Object Store

Raymond Camden user avatar by
Raymond Camden
·
Dec. 04, 14 · Interview
Like (0)
Save
Tweet
Share
3.69K Views

Join the DZone community and get the full member experience.

Join For Free

A few days ago I ran across an interesting post on Stack Overflow, Is there any way to retrieve random row from indexeddb? The posted answer used the following process:

  • Open an index.
  • Iterate over every row.
  • On the first iteration, use the key value as an upper bound, and select a random number from 1 to that number.
  • Iterate until you hit that number.

While this worked, it seemed like a bad idea to iterate over – possibly – a huge number of rows to get to the random row you wanted. I double checked the spec and discovered what seems to be a simpler solution. When you have opened a cursor (and for those who don’t know IDB very well, think of it as simply a way to iterate over a table), you can either continue to the next row, continue to a specific key, or use the advance method to go forward a specific number of rows.

I figured advance would be a good way to handle this. I built a simple demo that demonstrates this. I won’t bother showing the HTML as it is just two buttons (one to add some seed data and one to select the random value), but you can view source on the linked demo below if you want. Here is the JavaScript. Note – this code can definitely be rewritten to be a bit tighter.

/* global $,document,indexedDB,console */

/**
 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt (min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

$(document).ready(function() {
	var db;

	var openRequest = indexedDB.open("randomidb",1);

	openRequest.onupgradeneeded = function(e) {
		var thisDB = e.target.result;

		console.log("running onupgradeneeded");

		if(!thisDB.objectStoreNames.contains("notes")) {
			thisDB.createObjectStore("notes", {autoIncrement:true});
		}
	};


	openRequest.onsuccess = function(e) {
		console.log("running onsuccess");

		db = e.target.result;

		$("#seedButton").on("click", function() {

			var store = db.transaction(["notes"],"readwrite").objectStore("notes");

			for(var i=0; i<10; i++) {
				var note = {
					title:"Just a random note: "+getRandomInt(1,99999),
					created:new Date()
				};

				var request = store.add(note);

				request.onerror = function(e) {
					console.log("Error",e.target.error.name);
					//some type of error handler
				};

				request.onsuccess = function(e) {
					console.log("Woot! Did it");
				};
			}

		});

		$("#randomButton").on("click", function() {

			//success handler, could be passed in
			var done = function(ob) {
				console.log("Random result",ob);	
			};

			//ok, first get the count
			var store = db.transaction(["notes"],"readonly").objectStore("notes");

			store.count().onsuccess = function(event) {
				var total = event.target.result;
				var needRandom = true;
				console.log("ok, total is "+total);
				store.openCursor().onsuccess = function(e) {
					var cursor = e.target.result;
					if(needRandom) {
						var advance = getRandomInt(0, total-1);
						console.log("going up "+advance);
						if(advance > 0) {
							needRandom = false;
							cursor.advance(advance);	
						} else {
							done(cursor);
						}
					} else {
						done(cursor);
					}

				};

			};

		});

	};

});

I assume we can skip the IDB setup and seed functions. I built the bare minimum so I could test the random aspect. The random selection code works by first doing a count on the object store. This returns – yes – the count. Once we have that, we open a cursor that would normally let us iterate over the entire store. On the first iteration it has the first row. We then ask for a random number. Our range starts at 0 because we want to support the first row being acceptable as well. Based on that number we advance X number of rows and return that result to the done function. If for some reason 0 was selected, we run done right away.

Not rocket science, but it seems to work well. At most you run two iterations, not N, so it seems like it should be much more performant than the original answer on Stack Overflow. As I said, this was my first version so the code could definitely be organized a bit better. You can view the demo here: http://www.raymondcamden.com/demos/2014/nov/30/test1.html.

Object (computer science) Row (database) Record (computer science)

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Reducing Network Latency and Improving Read Performance With CockroachDB and PolyScale.ai
  • JavaFX Goes Mobile
  • Conditional Breakpoints: A Guide to Effective Debugging
  • Google Becomes A Java Developer's Best Friend: Instantiations Developer Tools Relaunched For Free

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: