Search code examples
stringdynamicarangodbaql

ArangoDB Dynamic AQL String Handler


Is it possible to use the aql string handler in ArangoDB to perform a dynamic query? I've tried a number of different ways but it always errors out. For example, I'd like to do something like this:

let sortExpression = sortByDate ? 'SORT ${date}' : `SORT ${name}`

const result = db._query(aql`
    FOR doc IN tickets
    ${sortExpression}
    RETURN doc
`)

This example is very simplified, but I have a more complex situation where something like this would be really handy. Is there a way to make something like this work?


Solution

  • After looking more closely at how the aql string handler works, it turns out what I'm trying to do is just not feasible with it. So I decided to use the regular bind var syntax:

    let sortExpression = 'SORT @sortField'
    
    const result = db._query(`
        FOR doc IN @@coll
        ${sortExpression}
        RETURN doc
    `, {
        '@coll': module.context.collectionName('tickets'),
        'sortField': sortByDate ? 'date' : 'name'
    })
    

    Again this is overkill for the simple example above, but my real world query is much more complex.