javascript - Relational queries in Cloud Code (parse.com) -
table structure:
collection
name (string)
image
collection (pointer<collection>)
url (string)
position (number)
image class has column collection pointer collection class.
position used sort images within collection.
what efficient way in cloud code accomplish following?
lets assume have ~3000 images , 3 collections.
what best way construct query returns array containing collections have at least 1 associated image , show only first 5 images of each collection, sorted position
associated images each collection need included in response , vaguely this:
results: [{ collection: { name: 'foo' }, images: [{ position: 0, url: 'test.jpg' }, { position: 1, url: 'test.gif' }] }, { ... }] all can think of @ moment doing 2 queries, 1 collections , images upfront , filter them, seems quite backwards, coupled fact parse limited result sets of 1000 @ maximum. need rethink table structure?
you can in single call, given constraints.
if have small number of collection objects , you're using relative position (each collection has image position = 1, 2, etc.), there's no need overthink problem. these constraints mean there relatively few items 'position' < 6 (or 5, if 0 first index position).
simply make call on image class , restrict objects position less or equal 5. use .include() return collection object attached each image object part of return. sort image objects locally in whatever format see fit.
remember parse limits number of objects can returned 100, , can increase 1000. if .include() collection on each image, means each returned image counts 2 objects, can return 500 image objects. sounds above expected needs.
voilá - 1 call, objects.
var image = parse.object.extend("image"); var query = new parse.query(image); query.lessthan("number", 6); //assumes lowest index of 1; switch 5 if lowest index number 0 query.include("collection"); query.find({ success: function(results) { //sort results according collection, send controllers, etc. //each result have pulled, valid collection object ready on .collection }, error: function(error) { alert("error: " + error.code + " " + error.message); } }); update worth noting approach outperforms 'nested query' approach, both small number of collections or @ scale (1000s or 10,000s of collections)
Comments
Post a Comment