or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-manipulation.mddatabase-management.mdindex.mdquerying-filtering.mdutility-functions.md

querying-filtering.mddocs/

0

# Querying and Filtering

1

2

Powerful query system with SQL-like filtering capabilities, supporting complex conditions, operator combinations, and chainable query refinement.

3

4

## Capabilities

5

6

### Basic Querying

7

8

Query the database by calling it as a function with filter conditions.

9

10

```javascript { .api }

11

/**

12

* Query the database with filter conditions

13

* @param filter - Filter object, function, or record ID

14

* @returns QueryResult for further operations

15

*/

16

(filter?: object | function | string): QueryResult;

17

```

18

19

**Usage Examples:**

20

21

```javascript

22

// Get all records

23

const allUsers = db();

24

25

// Filter by simple equality

26

const activeUsers = db({ active: true });

27

28

// Filter by multiple conditions (AND logic)

29

const youngActiveUsers = db({ active: true, age: { lt: 30 } });

30

31

// Filter by record ID

32

const specificUser = db("T000001R000002");

33

34

// Filter with custom function

35

const customFilter = db(function() {

36

return this.name.startsWith('A') && this.age > 25;

37

});

38

```

39

40

### Filter Operators

41

42

Comprehensive set of operators for precise data matching and comparison.

43

44

```javascript { .api }

45

// Available operators in filter objects

46

interface FilterOperators {

47

is?: any; // Exact equality (===)

48

eq?: any; // Loose equality (==)

49

like?: string; // Contains substring (case-sensitive)

50

likenocase?: string; // Contains substring (case-insensitive)

51

left?: string; // Starts with string

52

leftnocase?: string; // Starts with string (case-insensitive)

53

right?: string; // Ends with string

54

rightnocase?: string; // Ends with string (case-insensitive)

55

lt?: number; // Less than

56

lte?: number; // Less than or equal

57

gt?: number; // Greater than

58

gte?: number; // Greater than or equal

59

ne?: any; // Not equal (!=)

60

regex?: RegExp; // Regular expression match

61

has?: any; // Contains value (for arrays/objects)

62

hasall?: any[]; // Contains all values

63

isnocase?: string; // Case-insensitive equality

64

contains?: any; // Array contains value

65

}

66

```

67

68

**Usage Examples:**

69

70

```javascript

71

// Exact equality

72

const user1 = db({ id: { is: 1 } });

73

74

// String matching

75

const nameContains = db({ name: { like: "John" } });

76

const nameStartsWith = db({ name: { left: "Dr." } });

77

const nameEndsWith = db({ name: { right: "Jr." } });

78

79

// Case-insensitive matching

80

const caseInsensitive = db({ email: { likenocase: "GMAIL" } });

81

82

// Numeric comparisons

83

const adults = db({ age: { gte: 18 } });

84

const seniors = db({ age: { gt: 65 } });

85

const youngAdults = db({ age: { gte: 18, lt: 30 } });

86

87

// Regular expressions

88

const emailPattern = db({ email: { regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ } });

89

90

// Array operations

91

const hasSkill = db({ skills: { contains: "JavaScript" } });

92

const hasAllSkills = db({ skills: { hasall: ["JavaScript", "React"] } });

93

94

// Negation (prefix with !)

95

const notActive = db({ active: { '!is': true } });

96

const notContains = db({ name: { '!like': "test" } });

97

```

98

99

### Complex Filtering

100

101

Combine multiple conditions with logical operators and nested queries.

102

103

```javascript { .api }

104

// Logical OR using arrays

105

database([condition1, condition2, condition3]): QueryResult;

106

107

// Custom filter functions

108

database(function(): boolean): QueryResult;

109

```

110

111

**Usage Examples:**

112

113

```javascript

114

// OR logic with arrays

115

const seniorOrVIP = db([

116

{ age: { gte: 65 } },

117

{ vip: true }

118

]);

119

120

// Complex OR conditions

121

const multipleRoles = db([

122

{ role: "admin" },

123

{ role: "manager" },

124

{ permissions: { contains: "write" } }

125

]);

126

127

// Custom function filters

128

const complexLogic = db(function() {

129

const hasValidEmail = this.email && this.email.includes('@');

130

const isActive = this.active === true;

131

const hasRecentActivity = new Date(this.lastLogin) > new Date('2023-01-01');

132

133

return hasValidEmail && isActive && hasRecentActivity;

134

});

135

136

// Combining function filters with chaining

137

const filtered = db(function() {

138

return this.department === 'Engineering';

139

}).filter(function() {

140

return this.salary > 75000;

141

});

142

```

143

144

### Query Refinement

145

146

Chain additional filters and sorting to refine query results.

147

148

```javascript { .api }

149

/**

150

* Apply additional filtering to existing query results

151

* @param filterObj - Additional filter conditions

152

* @returns New QueryResult with combined filters

153

*/

154

filter(filterObj: object | function): QueryResult;

155

156

/**

157

* Sort query results by specified columns

158

* @param orderString - Sort specification (e.g., "name desc, age")

159

* @returns New QueryResult with applied sorting

160

*/

161

order(orderString: string): QueryResult;

162

163

/**

164

* Limit the number of results returned

165

* @param count - Maximum number of records to return

166

* @returns New QueryResult with limited results

167

*/

168

limit(count: number): QueryResult;

169

170

/**

171

* Set starting offset for results (1-based indexing)

172

* @param offset - Starting record number

173

* @returns New QueryResult with offset applied

174

*/

175

start(offset: number): QueryResult;

176

```

177

178

**Usage Examples:**

179

180

```javascript

181

// Chain multiple filters

182

const result = db({ department: "Sales" })

183

.filter({ active: true })

184

.filter({ performance: { gte: 4.0 } });

185

186

// Apply sorting

187

const sorted = db({ active: true })

188

.order("salary desc, name");

189

190

// Pagination with limit and start

191

const page2 = db({ active: true })

192

.order("name")

193

.start(11) // Start from 11th record (1-based)

194

.limit(10); // Return 10 records

195

196

// Complex query chain

197

const complexQuery = db({ department: "Engineering" })

198

.filter({ salary: { gte: 80000 } })

199

.filter(function() { return this.skills.length >= 3; })

200

.order("experience desc, salary desc")

201

.limit(5);

202

```

203

204

### Record ID Queries

205

206

Query by specific record IDs or arrays of IDs for direct record access.

207

208

```javascript { .api }

209

// Query by single record ID

210

database(recordId: string): QueryResult;

211

212

// Query by array of record IDs

213

database(recordIds: string[]): QueryResult;

214

```

215

216

**Usage Examples:**

217

218

```javascript

219

// Query by single record ID

220

const specificRecord = db("T000001R000005");

221

222

// Query by multiple record IDs

223

const multipleRecords = db([

224

"T000001R000002",

225

"T000001R000007",

226

"T000001R000010"

227

]);

228

229

// Record IDs are automatically generated in format: T{dbId}R{recordId}

230

// You can get record IDs from query results:

231

const users = db({ active: true }).get();

232

users.forEach(user => {

233

console.log('Record ID:', user.___id);

234

});

235

```

236

237

### Query Context and Caching

238

239

TaffyDB automatically caches query results for performance optimization.

240

241

```javascript { .api }

242

// Query context information (internal)

243

interface QueryContext {

244

limit: number | false; // Result limit

245

start: number | false; // Starting offset

246

q: function[]; // Applied filters

247

filterRaw: any[]; // Raw filter input

248

index: any[]; // Index conditions

249

order: string[]; // Sort order

250

results: object[] | false; // Cached results

251

run: Date | null; // Last execution time

252

sort: Date | null; // Last sort time

253

}

254

```

255

256

**Performance Notes:**

257

258

```javascript

259

// Queries are cached automatically

260

const query1 = db({ active: true });

261

const results1 = query1.get(); // Executes query

262

263

const query2 = db({ active: true });

264

const results2 = query2.get(); // Uses cached results (if unchanged)

265

266

// Cache is invalidated on database modifications

267

db.insert({ name: "New User", active: true });

268

const results3 = query2.get(); // Re-executes query (cache invalidated)

269

270

// Function-based filters disable caching

271

const uncached = db(function() { return Math.random() > 0.5; });

272

```