1
votes

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?

2

2 Answers

0
votes

If the query was more complex, and I had real variables to embed, I'd write this like the following:

let sortProp = sortByDate ? 'date' : 'name';

var query = aql`
    FOR doc IN tickets
       SORT @SORT_PROP@
       RETURN doc`;
query.query = query.query.replace('@SORT_PROP@', sortProp);
var result = db._query(query);

Maybe this works for your use case, too.

0
votes

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.