0

I would like to generate a query dynamically in Foxx. The filter statement would be there or not depend on the request parameter. For example

//Conditionally determine if we should include a filter statement here or not
var var1=true;
getAllEntitiesThatSatisfyTheCondition = db._query(aql `
      For u In ${EntityCollection}
      ${var1 ? `Filter u.prop == ${var1}`:``}
      Return DISTINCT u._id
    `).toArray();

This one would return an error about binding value

syntax error, unexpected bind parameter

How can I construct the query using literal template this way in arango, or I have to use query builder?

Loredra L
  • 1,485
  • 2
  • 16
  • 32
  • There are some (not yet unreleased) changes to the ArangoJS driver that should help you, namely the handling of `undefined` (will be omitted instead of generating a bind variable with no value) and nesting support: https://github.com/arangodb/arangojs/blob/master/CHANGELOG.md – CodeManX Oct 18 '18 at 14:08
  • Related: [AQL template in arango Foxx does not work correctly with array](https://stackoverflow.com/questions/52967790/aql-template-in-arango-foxx-does-not-work-correctly-with-array/) (ArangoJS v6.7.0 supports nesting of templates) – CodeManX Oct 25 '18 at 14:28

2 Answers2

2

This works for me on Foxx using Arango 3.3.16:

var test = "1124852" 
const filter = aql.literal(
    test ? `AND v._key == "${test}" ` : ''
  );

then on your query just add

${filter}
camba1
  • 1,795
  • 2
  • 12
  • 18
  • Goes without saying that literals do not validate the parameters, so use with caution and validate properly to avoid injection – camba1 Oct 18 '18 at 16:30
  • When I use your suggestion into the exact query I have above, there is a new problem as "AQL: syntax error, unexpected assignment near..." – Loredra L Oct 19 '18 at 07:34
  • Nevermind, it was the error of using !==. I have accepted your answer – Loredra L Oct 19 '18 at 07:38
0

You can use it like below as well.

var filter = "FILTER a.name=='test'";


var query = `
   for a IN collection1
  "${filter}"
 limit 50
  return a
`;

db._query(query).toArray();

Here the javascript filter variable will be replaced dynamically. Hope this helps.

Sajeev
  • 17
  • 3