or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aql.mdclient-database.mdcollections.mderrors-types.mdgraphs.mdindex.mdtransactions.md

aql.mddocs/

0

# AQL Query Interface

1

2

Advanced Query Language (AQL) interface for executing complex queries, analyzing performance, managing query cache, and working with user-defined functions. AQL is ArangoDB's SQL-like query language optimized for multi-model data.

3

4

## Capabilities

5

6

### Query Execution

7

8

Execute AQL queries with extensive configuration options, bind parameters, and result cursors for efficient data retrieval.

9

10

```python { .api }

11

class AQL:

12

def execute(self, query: str, count: bool = False, batch_size=None,

13

ttl=None, bind_vars=None, full_count=None, max_plans=None,

14

optimizer_rules=None, cache=None, memory_limit: int = 0,

15

fail_on_warning=None, profile=None, **kwargs) -> Result[Cursor]:

16

"""

17

Execute AQL query.

18

19

Parameters:

20

- query: str, AQL query string

21

- count: bool, return total count

22

- batch_size: int, result batch size

23

- ttl: float, query time-to-live in seconds

24

- bind_vars: dict, bind parameters for query

25

- full_count: bool, return full count even with LIMIT

26

- max_plans: int, maximum optimizer plans to generate

27

- optimizer_rules: list, optimizer rules to apply/disable

28

- cache: bool, use query result cache

29

- memory_limit: int, memory limit in bytes

30

- fail_on_warning: bool, fail on warnings

31

- profile: bool or int, profiling level

32

- **kwargs: additional query options

33

34

Returns:

35

Result[Cursor]: Query result cursor

36

"""

37

```

38

39

### Query Analysis

40

41

Analyze query execution plans, validate query syntax, and optimize query performance.

42

43

```python { .api }

44

def explain(self, query: str, all_plans: bool = False, max_plans=None,

45

opt_rules=None, bind_vars=None) -> Result:

46

"""

47

Explain query execution plan.

48

49

Parameters:

50

- query: str, AQL query to explain

51

- all_plans: bool, return all possible plans

52

- max_plans: int, maximum plans to generate

53

- opt_rules: list, optimizer rules to consider

54

- bind_vars: dict, bind parameters

55

56

Returns:

57

Result[Json|List[Json]]: Execution plan(s)

58

"""

59

60

def validate(self, query: str) -> Result[Json]:

61

"""

62

Validate query syntax.

63

64

Parameters:

65

- query: str, AQL query to validate

66

67

Returns:

68

Result[Json]: Validation result with syntax info

69

"""

70

```

71

72

### Query Management

73

74

Monitor running queries, kill long-running queries, and manage slow query tracking.

75

76

```python { .api }

77

def queries(self) -> Result[List[Json]]:

78

"""

79

List currently running queries.

80

81

Returns:

82

Result[List[Json]]: List of active query information

83

"""

84

85

def kill(self, query_id: str) -> Result[bool]:

86

"""

87

Kill a running query.

88

89

Parameters:

90

- query_id: str, ID of query to terminate

91

92

Returns:

93

Result[bool]: True on success

94

"""

95

96

def slow_queries(self) -> Result[List[Json]]:

97

"""

98

Get slow query log.

99

100

Returns:

101

Result[List[Json]]: List of slow queries

102

"""

103

104

def clear_slow_queries(self) -> Result[bool]:

105

"""

106

Clear slow query log.

107

108

Returns:

109

Result[bool]: True on success

110

"""

111

```

112

113

### Query Tracking

114

115

Configure query tracking settings to monitor performance and identify slow queries.

116

117

```python { .api }

118

def tracking(self) -> Result[Json]:

119

"""

120

Get current query tracking configuration.

121

122

Returns:

123

Result[Json]: Tracking configuration dict

124

"""

125

126

def set_tracking(self, enabled=None, max_slow_queries=None,

127

slow_query_threshold=None, max_query_string_length=None,

128

track_bind_vars=None, track_slow_queries=None) -> Result[Json]:

129

"""

130

Configure query tracking.

131

132

Parameters:

133

- enabled: bool, enable query tracking

134

- max_slow_queries: int, max slow queries to track

135

- slow_query_threshold: int, threshold for slow queries (seconds)

136

- max_query_string_length: int, max query string length to log

137

- track_bind_vars: bool, include bind variables in logs

138

- track_slow_queries: bool, track slow queries

139

140

Returns:

141

Result[Json]: Updated tracking configuration

142

"""

143

```

144

145

### User-Defined Functions

146

147

Create, manage, and execute custom AQL functions to extend query capabilities.

148

149

```python { .api }

150

def functions(self) -> Result[List[Json]]:

151

"""

152

List all user-defined functions.

153

154

Returns:

155

Result[List[Json]]: List of function definitions

156

"""

157

158

def create_function(self, name: str, code: str) -> Result[Json]:

159

"""

160

Create or update user-defined function.

161

162

Parameters:

163

- name: str, function name (namespace::name format)

164

- code: str, JavaScript function code

165

166

Returns:

167

Result[Json]: Function creation result

168

"""

169

170

def delete_function(self, name: str, group: bool = False,

171

ignore_missing: bool = False) -> Result:

172

"""

173

Delete user-defined function.

174

175

Parameters:

176

- name: str, function name or namespace

177

- group: bool, delete entire function group/namespace

178

- ignore_missing: bool, ignore if function doesn't exist

179

180

Returns:

181

Result[Json|bool]: Deletion result

182

"""

183

184

def query_rules(self) -> Result[List[Json]]:

185

"""

186

Get available optimizer rules.

187

188

Returns:

189

Result[List[Json]]: List of optimizer rule information

190

"""

191

```

192

193

### Query Cache

194

195

Manage AQL query result caching to improve performance for repeated queries.

196

197

```python { .api }

198

class AQLQueryCache:

199

def properties(self) -> Result[Json]:

200

"""

201

Get query cache properties.

202

203

Returns:

204

Result[Json]: Cache configuration dict

205

"""

206

207

def configure(self, mode=None, max_results=None, max_results_size=None,

208

max_entry_size=None, include_system=None) -> Result[Json]:

209

"""

210

Configure query cache.

211

212

Parameters:

213

- mode: str, cache mode ('off', 'on', 'demand')

214

- max_results: int, maximum number of cached results

215

- max_results_size: int, maximum cache size in bytes

216

- max_entry_size: int, maximum size per cache entry

217

- include_system: bool, cache system database queries

218

219

Returns:

220

Result[Json]: Updated cache configuration

221

"""

222

223

def entries(self) -> Result[List[Json]]:

224

"""

225

Get cache entries.

226

227

Returns:

228

Result[List[Json]]: List of cached queries

229

"""

230

231

def clear(self) -> Result[bool]:

232

"""

233

Clear query cache.

234

235

Returns:

236

Result[bool]: True on success

237

"""

238

```

239

240

## Usage Examples

241

242

### Basic Query Execution

243

244

```python

245

from arango import ArangoClient

246

247

client = ArangoClient()

248

db = client.db('example', username='root', password='password')

249

250

# Simple query

251

query = "FOR doc IN students RETURN doc"

252

cursor = db.aql.execute(query)

253

students = [doc for doc in cursor]

254

255

# Query with bind parameters

256

query = "FOR s IN students FILTER s.age >= @min_age RETURN s"

257

cursor = db.aql.execute(query, bind_vars={'min_age': 21})

258

adults = list(cursor)

259

260

# Query with options

261

cursor = db.aql.execute(

262

query,

263

count=True, # Include count

264

batch_size=100, # Batch size

265

cache=True, # Use cache

266

memory_limit=1000000 # 1MB memory limit

267

)

268

269

print(f"Total count: {cursor.count()}")

270

```

271

272

### Complex Queries

273

274

```python

275

# JOIN-like operation

276

join_query = """

277

FOR student IN students

278

FOR course IN courses

279

FILTER student.major == course.department

280

RETURN {

281

student_name: student.name,

282

course_name: course.name,

283

credits: course.credits

284

}

285

"""

286

287

# Aggregation query

288

agg_query = """

289

FOR student IN students

290

COLLECT major = student.major

291

AGGREGATE count = LENGTH(1), avg_age = AVERAGE(student.age)

292

RETURN {

293

major: major,

294

student_count: count,

295

average_age: avg_age

296

}

297

"""

298

299

# Graph traversal

300

graph_query = """

301

FOR vertex, edge, path IN 1..3 OUTBOUND 'students/alice' GRAPH 'university'

302

RETURN {

303

vertex: vertex,

304

path_length: LENGTH(path.vertices)

305

}

306

"""

307

308

results = db.aql.execute(agg_query)

309

for result in results:

310

print(f"{result['major']}: {result['student_count']} students")

311

```

312

313

### Query Analysis and Optimization

314

315

```python

316

# Explain query execution plan

317

query = "FOR s IN students FILTER s.age > 21 SORT s.name RETURN s"

318

plan = db.aql.explain(query)

319

print(f"Estimated cost: {plan['plan']['estimatedCost']}")

320

321

# Validate query syntax

322

invalid_query = "FOR s IN students FILTER s.age > RETURN s"

323

validation = db.aql.validate(invalid_query)

324

if not validation['error']:

325

print("Query is valid")

326

else:

327

print(f"Syntax error: {validation['errorMessage']}")

328

329

# Profile query execution

330

cursor = db.aql.execute(query, profile=2) # Detailed profiling

331

profile_data = cursor.profile()

332

print(f"Execution time: {profile_data['executing']}")

333

```

334

335

### User-Defined Functions

336

337

```python

338

# Create custom function

339

function_code = """

340

function(name) {

341

return "Hello, " + name + "!";

342

}

343

"""

344

345

db.aql.create_function('greeting::hello', function_code)

346

347

# Use custom function in query

348

query = "FOR s IN students RETURN greeting::hello(s.name)"

349

cursor = db.aql.execute(query)

350

greetings = list(cursor)

351

352

# List all functions

353

functions = db.aql.functions()

354

for func in functions:

355

print(f"Function: {func['name']}")

356

357

# Delete function

358

db.aql.delete_function('greeting::hello')

359

```

360

361

### Query Tracking and Monitoring

362

363

```python

364

# Configure tracking

365

db.aql.set_tracking(

366

enabled=True,

367

max_slow_queries=100,

368

slow_query_threshold=5, # 5 seconds

369

track_bind_vars=True

370

)

371

372

# Monitor running queries

373

running = db.aql.queries()

374

for query_info in running:

375

print(f"Query {query_info['id']}: {query_info['query'][:50]}...")

376

377

# Check slow queries

378

slow = db.aql.slow_queries()

379

for slow_query in slow:

380

print(f"Slow query took {slow_query['runTime']}s")

381

382

# Kill long-running query

383

if running:

384

db.aql.kill(running[0]['id'])

385

```

386

387

### Query Cache Management

388

389

```python

390

# Configure cache

391

cache = db.aql.cache

392

cache.configure(

393

mode='demand', # Cache on demand

394

max_results=1000, # Max 1000 cached queries

395

max_results_size=64*1024*1024, # 64MB total

396

max_entry_size=1024*1024 # 1MB per entry

397

)

398

399

# Check cache status

400

cache_props = cache.properties()

401

print(f"Cache mode: {cache_props['mode']}")

402

print(f"Cache entries: {len(cache.entries())}")

403

404

# Execute cacheable query

405

query = "FOR s IN students COLLECT age = s.age RETURN {age, count: LENGTH(1)}"

406

cursor = db.aql.execute(query, cache=True)

407

results = list(cursor)

408

409

# Clear cache when needed

410

cache.clear()

411

```

412

413

### Advanced Query Options

414

415

```python

416

# Query with optimizer rules

417

cursor = db.aql.execute(

418

"FOR s IN students FILTER s.age > 21 SORT s.name RETURN s",

419

optimizer_rules=[

420

'+all', # Enable all rules

421

'-sort-limit' # Disable sort-limit rule

422

]

423

)

424

425

# Query with custom memory limit

426

large_query = """

427

FOR s1 IN students

428

FOR s2 IN students

429

FILTER s1._key != s2._key

430

RETURN {s1: s1.name, s2: s2.name}

431

"""

432

433

try:

434

cursor = db.aql.execute(

435

large_query,

436

memory_limit=10*1024*1024, # 10MB limit

437

fail_on_warning=True

438

)

439

results = list(cursor)

440

except Exception as e:

441

print(f"Query failed: {e}")

442

```