Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Sorting with gorm-couchdb #9

Closed
jasonshah opened this Issue · 5 comments

3 participants

@jasonshah

Here's an interesting problem that we couldn't quite figure out.

How do we sort by, say, the 'order' field on 'question' documents?

The Couch docs seem to indicate that designing the query so that the ordering field is in the key is the best way to go, e.g.:

    function(doc) {
        if(doc.type == 'question' && doc.formId) {
            emit([doc.order, doc.formId], doc);
        }
    }

But, I don't quite see how I would use queryViewByKeys where the key itself is an array. How would I use queryViewByKeys to ignore doc.order but filter against doc.id?

Or, is there a better way to handle sorting in your experience?

@coryhacking
Owner

This is one of the things about couchdb that you have to get used to, but is extremely powerful once you get the hang of it. Your view should be something like this:

function(doc) {
    if(doc.type == 'question' && doc.formId) {
        emit([doc.formId, doc.order], null);
    }
}

Notice that I switched the parameter order because you use the formId in your query. If you wanted ALL questions sorted by some order then you would probably leave 'formId' off. When you query this view, you specify a range using 'startkey' and 'endkey' like this:

def search = [:]
search.startkey = [formId]
search.endkey = [formId, '\u9999']
search.include_docs = true
def questions = Question.findByFormId(search)

What you'll get back are all of the questions that have a form id of 'formId' sorted by 'order'.

@jasonshah

This works great (though, the ordering gets lost in moving from domain to JSON representation, our ArrayList gets converted to an unordered HashSet. That's an internal problem of course).

Side question: what does the '\u9999' represent?
Thanks again!

@jasonshah jasonshah closed this
@divideby0

I believe that's just a large unicode character, so it should cover the range of all possible values for your secondary key (from null to the 9999th unicode character).

@coryhacking
Owner

Just found another way to do this...

def search = [:]
search.startkey = [formId]
search.endkey = [formId, [:]]
search.include_docs = true
def questions = Question.findByFormId(search)

Works with couchdb v1.0.2. See http://permalink.gmane.org/gmane.comp.db.couchdb.user/10845 for more information.

@jasonshah

Yes, that works and feels cleaner. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.